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 5b01c43 commit 6cab591Copy full SHA for 6cab591
linked-list-cycle/devyejin.py
@@ -0,0 +1,35 @@
1
+# Definition for singly-linked list.
2
+class ListNode:
3
+ def __init__(self, x):
4
+ self.val = x
5
+ self.next = None
6
+
7
+from typing import Optional
8
9
+# time complexity O(n)
10
+# space complexity O(1)
11
+class Solution:
12
+ def hasCycle(self, head: Optional[ListNode]) -> bool:
13
+ slow, fast = head, head
14
+ while fast and fast.next:
15
+ slow = slow.next
16
+ fast = fast.next.next
17
18
+ if slow == fast:
19
+ return True
20
+ return False
21
22
23
24
+# space complexity O(n)
25
+# class Solution:
26
+# def hasCycle(self, head: Optional[ListNode]) -> bool:
27
+# visited = set()
28
+# while head:
29
+# if head in visited:
30
+# return True
31
+# visited.add(head)
32
+# head = head.next
33
+# return False
34
35
0 commit comments