Skip to content

Commit d7c2369

Browse files
committed
solve 2
1 parent 1620e94 commit d7c2369

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

reorder-list/pmjuu.py

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
'''
2+
시간 복잡도: O(n)
3+
- 중간 노드 찾기: O(n)
4+
- 리스트 반전: O(n)
5+
- 리스트 병합: O(n)
6+
7+
공간 복잡도: O(1)
8+
- 포인터만 사용하여 링크를 조작하므로 O(1)
9+
'''
10+
from typing import Optional
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+
"""
20+
Do not return anything, modify head in-place instead.
21+
"""
22+
# find the middle node
23+
slow, fast = head, head
24+
while fast and fast.next:
25+
slow = slow.next
26+
fast = fast.next.next
27+
28+
# reverse back half of the list
29+
prev, curr = None, slow.next
30+
slow.next = None # cut in the middle
31+
while curr:
32+
curr.next, prev, curr = prev, curr, curr.next
33+
34+
# merge front half with back half
35+
first, second = head, prev
36+
while second:
37+
first.next, second.next, first, second = second, first.next, first.next, second.next

0 commit comments

Comments
 (0)