Leetcode 143. Reorder List

Given a singly linked list L: L0L1→…→Ln-1Ln,
reorder it to: L0LnL1Ln-1L2Ln-2→…

You must do this in-place without altering the nodes' values.

For example,
Given {1,2,3,4}, reorder it to {1,4,2,3}.

 

思路:

1. 用快慢pointer取mid

2. 翻转后半截list.

3. 合并前后两段list。

 

注意1. mid的位置,比如 list = [1, 2, 3, 4, 5], mid =3。list = [1, 2, 3, 4] mid =2。

 

 1 # Definition for singly-linked list.
 2 # class ListNode(object):
 3 #     def __init__(self, x):
 4 #         self.val = x
 5 #         self.next = None
 6 
 7 class Solution(object):
 8     def reorderList(self, head):
 9         """
10         :type head: ListNode
11         :rtype: void Do not return anything, modify head in-place instead.
12         """
13         if not head or not head.next or not head.next.next:
14             return
15         
16         slow = fast = head
17         while fast.next and fast.next.next:
18             fast = fast.next.next
19             slow = slow.next
20         mid = slow
21         
22         left = head
23         right = mid.next
24         if right is None:
25             return
26         mid.next = None
27         
28         cursor = right.next
29         right.next = None
30         while cursor:
31             next = cursor.next
32             cursor.next = right
33             right = cursor
34             cursor = next
35         
36         dummy = ListNode(0)
37         while left or right:
38             if left is not None:
39                 dummy.next = left
40                 left = left.next
41                 dummy = dummy.next
42             if right is not None:
43                 dummy.next = right
44                 right = right.next
45                 dummy = dummy.next
46 
47         

 

posted @ 2017-02-20 13:01  lettuan  阅读(120)  评论(0编辑  收藏  举报