Skip to content

Instantly share code, notes, and snippets.

@wayetan
Created December 24, 2013 10:39
Show Gist options
  • Save wayetan/8111496 to your computer and use it in GitHub Desktop.
Save wayetan/8111496 to your computer and use it in GitHub Desktop.
Linked List Cycle
/**
* Given a linked list, determine if it has a cycle in it.
*/
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution{
public boolean hasLoop(ListNode head){
ListNode slow = head, fast = head;
while(slow != null && fast != null && fast.next != null){
slow = slow.next;
fast = fast.next.next;
if(slow == fast)
return true;
}
return false;
}
}
/**
* Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
*/
public class Solution{
public ListNode detectCycle(ListNode head) {
// The slow pointer advances one node at a time, while the fast pointer
// traverses twice as fast. If the list has loop in it, eventually the
// fast and slow pointer will meet at the same node. On the other hand,
// if the loop has no loop, the fast pointer will reach the end of list
// before the slow pointer does.
if(head == null || head.next == null || head.next.next == null)
return null;
ListNode slow = head.next;
ListNode fast = head.next.next;
while(slow != fast){
if(fast.next == null || fast.next.next == null)
return null;
slow = slow.next;
fast = fast.next.next;
}
// If the program runs here, which means there is a loop, now advance
// one pointer to the head, and make them move in the same speed.
// When they meet again, it has to be the loop start point.
slow = head; // or fast = head
while(slow != fast){
slow = slow.next;
fast = fast.next;
}
return slow;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment