Skip to content

Commit 8692ab2

Browse files
committed
feat: Add Solution to Linked List Cycle #225
1 parent 84105a9 commit 8692ab2

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

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

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
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+
# ํ”Œ๋กœ์ด๋“œ ํ† ๋ผ์™€ ๊ฑฐ๋ถ์ด ์•Œ๊ณ ๋ฆฌ์ฆ˜
10+
# ๋А๋ฆฐ ํฌ์ธํ„ฐ์™€ ๋น ๋ฅธ ํฌ์ธํ„ฐ, ์‚ฌ์ดํด์ด ์žˆ๋‹ค๋ฉด
11+
# ๋А๋ฆฐ ํฌ์ธํ„ฐ๋ฅผ ๋น ๋ฅธ ํฌ์ธํ„ฐ๊ฐ€ ๋”ฐ๋ผ ์žก์•„
12+
# ์–ธ์  ๊ฐ€ ๊ฐ™์€ ๋…ธ๋“œ์—์„œ ๋งŒ๋‚˜๊ฒŒ ๋  ๊ฒƒ
13+
# TC: O(N)
14+
# SC: O(1)
15+
# ๋ฆฌ์ŠคํŠธ๊ฐ€ ๋น„์–ด ์žˆ๊ฑฐ๋‚˜ ๋…ธ๋“œ๊ฐ€ ํ•˜๋‚˜๋ฟ์ด๋ฉด ์‚ฌ์ดํด X
16+
if not head or not head.next:
17+
return False
18+
19+
slow = head # ๋А๋ฆฐ ํฌ์ธํ„ฐ
20+
fast = head # ๋น ๋ฅธ ํฌ์ธํ„ฐ
21+
22+
while fast is not None and fast.next is not None: # fast์™€ fast.next ๋ชจ๋‘ ์œ ํšจํ•ด์•ผ fast.next.next ์ ‘๊ทผ ๊ฐ€๋Šฅ
23+
slow = slow.next # ๋А๋ฆฐ ํฌ์ธํ„ฐ ํ•œ ์นธ ์ด๋™
24+
fast = fast.next.next # ๋น ๋ฅธ ํฌ์ธํ„ฐ ํ•œ ์นธ ์ด๋™
25+
26+
if slow == fast: # ๋‘ ํฌ์ธํ„ฐ๊ฐ€ ๋งŒ๋‚œ๋‹ค๋ฉด
27+
return True # ์‚ฌ์ดํด ์กด์žฌ
28+
29+
# ๋ฃจํ”„๊ฐ€ ๋๋‚ฌ๋‹ค๋ฉด ํฌ์ธํ„ฐ๊ฐ€ ๋ฆฌ์ŠคํŠธ ๋์— ๋„๋‹ฌํ•œ ๊ฒƒ์ด๋ฏ€๋กœ ์‚ฌ์ดํด X
30+
return False

0 commit comments

Comments
ย (0)