-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path143-ReorderList.py
118 lines (93 loc) · 3 KB
/
143-ReorderList.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
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
# 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.
1. Find the middle node
2. Get the next head pointer of the middle node
3. Reverse the rest of the head in the 2.
4. Merge two linked lists
"""
mid_head = self.findMid(head)
reversed_right_part_list = self.reverseList(mid_head)
return self.mergeTwoLists(head, reversed_right_part_list)
def mergeTwoLists(self, head1, head2):
p = dummy = ListNode()
p1 = head1
p2 = head2
count = 0
while p1 and p2:
if count % 2 == 0:
p.next = p1
p1 = p1.next
p = p.next
else:
p.next = p2
p2 = p2.next
p = p.next
count += 1
return dummy.next
def reverseList(self, head):
if head is None or head.next is None: return head
reversed_list = self.reverseList(head.next)
head.next.next = head
head.next = None
return reversed_list
def findMid(self, head):
slow = head
fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
return slow
class Solution2:
def reorderList(self, head: Optional[ListNode]) -> None:
"""
Do not return anything, modify head in-place instead.
1. Find the middle node
2. Get the next head pointer of the middle node
3. Reverse the rest of the head in the 2.
4. Merge two linked lists
"""
mid_head = self.findMid(head)
right_part_head = mid_head.next
mid_head.next = None
reversed_right_part_list = self.reverseList(right_part_head)
return self.mergeTwoLists(head, reversed_right_part_list)
def mergeTwoLists(self, head1, head2):
p = dummy = ListNode()
p1 = head1
p2 = head2
count = 0
while p1 and p2:
if count % 2 == 0:
p.next = p1
p1 = p1.next
p = p.next
else:
p.next = p2
p2 = p2.next
p = p.next
count += 1
if p1 is None:
p.next = p2
else:
p.next = p1
return dummy.next
def reverseList(self, head):
if head is None or head.next is None: return head
reversed_list = self.reverseList(head.next)
head.next.next = head
head.next = None
return reversed_list
def findMid(self, head):
slow = head
fast = head
while fast and fast.next and fast.next.next:
slow = slow.next
fast = fast.next.next
return slow