forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmangodm-web.py
45 lines (35 loc) ยท 1.33 KB
/
mangodm-web.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
43
44
45
from typing import Optional
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def reorderList(self, head: Optional[ListNode]) -> None:
"""
- Idea:
์ฐ๊ฒฐ ๋ฆฌ์คํธ๋ฅผ ๋ฐ์ผ๋ก ๋๋๊ณ , ๋ค์ชฝ(๋๋ฒ์งธ ๋ฆฌ์คํธ)์ ์ฐ๊ฒฐ ๋ฐฉํฅ์ ๋ฐ๋๋ก ๋ค์ง๋๋ค.
์ฒซ๋ฒ์งธ ๋ฆฌ์คํธ์ ๋๋ฒ์งธ ๋ฆฌ์คํธ์ ๋
ธ๋๋ฅผ ๋ฒ๊ฐ์๊ฐ๋ฉฐ ์ฐ๊ฒฐํ๋ค.
- Time Complexity: O(n). n์ ์ ์ฒด ๋
ธ๋์ ์
๋ฆฌ์คํธ๋ฅผ ํ์ํ๊ณ ๋ณํฉํ๋ ๋ฐ ๊ฑธ๋ฆฌ๋ ์๊ฐ์ ๋น๋กํ๋ค.
- Space Complexity: O(1)
๋ช ๊ฐ์ ํฌ์ธํฐ๋ฅผ ์ฌ์ฉํ๋ ์์ ๊ณต๊ฐ๋ง ์ฐจ์งํ๋ค.
"""
slow, fast = head, head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
mid = slow.next
slow.next = None
prev, cur = None, mid
while cur:
next_temp = cur.next
cur.next = prev
prev = cur
cur = next_temp
first, second = head, prev
while second:
first_next, second_next = first.next, second.next
first.next = second
second.next = first_next
first, second = first_next, second_next