-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path0143.Reorder_List.py
More file actions
77 lines (59 loc) Β· 1.84 KB
/
0143.Reorder_List.py
File metadata and controls
77 lines (59 loc) Β· 1.84 KB
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
"""
You are given the head of a singly linked-list. The list can be represented as:
L0 β L1 β β¦ β Ln - 1 β Ln
Reorder the list to be on the following form:
L0 β Ln β L1 β Ln - 1 β L2 β Ln - 2 β β¦
You may not modify the values in the list's nodes. Only nodes themselves may be changed.
Example 1:
Input: head = [1,2,3,4]
Output: [1,4,2,3]
Example 2:
Input: head = [1,2,3,4,5]
Output: [1,5,2,4,3]
Constraints:
The number of nodes in the list is in the range [1, 5 * 104].
1 <= Node.val <= 1000
"""
# 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.
"""
if not head or not head.next:
return head
#1.get mid value, then seperate it to 2 part
slow, fast = head, head.next
while fast and fast.next:
slow = slow.next
fast = fast.next.next
right_head = slow.next
slow.next = None
#2. reverse second part
prev, curr = None, right_head
while curr:
temp = curr.next
curr.next = prev
prev = curr
curr = temp
right_head = prev
#3. connect the 1st and 2nd half
dummy = ListNode(-1)
curr = dummy
left, right = head, right_head
while left and right:
curr.next = left
left = left.next
curr = curr.next
curr.next = right
right = right.next
curr = curr.next
if left:
curr.next = left
if right:
curr.next = right
return dummy.next