Skip to content

Instantly share code, notes, and snippets.

@xnorcode
Created May 3, 2018 19:23
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 xnorcode/05b8261f7b323d30be494f2e31ba69b0 to your computer and use it in GitHub Desktop.
Save xnorcode/05b8261f7b323d30be494f2e31ba69b0 to your computer and use it in GitHub Desktop.
Linked List Check For Cycle
public class LinkedList<T> {
// Reference to the head node
Node head;
public boolean hasCycle(){
// check if list empty
if(head == null) return false;
// create slow and fast nodes
Node slow, fast;
slow = fast = head;
// iterate list
while(true){
// get next node
// slow pointer iterates the list node by node
slow = slow.next;
// check if end of the list
if(fast.next == null) return false;
// get reference of a next node always skipping one
fast = fast.next.next;
// check if end of the list
if(fast == null) return false;
// if there is a cycle then the fast and slow
// pointers will meet at some point.
if(fast.equals(slow)) return true;
}
}
...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment