Created
May 3, 2018 19:23
-
-
Save xnorcode/05b8261f7b323d30be494f2e31ba69b0 to your computer and use it in GitHub Desktop.
Linked List Check For Cycle
This file contains 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 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