Skip to content

Instantly share code, notes, and snippets.

@nij4t
Last active August 8, 2020 15:47
Show Gist options
  • Save nij4t/cda617f66ea7dcf22bf07390985299d1 to your computer and use it in GitHub Desktop.
Save nij4t/cda617f66ea7dcf22bf07390985299d1 to your computer and use it in GitHub Desktop.
O(1) Space
// Use two pointers, walker and runner.
// walker moves step by step. runner moves two steps at time.
// if the Linked List has a cycle walker and runner will meet at some
// point.
public boolean hasCycle(ListNode head) {
if(head==null) return false;
ListNode walker = head;
ListNode runner = head;
while(runner.next!=null && runner.next.next!=null) {
walker = walker.next;
runner = runner.next.next;
if(walker==runner) return true;
}
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment