forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy paththispath98.py
31 lines (27 loc) ยท 1011 Bytes
/
thispath98.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
class Solution:
def reorderList(self, head: Optional[ListNode]) -> None:
"""
Intuition:
nodes ๋ฆฌ์คํธ์ ๋ชจ๋ ๋
ธ๋๋ฅผ ์ ์ฅํ๋ค.
ํ์ฌ ๋
ธ๋๊ฐ -i - 1๋ฒ์งธ ๋
ธ๋์ผ ๋,
ํ์ฌ ๋
ธ๋์ next๋ head์ next๋ก ์ค์ ํ๊ณ ,
head์ next๋ ํ์ฌ ๋
ธ๋๋ก ์ค์ ํ๋ค.
์ดํ ๋ง์ง๋ง์ ์ค๊ฐ์ ์๋ ๋
ธ๋๋ฅผ None์ผ๋ก ์ค์ ํ๋ค.
Time Complexity:
O(N):
๋ชจ๋ ๋
ธ๋๋ฅผ ์ํํ๋ฏ๋ก O(N)์ด๋ค.
Space Complexity:
O(N):
๋ชจ๋ ๋
ธ๋๋ฅผ nodes ๋ฆฌ์คํธ์ ์ ์ฅํ๋ฏ๋ก O(N)์ด๋ค.
"""
nodes = []
node = head
while node:
nodes.append(node)
node = node.next
for i in range((len(nodes) - 1) // 2):
cur = nodes[-i - 1]
cur.next = head.next
head.next = cur
head = cur.next
nodes[len(nodes) // 2].next = None