Skip to content

Commit 4659042

Browse files
committed
solve(w11): 143. Reorder List
1 parent 6867e83 commit 4659042

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

reorder-list/seungriyou.py

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
# https://leetcode.com/problems/reorder-list/
2+
3+
from typing import Optional
4+
5+
# Definition for singly-linked list.
6+
class ListNode:
7+
def __init__(self, val=0, next=None):
8+
self.val = val
9+
self.next = next
10+
11+
class Solution:
12+
def reorderList(self, head: Optional[ListNode]) -> None:
13+
"""
14+
Do not return anything, modify head in-place instead.
15+
"""
16+
"""
17+
[Complexity]
18+
- TC: O(n)
19+
- SC: O(1)
20+
21+
[Approach]
22+
1. linked-list의 중간 지점을 찾은 후, left / right list를 나눈다.
23+
2. right list를 reverse 한다.
24+
3. left와 right에서 노드를 하나씩 가져와 연결한다.
25+
"""
26+
27+
# linked-list의 중간 지점을 찾은 후, left / right list 나누기
28+
slow = fast = head
29+
while fast and fast.next:
30+
slow = slow.next # -> fast가 linked-list의 끝에 도달하면, slow는 중앙에 위치
31+
fast = fast.next.next
32+
33+
# (slow부터 시작하는) right list를 reverse (w. 다중 할당)
34+
prev, curr = None, slow
35+
while curr:
36+
curr.next, prev, curr = prev, curr, curr.next
37+
38+
# left와 right list에서 노드를 각각 하나씩 가져와 연결 (w. 다중 할당)
39+
left, right = head, prev
40+
while right.next:
41+
left.next, left = right, left.next
42+
right.next, right = left, right.next

0 commit comments

Comments
 (0)