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

先找到链表的中间节点,然后从中间节点将链表一分为二。

将后半部分的节点倒序。然后轮流从两个链表中选择节点连接在一起。

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

posted on 2019-12-11 13:04  Sempron2800+  阅读(139)  评论(0编辑  收藏  举报