Skip to content

Commit 64cc659

Browse files
committed
feat: add reorder list solution
1 parent 73411d4 commit 64cc659

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

โ€Žreorder-list/mangodm-web.py

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
from typing import Optional
2+
3+
4+
# Definition for singly-linked list.
5+
class ListNode:
6+
def __init__(self, val=0, next=None):
7+
self.val = val
8+
self.next = next
9+
10+
11+
class Solution:
12+
def reorderList(self, head: Optional[ListNode]) -> None:
13+
"""
14+
- Idea:
15+
์—ฐ๊ฒฐ ๋ฆฌ์ŠคํŠธ๋ฅผ ๋ฐ˜์œผ๋กœ ๋‚˜๋ˆ„๊ณ , ๋’ค์ชฝ(๋‘๋ฒˆ์งธ ๋ฆฌ์ŠคํŠธ)์˜ ์—ฐ๊ฒฐ ๋ฐฉํ–ฅ์„ ๋ฐ˜๋Œ€๋กœ ๋’ค์ง‘๋Š”๋‹ค.
16+
์ฒซ๋ฒˆ์งธ ๋ฆฌ์ŠคํŠธ์™€ ๋‘๋ฒˆ์งธ ๋ฆฌ์ŠคํŠธ์˜ ๋…ธ๋“œ๋ฅผ ๋ฒˆ๊ฐˆ์•„๊ฐ€๋ฉฐ ์—ฐ๊ฒฐํ•œ๋‹ค.
17+
- Time Complexity: O(n). n์€ ์ „์ฒด ๋…ธ๋“œ์˜ ์ˆ˜
18+
๋ฆฌ์ŠคํŠธ๋ฅผ ํƒ์ƒ‰ํ•˜๊ณ  ๋ณ‘ํ•ฉํ•˜๋Š” ๋ฐ ๊ฑธ๋ฆฌ๋Š” ์‹œ๊ฐ„์— ๋น„๋ก€ํ•œ๋‹ค.
19+
- Space Complexity: O(1)
20+
๋ช‡ ๊ฐœ์˜ ํฌ์ธํ„ฐ๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ์ƒ์ˆ˜ ๊ณต๊ฐ„๋งŒ ์ฐจ์ง€ํ•œ๋‹ค.
21+
"""
22+
slow, fast = head, head
23+
24+
while fast and fast.next:
25+
slow = slow.next
26+
fast = fast.next.next
27+
28+
mid = slow.next
29+
slow.next = None
30+
31+
prev, cur = None, mid
32+
33+
while cur:
34+
next_temp = cur.next
35+
cur.next = prev
36+
prev = cur
37+
cur = next_temp
38+
39+
first, second = head, prev
40+
41+
while second:
42+
first_next, second_next = first.next, second.next
43+
first.next = second
44+
second.next = first_next
45+
first, second = first_next, second_next

0 commit comments

Comments
ย (0)