Skip to content

Commit 080179d

Browse files
committed
- Linked List Cycle #225
1 parent 14d8c3b commit 080179d

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

linked-list-cycle/ayosecu.py

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
from typing import Optional
2+
3+
# Definition for singly-linked list.
4+
class ListNode:
5+
def __init__(self, x):
6+
self.val = x
7+
self.next = None
8+
9+
class Solution:
10+
"""
11+
- Time Complexity: O(n), n = The number of nodes
12+
- Space Complexity: O(1)
13+
"""
14+
def hasCycle(self, head: Optional[ListNode]) -> bool:
15+
if not head:
16+
return False
17+
18+
slow, fast = head, head
19+
while slow and fast:
20+
slow = slow.next
21+
if fast.next:
22+
fast = fast.next.next
23+
else:
24+
return False
25+
26+
if fast == slow:
27+
return True
28+
29+
return False
30+
31+
# Run Test Cases
32+
def do_test():
33+
sol = Solution()
34+
35+
h1 = ListNode(3)
36+
h1.next = ListNode(2)
37+
h1.next.next = ListNode(0)
38+
h1.next.next = ListNode(-4)
39+
h1.next.next.next = h1.next
40+
r1 = sol.hasCycle(h1)
41+
print(f"TC 1 is Passed!" if r1 == True else f"TC 1 is Failed!")
42+
43+
h2 = ListNode(1)
44+
h2.next = ListNode(2)
45+
h2.next.next = h2
46+
r2 = sol.hasCycle(h2)
47+
print(f"TC 2 is Passed!" if r2 == True else f"TC 2 is Failed!")
48+
49+
h3 = ListNode(1)
50+
r3 = sol.hasCycle(h3)
51+
print(f"TC 3 is Passed!" if r3 == False else f"TC 3 is Failed!")
52+
53+
do_test()

0 commit comments

Comments
 (0)