Reorder List

Given a singly linked list L: L0 → L1 → … → Ln-1 → Ln

reorder it to: L0 → Ln → L1 → Ln-1 → L2 → Ln-2 → …

Example

Given 1->2->3->4->null, reorder it to 1->4->2->3->null.

分析



首先使用快慢指针找到list的中间数
1->2->3->4->null返回的2
1->2->3->4->5->null返回的3
1->2->3->4->5->6->null返回的3
可以使用 Middle of Linked List 中的函数

然后将中间数的后面的 ListNode 反序

之后挨个合并就是
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/**
 * Definition for ListNode.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int val) {
 *         this.val = val;
 *         this.next = null;
 *     }
 * }
 */ 
public class Solution {
    /**
     * @param head: The head of linked list.
     * @return: void
     */
    public void reorderList(ListNode head) {  
        // write your code here
        if(head == nullreturn;
        // find mid node
        ListNode slow = head, fast = head;
        while(fast != null && fast.next != null){
            slow = slow.next;
            fast = fast.next.next;
        }
        // reverse the right half list
        ListNode pos2 = reorder(slow.next);
        ListNode pos1 = head;
        slow.next = null;
         
        // combine the two list to one
        ListNode dummy = new ListNode(0);
        ListNode pos = dummy;
        boolean sign = false;
        while(pos2 != null){
            pos.next = sign ? pos2 : pos1;
             
            if(sign)
                pos2 = pos2.next;
            else
                pos1 = pos1.next;
                 
            pos = pos.next;
            sign = !sign;
        }
        pos.next = pos1;
    }
     
    public ListNode reorder(ListNode head){
        ListNode dummy = null;
        ListNode pos = dummy;
        ListNode next = head;
        while(next != null){
            ListNode tmp = next.next;
            next.next = pos;
            pos = next;
            next = tmp;
        }
        return pos;
    }
}




posted @ 2017-02-14 16:52  copperface  阅读(232)  评论(0编辑  收藏  举报