Skip to content

Instantly share code, notes, and snippets.

@chrislukkk
Created June 26, 2014 01:47
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 chrislukkk/f452d108f42cc6a52110 to your computer and use it in GitHub Desktop.
Save chrislukkk/f452d108f42cc6a52110 to your computer and use it in GitHub Desktop.
CareerCup_2.6 - Find Cycle Start
package Chapter2;
public class LoopStartFinder {
public static <T> Node<T> findLoopStart(MyLinkedList<T> list) {
if (list == null || list.head == null || list.head.next == null)
return null;
Node<T> fir = list.head.next.next;
Node<T> sec = list.head.next;
//first time meet use runner tech
while (fir != null && sec != null) {
if (fir == sec) {
break;
}
if (fir.next == null)
return null;
fir = fir.next.next;
sec = sec.next;
}
fir = list.head;
//second time meet
while (fir != sec) {
fir = fir.next;
sec = sec.next;
}
return fir;
}
public static void main(String[] args) {
Node<String> cycleHead = new Node<String>("A", new Node<String>("B",
new Node<String>("C", new Node<>("D", new Node<>("E", null)))));
MyLinkedList<String> list = new MyLinkedList<String>(cycleHead);
list.last().next = list.head.next.next;
Node<String> loopStart = findLoopStart(list);
System.out.println("loop start is " + loopStart.data);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment