Circular linked list

Given a linked list, determine whether there are rings in the list.

If there is a node in the list that can be reached again by continuously tracing the next pointer, there is a loop in the list. To represent the loop in a given list, we use the integer POS to represent where the end of the list is joined into the list (the index starts at 0). If pos is -1, there are no rings in the list. Note: POS is not passed as a parameter, only to identify the actual condition of the linked list.

Returns true if there is a loop in the list. Otherwise, return false.

For details, see the LeetCode official website.

Source: LeetCode link:… Copyright belongs to collar network. Commercial reprint please contact the official authorization, non-commercial reprint please indicate the source.

Solution 1: Remove the Set weight

First, return false if head is null or if head has only one node.

(5) The application of the HashSet appeared. (5) The application of the HashSet appeared. (5) The application of the HashSet appeared.

  • (5) Return false (5) Return false (5) Return false (5) Return false (5) If true is returned, the node does not exist and the loop continues to the next node.
  • At the end of the loop, return false if no loop exists.
import java.util.HashSet; import java.util.Set; public class LeetCode_141 { public static boolean hasCycle(ListNode head) { if (head == null || == null) { return false; } Set<ListNode> appeared = new HashSet<>(); while (head ! = null) { if (! appeared.add(head)) { return true; } head =; } return false; } public static void main(String[] args) { ListNode head = new ListNode(1); = new ListNode(2); System.out.println(hasCycle(head)); }}

[Daily Message]
Do not love the world flashy, do not write the world of mortals, do not sigh desolate, do not provoke love and sorrow.