Skip to content

Instantly share code, notes, and snippets.

@jingz8804
Created March 15, 2014 22:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jingz8804/9574773 to your computer and use it in GitHub Desktop.
Save jingz8804/9574773 to your computer and use it in GitHub Desktop.
// in this context, we've already know that the list has cycle
// suppose there is a class Node
// public class Node<Item>{
// Item item;
// Node next;
// }
// import the Node class here;
public class DetectCycleStartInList{// I wish I could use a better name :)
public Node detect(Node head){
if (head == null) return null;
Node slowRunner = head; // move at rate 1
Node fastRunner = head; // move at rate 2
while(true){
fastRunner = fastRunner.next.next;
slowRunner = slowRunner.next;
if (slowRunner == fastRunner) break;
}
while(true){
slowRunner = slowRunner.next;
head = head.next;
if (slowRunner == head) break;
}
return slowRunner;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment