Skip to content

Commit ed3d0a8

Browse files
committed
Add #0141 Linked List Cycle
1 parent f830afa commit ed3d0a8

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

#0141 Linked List Cycle.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
from typing import Optional
2+
3+
class ListNode:
4+
def __init__(self, x):
5+
self.val = x
6+
self.next = None
7+
8+
class Solution:
9+
def hasCycle(self, head: Optional[ListNode]) -> bool:
10+
"""
11+
Detect if a linked list has a cycle in it.
12+
13+
Parameters:
14+
head (Optional[ListNode]): The head of the singly linked list.
15+
16+
Returns:
17+
bool: True if there is a cycle in the linked list, False otherwise.
18+
"""
19+
slow = head
20+
fast = head
21+
22+
while fast and fast.next:
23+
slow = slow.next # Move slow pointer by one step
24+
fast = fast.next.next # Move fast pointer by two steps
25+
26+
if slow == fast: # Cycle detected if slow and fast pointers meet
27+
return True
28+
29+
return False # No cycle found

0 commit comments

Comments
 (0)