Floyd’s Cycle Finding Algorithm
https://leetcode.com/problems/linked-list-cycle/description/
Given head
, the head of a linked list, determine if the linked list has a cycle in it.
- Initialize Two Pointers:
- Create two pointers,
slow
andfast
, and set slow to the head of the linked list and fast to the next of the head.
- Create two pointers,
- Traverse the Linked List:
- Start a loop where the
slow
pointer moves one step at a time, and thefast
pointer moves two steps at a time.
- Start a loop where the
- Check for a Cycle:
- In each iteration, check if the
slow
andfast
pointers meet. If they do, it indicates the presence of a cycle in the linked list.
- In each iteration, check if the
- Termination Conditions:
- If the
fast
pointer reaches the end of the linked list (i.e.,fast
orfast.next
isNone
), there is no cycle, and the algorithm terminates.
- If the
- Return Result:
- If a cycle is found, return
True
. Otherwise, returnFalse
.
- If a cycle is found, return
public boolean hasCycle(ListNode head) {
if(head == null)
return false;
ListNode slow = head;
ListNode fast = head.next;
while(slow != fast){
if(fast == null || fast.next == null){
return false;
}
slow = slow.next;
fast = fast.next.next;
}
return true;
}
Time Complexity: O(n)
Space Complexity: O(1)
https://leetcode.com/problems/linked-list-cycle-ii/description/
Given the head
of a linked list, return the node where the cycle begins. If there is no cycle, return null
.
public ListNode detectCycle(ListNode head) {
if(head == null){
return null;
}
ListNode slow = head;
ListNode fast = head.next;
while(slow != fast){
if(fast == null || fast.next == null){
return null;
}
slow = slow.next;
fast = fast.next.next;
}
slow = head;
fast = fast.next;
while(slow != fast){
slow = slow.next;
fast = fast.next;
}
return slow;
}