-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathreorder-list.py
More file actions
49 lines (39 loc) · 1.29 KB
/
reorder-list.py
File metadata and controls
49 lines (39 loc) · 1.29 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
from typing import Optional
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.
"""
def find_mid(head):
fast = slow = head
while fast.next and fast.next.next:
fast = fast.next.next
slow = slow.next
return slow
def reverse(head):
first, second = None, head
while second:
third = second.next
second.next = first
first, second = second, third
return first
def weave(left, right):
head = curr = left
while right:
curr_next = curr.next
curr.next = right
right, left = curr_next, right.next
curr = curr.next
return head
if head.next == None: return head
dummy_head = ListNode(0, head)
mid = find_mid(dummy_head)
left = head
right = mid.next
mid.next = None
right = reverse(right)
weave(left, right)