Skip to content

Commit cc9a4d6

Browse files
committed
weeok 09 solution linked-list-cycle
1 parent 1937d70 commit cc9a4d6

1 file changed

Lines changed: 36 additions & 0 deletions

File tree

linked-list-cycle/HYUNAHKO.py

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
# Definition for singly-linked list.
2+
# class ListNode:
3+
# def __init__(self, x):
4+
# self.val = x
5+
# self.next = None
6+
7+
class Solution:
8+
def hasCycle(self, head: Optional[ListNode]) -> bool:
9+
visited = set()
10+
11+
current = head
12+
while current:
13+
if current in visited:
14+
return True
15+
16+
visited.add(current)
17+
current = current.next
18+
19+
return False
20+
21+
# w/o set()
22+
class Solution:
23+
def hasCycle(self, head: Optional[ListNode]) -> bool:
24+
if not head or not head.next:
25+
return False
26+
27+
slow = head
28+
fast = head.next
29+
30+
while slow != fast:
31+
if not fast or not fast.next:
32+
return False
33+
slow = slow.next
34+
fast = fast.next.next
35+
36+
return True

0 commit comments

Comments
 (0)