Created
September 29, 2015 02:40
-
-
Save adamblank/99df033c21d4fb198bbf 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
public class Node { | |
protected String data; | |
protected Node next; | |
public Node(final String data, final Node next) { | |
this.data = data; | |
this.next = next; | |
} | |
public Node getNext() { | |
return next; | |
} | |
public void setNext(final Node next) { | |
this.next = next; | |
} | |
public String getData() { | |
return this.data; | |
} | |
public static boolean isThereLoop(final Node head) throws Exception { | |
boolean stop = false; | |
boolean tick = false; | |
Node fast_current = head; | |
Node slow_current = head; | |
int count = 0; | |
while (!stop || count > 10000) { | |
fast_current = fast_current.getNext(); | |
if (tick) { | |
slow_current = slow_current.getNext(); | |
} | |
if (fast_current == null) { | |
return false; | |
} else if (fast_current.equals(slow_current)) { | |
return true; | |
} | |
tick = !tick; | |
count++; | |
} | |
throw new Exception("failure!!!"); | |
} | |
public static void main(String[] args) { | |
//setup linked list | |
final Node head = new Node("head", null); | |
final Node next1 = new Node("1", null); | |
head.setNext(next1); | |
final Node next2 = new Node("2", null); | |
next1.setNext(next2); | |
final Node next3 = new Node("3", null); | |
next2.setNext(next3); | |
final Node next4 = new Node("4", null); | |
next3.setNext(next4); | |
next4.setNext(next2); // the loop! | |
try { | |
System.out.println(isThereLoop(head)); | |
} catch (Exception e) { | |
System.out.println("There was a problem"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment