Skip to content

Instantly share code, notes, and snippets.

@cloudbank
Last active October 3, 2017 01:19
Show Gist options
  • Save cloudbank/582e13d77a8aebac5b3364b3ee0fa50b to your computer and use it in GitHub Desktop.
Save cloudbank/582e13d77a8aebac5b3364b3ee0fa50b to your computer and use it in GitHub Desktop.
Finding cycle start in SLL is often presented wrong it its implementation, in fact even published. It is a simple mistake, but the correct version is a rare find as a result.
//see https://stackoverflow.com/questions/2936213/explain-how-finding-cycle-start-node-in-cycle-linked-list-work/42615373#42615373
public Node whereLoopBegins(Node head) {
Node slow = head;
Node fast = head;
// collide them at loopsize - K , K = k % loopsize
while (fast != null && fast.next != null && fast.next.next != null) {
slow = slow.next;
fast = fast.next.next;
if (slow == fast) { // there is a cycle, but slow and fast may have
// met at head due to a 0 length start to loop
int cLength = 0;
do {
++cLength;
} while (slow != fast);
fast = head;
while (cLength-- > 0) {
fast = fast.next;
}
slow = head;
while (fast != slow) {
fast = fast.next;
slow = slow.next;
}
return slow;
}
}
return null;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment