***143. Reorder List 重排链表

1. 原始题目

给定一个单链表 LL0→L1→…→Ln-1→Ln ,
将其重新排列后变为: L0→LnL1→Ln-1→L2→Ln-2→…

你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。

示例 1:

给定链表 1->2->3->4, 重新排列为 1->4->2->3.

示例 2:

给定链表 1->2->3->4->5, 重新排列为 1->5->2->4->3.

2. 思路

这道题不难,但是考察的点比较多。包括快慢指针、反转链表等知识。

给定一个链表,如果可以找到其中点位置,然后将链表一分为二。后半部分进行反转,之后将这两个链表依次链接就可以,例子如下:

1-2-3-4-5-6-7-8-9

中点是5,那按照中点一份为2:1-2-3-4-5和6-7-8-9。将后半部分反转:9-8-7-6。然后依次链接;两个链表(1-2-3-4-5)和(9-8-7-6)就得到:

1-9-2-8-3-7-4-6-5。

额外要注意的是链表的结点数的奇偶性。纸上画图就一目了然了。

3. 解题

 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 or not head.next or not head.next.next:return None
 7         temp = head
 8         p,q = head, head.next
 9 
10         while(q and q.next):          # 快慢指针
11             p = p.next
12             q = q.next.next
13         k = p.next                    # 以k开头的后半部分链表 
14         p.next = None                 # 以head开头的前半部分链表  
15         
16         head2 = self.reverseList(k)   # 翻转后半部分链表
17         pp,kk = temp.next, head2.next      # 依次连接两个链表
18         while(temp and head2):   
19             temp.next = head2
20             head2.next = pp
21             temp = pp
22             if temp:
23                 pp = temp.next
24                 temp.next = kk
25             head2 = kk
26             if head2:
27                 kk = head2.next
28 #        return head
29 
30     def reverseList(self,head):     # 递归反转链表
31         if not head or not head.next:return head
32         next = head.next
33         newhead = self.reverseList(next)
34         next.next = head
35         head.next = None
36         return newhead

 

posted @ 2019-05-11 10:52  三年一梦  阅读(289)  评论(0)    收藏  举报