Skip to main content

141. Linked List Cycle

https://leetcode.com/problems/linked-list-cycle

Python

Floyd's Tortoise and Hare Algorithm

class Solution:
def hasCycle(self, head: Optional[ListNode]) -> bool:
slow, fast = head, head
is_first = True

while is_first or slow != fast:
is_first = False

if not fast or not fast.next:
return False
slow = slow.next
fast = fast.next.next

return True

Javascript

var hasCycle = function(head) {  
var slow = head;
var fast = head;

while (fast !== null && fast.next !== null) {
slow = slow.next;
fast = fast.next.next;

if (slow === fast) return true;
}
return false;
};