forked from wuduhren/leetcode-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreorder-list.py
More file actions
37 lines (31 loc) · 1.01 KB
/
reorder-list.py
File metadata and controls
37 lines (31 loc) · 1.01 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
class Solution:
def reorderList(self, head: Optional[ListNode]) -> None:
#find the middle point
slow = head
fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
middle = slow.next
#reverse the linked list after the middle point
middle = self.reverseList(middle)
#separate the linked list before the middle
slow.next = None
#merge two linked list
node = head
while middle and node:
nextNode = node.next
node.next = middle
middle = middle.next
node.next.next = nextNode
node = nextNode
return head
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
pre = None
node = head
while node:
nextNode = node.next
node.next = pre
if not nextNode: return node
pre = node
node = nextNode