Skip to content

Commit 05eab5e

Browse files
committed
LeetCode-141: Linked List Cycle(Floyd’s Tortoise and Hare Algorithm)
1 parent 01dc7e0 commit 05eab5e

1 file changed

Lines changed: 7 additions & 5 deletions

File tree

prep/practice/linked_list.py

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -48,10 +48,12 @@ def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) ->
4848
return dummy.next
4949

5050
def hasCycle(self, head: Optional[ListNode]) -> bool:
51-
seen = set()
52-
while head:
53-
if head in seen:
51+
tortoise, hare = head, head
52+
53+
while hare and hare.next:
54+
tortoise = tortoise.next
55+
hare = hare.next.next
56+
if tortoise == hare:
5457
return True
55-
seen.add(head)
56-
head = head.next
58+
5759
return False

0 commit comments

Comments
 (0)