forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathChaedie.py
42 lines (36 loc) ยท 956 Bytes
/
Chaedie.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
"""
๊ฐ์ฅ ๋ค๋ถํฐ ๋์์ค๋ ๋ฐฉ๋ฒ์ ์ฐพ์์ผํ๋ค.
1) ์ฌ๊ท ์คํ ๋ฐฉ์
2) ์๋ก์ด ๋ฆฌ์คํธ๋ฅผ ๋ง๋๋ ๋ฐฉ๋ฒ
3) two pointer ๋ก ๋ฐ ์๋ผ์ reverse ํ ๋ค merge
"""
"""
Solution: 3) Two pointer
Time: O(n)
Space: O(1)
"""
class Solution:
def reorderList(self, head: Optional[ListNode]) -> None:
# ์ ๋ฐ ์๋ฅด๊ธฐ
slow, fast = head, head.next
while fast and fast.next:
slow = slow.next
fast = fast.next.next
# Reverse
second = slow.next
slow.next = None
prev = None
while second:
tmp = second.next
second.next = prev
prev = second
second = tmp
# Merge
first = head
second = prev
while second:
tmp1, tmp2 = first.next, second.next
first.next = second
second.next = tmp1
first = tmp1
second = tmp2