Created
February 14, 2013 16:06
-
-
Save charlespunk/4953805 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Given a circular linked list, implement an algorithm which returns the node at the begining of the loop. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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