Similar Problem:
Given head, the head of a linked list, determine if the linked list has a cycle in it.
Input: head = [3,2,0,-4], pos = 1
Output: true
Use a slow and fast pointer
- if they meet each, there exists a cycle
- otherwise, false
Time: O(n)
Space: O(1)
public boolean hasCycle(ListNode head) {
ListNode slow = head, fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if (slow == fast)
return true;
}
return false;
}