forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpmjuu.py
37 lines (33 loc) ยท 1.07 KB
/
pmjuu.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
'''
์๊ฐ ๋ณต์ก๋: O(n)
- ์ค๊ฐ ๋
ธ๋ ์ฐพ๊ธฐ: O(n)
- ๋ฆฌ์คํธ ๋ฐ์ : O(n)
- ๋ฆฌ์คํธ ๋ณํฉ: O(n)
๊ณต๊ฐ ๋ณต์ก๋: O(1)
- ํฌ์ธํฐ๋ง ์ฌ์ฉํ์ฌ ๋งํฌ๋ฅผ ์กฐ์ํ๋ฏ๋ก O(1)
'''
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:
"""
Do not return anything, modify head in-place instead.
"""
# find the middle node
slow, fast = head, head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
# reverse back half of the list
prev, curr = None, slow.next
slow.next = None # cut in the middle
while curr:
curr.next, prev, curr = prev, curr, curr.next
# merge front half with back half
first, second = head, prev
while second:
first.next, second.next, first, second = second, first.next, first.next, second.next