leetcode143

 1 class Solution:
 2     def reorderList(self, head: ListNode) -> None:
 3         """
 4         Do not return anything, modify head in-place instead.
 5         """
 6         if not head:
 7             return
 8         aux = self.findmid(head)
 9         new_head = self.reverse(aux.next)
10         aux.next = None
11         l, r = head, new_head
12         while l and r:
13             l_next = l.next
14             r_next = r.next
15             l.next = r
16             r.next = l_next
17             l = l_next
18             r = r_next
19         
20     def findmid(self, head):
21         if not head:
22             return
23         fast = slow = head
24         while fast and fast.next:
25             fast = fast.next.next
26             slow = slow.next  
27         return slow
28     def reverse(self, head):
29         if not head:
30             return None
31         pre = None
32         while head:
33             tmp = head.next
34             head.next = pre
35             pre = head
36             head = tmp
37         return pre

To find the list of the intermediate node, the intermediate node from the list and then divided into two.

The second half of the nodes in reverse order. Node is then selected in turn from two joined the list.

Reference: https://leetcode.com/problems/reorder-list/discuss/447242/python-solution

Guess you like

Origin www.cnblogs.com/asenyang/p/12021878.html