Last active
August 8, 2020 15:47
-
-
Save nij4t/cda617f66ea7dcf22bf07390985299d1 to your computer and use it in GitHub Desktop.
O(1) Space
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
// 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