Skip to content

Commit 8089c42

Browse files
committed
feat: [Week 09-1] solve linked list cycle
1 parent df919d5 commit 8089c42

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

โ€Žlinked-list-cycle/Chaedie.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
"""
2+
Solution:
3+
1) ์‚ฌ์ดํด์ด ์žˆ๋‹ค๋ฉด ๋ฌดํ•œ ๋ฃจํ”„๊ฐ€ ๋ฐœ์ƒํ• ๊ฒƒ์ด๋‹ค.
4+
2) ์‚ฌ์ดํด์ด ์—†๋‹ค๋ฉด ์–ธ์  ๊ฐ€ null ์ด ๋ ๊ฒƒ์ด๋‹ค.
5+
3) ๋”ฐ๋ผ์„œ ๋‘๊ฐœ์˜ ํฌ์ธํ„ฐ๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ๋™์ผํ•œ Node์— ๋„๋‹ฌํ•˜๋Š” ์ง€ ํ™•์ธํ•œ๋‹ค.
6+
4) null ์ด ๋œ๋‹ค๋ฉด ์‚ฌ์ดํด์ด ์—†๋‹ค๋Š” ๋œป์ด๋‹ค.
7+
Time: O(n)
8+
Space: O(1)
9+
"""
10+
11+
12+
class Solution:
13+
def hasCycle(self, head: Optional[ListNode]) -> bool:
14+
if not head or not head.next:
15+
return False
16+
17+
slow = head
18+
fast = head.next
19+
while slow and fast and fast.next:
20+
slow = slow.next
21+
fast = fast.next.next
22+
if slow == fast:
23+
return True
24+
return False

0 commit comments

Comments
ย (0)