Skip to content

Instantly share code, notes, and snippets.

@charlespunk
Created February 14, 2013 16:06
Show Gist options
  • Save charlespunk/4953805 to your computer and use it in GitHub Desktop.
Save charlespunk/4953805 to your computer and use it in GitHub Desktop.
Given a circular linked list, implement an algorithm which returns the node at the begining of the loop.
/*
3 4 5 5
4 1
1 2 3 4 5 6 7 8 9 0
*/
public static Node findBeginningOfCircle(Node root){
Node fast = root;
Node slow = root;
while(fast != null && slow != null){
fast = fast.next;
slow = slow.next;
if(fast != null) fast = fast.next;
if(fast == slow) break;
}
if(fast == null || slow == null) return null;
slow = root;
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