143. Reorder List

Given a singly linked list LL0→L1→…→Ln-1→Ln,
reorder it to: L0→LnL1→Ln-1→L2→Ln-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}.

 

本题可以看做是Reverse Linked List 2的进一步复杂态,本题的解题思路是

若链表为1 2 3 4 5 6 7 8 9

1. 寻找链表的中间元素

2. 将链表的后半段反序(利用Reverse Linked List 2的概念)

3. 新得的链表1 2 3 4 5 9 8 7 6. 则对链表重新排序即可(亦利用Reverse Linked List 2,将后半段链表中的元素逐个插入到前半段,9插入到1,2之间;8插入到2,3之间......)

在解题时,由于遗失移动位的后一位进行了长时间的debug

因此,应该注意

1.如果移除链表的某一位,必须线保存其后一位

2.如果在链表的某一位进行添加,先保存其后一位

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public void reorderList(ListNode head) {
        
        if (head==null||head.next==null) return;
        
        ListNode p1 = head;
        ListNode p2 = head;
        while(p2.next != null && p2.next.next != null) {
            p1 = p1.next;
            p2 = p2.next.next;
        }
        
        ListNode pre = p1;
        ListNode curr = p1.next;
        ListNode middle = p1;
        while(curr.next != null) {
            ListNode then = curr.next;
            curr.next = then.next;
            then.next = pre.next;
            pre.next = then;
            then = curr.next;
        }
        
        ListNode start = head;
        ListNode move = middle.next;
        while(start != middle) {
            middle.next = move.next;
            move.next = start.next;
            start.next = move;
            start = move.next;
            move = middle.next;
        }
        
    }
}

  

posted @ 2016-02-24 17:49  Ray.Yang  阅读(182)  评论(0编辑  收藏  举报