Skip to content

Commit 0483b52

Browse files
committed
solve(w09): 141. Linked List Cycle
1 parent d033c2a commit 0483b52

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

linked-list-cycle/seungriyou.py

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
# https://leetcode.com/problems/linked-list-cycle/
2+
3+
from typing import Optional
4+
5+
# Definition for singly-linked list.
6+
class ListNode:
7+
def __init__(self, x):
8+
self.val = x
9+
self.next = None
10+
11+
class Solution:
12+
def hasCycle_on(self, head: Optional[ListNode]) -> bool:
13+
"""
14+
[Complexity]
15+
- TC: O(n)
16+
- SC: O(n)
17+
18+
[Approach]
19+
hash table로 visited 노드를 기록한다.
20+
"""
21+
curr = head
22+
visited = set()
23+
24+
while curr:
25+
if curr in visited:
26+
return True
27+
28+
visited.add(curr)
29+
curr = curr.next
30+
31+
return False
32+
33+
def hasCycle(self, head: Optional[ListNode]) -> bool:
34+
"""
35+
[Complexity]
36+
- TC: O(n)
37+
- SC: O(1)
38+
39+
[Approach]
40+
Floyd’s Cycle Detection 알고리즘을 사용한다.
41+
linked list에서 slow (1칸씩 전진) & fast (2칸씩 전진) runner를 이용하면,
42+
- slow와 fast가 만난다면 cyclic
43+
- 만나지 않은 채로 fast가 끝에 도달하면 not cyclic
44+
이다.
45+
"""
46+
slow = fast = head
47+
48+
while fast and fast.next:
49+
slow = slow.next
50+
fast = fast.next.next
51+
52+
if slow == fast:
53+
return True
54+
55+
return False

0 commit comments

Comments
 (0)