Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
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
// get next node
// slow pointer iterates the list node by node
slow =;
// check if end of the list
if( == null) return false;
// get reference of a next node always skipping one
fast =;
// 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