Given head, the head of a linked list, determine if the linked list has a cycle in it.
LeetCode-141: 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. Internally, pos
is used to denote the index of the node that tail’s next pointer is connected to. Note that pos is not passed as a parameter.
Return true
if there is a cycle in the linked list. Otherwise, return false
.
This is a very common question and we’ll be using Floyd’s Cycle Detection Algorithm to solve this. The algorithm uses two pointers, commonly referred to as the slow and the fast. Here’s a quick summary of how it works:
Here is a java implementation of the algorithm:
public boolean hasCycle(ListNode head) {
// if blank list or a single node
if(null == head || null == head.next){
return false;
}
// initialize to the start of list
ListNode fast = head;
ListNode slow = fast;
// while there are more nodes to process
while(null != fast.next){
// move fast one step forward
fast = fast.next;
// if not the end of list
if(null != fast.next){
// move fast one step ahead (again)
// now fast is 2 steps ahead
fast = fast.next;
// move slow 1 step ahead
slow = slow.next;
}
// if pointing to same node
if(slow == fast){
return true;
}
}
// else i.e. end of list is reached
// return false
return false;
}
The algorithm efficiently detects cycles with a time complexity of \(O(n)\).
Be notified of new posts. Subscribe to the RSS feed.