码迷,mamicode.com
首页 > 其他好文 > 详细

143. Reorder List

时间:2019-04-09 16:52:33      阅读:130      评论:0      收藏:0      [点我收藏+]

标签:for   bsp   ring   linked   val   out   with   this   public   

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

class Solution {
    public void reorderList(ListNode head) {
        if (head == null || head.next == null)
            return;
        //找到链表的中点,如1 2 3 4 5 6 7 8,则p1是4
        ListNode p1 = head;
        ListNode p2 = head;
        while (p2.next != null && p2.next.next != null) {
            p1 = p1.next;
            p2 = p2.next.next;
        }
        
      //链表后半边逆序,5 6 7 8 变成 8 7 6 5 
        ListNode preMiddle = p1; //preMiddle 是4
        ListNode preCur = p1.next; //preCur 是5
        while (preCur.next != null) {
            ListNode cur = preCur.next; //cur是6
            preCur.next = cur.next; //5->7
            cur.next = preMiddle.next; //6->5
            preMiddle.next = cur; //4->6
        }
        //达到最后排序目的
        p1 = head;
        p2 = preMiddle.next;
        while (p1 != preMiddle) {
            preMiddle.next = p2.next; //另4->7
            p2.next = p1.next; //8->2
            p1.next = p2;//1->8
            p1 = p2.next;//让p1等于2
            p2 = preMiddle.next; //p2等于7,现在链表1 8 2 3 4 7 6 5
        }
        
    }
}

143. Reorder List

标签:for   bsp   ring   linked   val   out   with   this   public   

原文地址:https://www.cnblogs.com/MarkLeeBYR/p/10677654.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!