-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path143-Reorder-List.py
35 lines (32 loc) · 1.03 KB
/
143-Reorder-List.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
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def reorderList(self, head):
\\\
:type head: Optional[ListNode]
:rtype: None Do not return anything, modify head in-place instead.
\\\
if not head or not head.next:
return
# Step 1: Find the middle of the list
slow, fast = head, head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
# Step 2: Reverse the second half of the list
prev, curr = None, slow
while curr:
temp = curr.next
curr.next = prev
prev = curr
curr = temp
# Step 3: Merge the two halves
first, second = head, prev
while second.next:
temp1, temp2 = first.next, second.next
first.next = second
second.next = temp1
first, second = temp1, temp2