[leedcode 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}.

/**
 * 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) {
        //本题注意将slow和fast划分成两个链表时,注意最后一个节点的处理,下面的算法是两个表公用了一个尾节点
        //也可以把两个尾节点都置null
        //本题需要针对节点个数的奇偶分别进行考虑,举例子!!
        if(head==null||head.next==null||head.next.next==null) return;
        ListNode fast=head;
        ListNode slow=head;
        while(fast!=null&&fast.next!=null){
            fast=fast.next.next;
            slow=slow.next;
        }
        fast=head;
        ListNode head2=reverse(slow);//reverse slow list
        ListNode head2last=head2; //merge slow and head
        while(fast!=head2last&&fast.next!=head2last){
            head2last=head2.next;
            head2.next=fast.next;
            fast.next=head2;
            fast=head2.next;
            head2=head2last;
        }
        return;
    }
    public ListNode reverse(ListNode node){
        ListNode pre=node;
        ListNode last=null;
        while(node!=null){
            pre=node.next;
            node.next=last;
            last=node;
            node=pre;
        }
        return last;
    }
}

 

posted @ 2015-07-26 22:57  ~每天进步一点点~  阅读(115)  评论(0编辑  收藏  举报