Back to Linked List
Easy
Linked List Cycle
Given `head`, the head of a linked list, determine if the linked list has a cycle in it. There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the `next` pointer. Return `true` if there is a cycle, and `false` otherwise.
Examples
Input:head = [3,2,0,-4], pos = 1 (where tail connects to)
Output:true
There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed).
Input:head = [1], pos = -1
Output:false
There is no cycle in the linked list.
Constraints
The number of the nodes in the list is in the range [0, 10^4].-10^5 <= Node.val <= 10^5
Approach
Traverse the linked list and store each visited node in a Hash Set. Before adding a node, check if it already exists in the set. If it does, there is a cycle. If we reach the end of the list (null), there is no cycle.
Complexity Analysis
Time Complexity
O(n)
Space Complexity
O(n)
This approach requires O(n) extra space to store the nodes in the hash set.
Solution.java
class Solution { public boolean hasCycle(ListNode head) { Set<ListNode> visited = new HashSet<>(); while (head != null) { if (visited.contains(head)) { return true; } visited.add(head); head = head.next; } return false; }}