We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent f830afa commit ed3d0a8Copy full SHA for ed3d0a8
#0141 Linked List Cycle.py
@@ -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