Skip to content

Commit c5bf746

Browse files
committed
reorder-list solution (py)
1 parent 1eec0e9 commit c5bf746

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

β€Žreorder-list/hi-rachel.pyβ€Ž

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
"""
2+
μŠ€νƒμ— λͺ¨λ“  μ›μ†Œκ°€ μ €μž₯λ˜μ–΄ μžˆλ‹€λ©΄, λ²ˆκ°ˆμ•„ κ°€λ©΄μ„œ, ν•œ λ²ˆμ€ λ§ν¬λ“œ λ¦¬μŠ€νŠΈμ—μ„œ λ…Έλ“œλ₯Ό μ–»κ³ ,
3+
ν•œ λ²ˆμ€ μŠ€νƒμ—μ„œ μ›μ†Œλ₯Ό μ–»λŠ”λ‹€λ©΄, L[0] β†’ L[n - 1] β†’ L[1] β†’ L[n - 2] β†’ L[2] β†’ L[n - 3] β†’ … 순으둜 λ…Έλ“œμ— μ ‘κ·Όν•  수 μžˆμ„ 것
4+
5+
TC: O(n)
6+
SC: O(n)
7+
"""
8+
9+
from typing import Optional
10+
11+
# Definition for singly-linked list.
12+
class ListNode:
13+
def __init__(self, val=0, next=None):
14+
self.val = val
15+
self.next = next
16+
17+
class Solution:
18+
def reorderList(self, head: Optional[ListNode]) -> None:
19+
stack = []
20+
node = head
21+
# μ—°κ²° 리슀트의 λͺ¨λ“  λ…Έλ“œλ₯Ό stack에 μ €μž₯
22+
while node:
23+
stack.append(node)
24+
node = node.next
25+
26+
node = dummy = ListNode(-1)
27+
for i in range(len(stack)):
28+
if i % 2:
29+
node.next = stack.pop() # ν™€μˆ˜ 인덱슀: λ’€μ—μ„œλΆ€ν„° 꺼냄
30+
else:
31+
node.next = head # 짝수 인덱슀: μ•žμ—μ„œλΆ€ν„° κ°€μ Έμ˜΄
32+
head = head.next
33+
node = node.next
34+
node.next = None
35+
return dummy.next

0 commit comments

Comments
Β (0)