Reorder List


//t 牵引拔出元素cur.next,后面的位置,为后面连起来用
// p2 牵引将要插入元素后面的位置,为后面连起来用
public void reorderList(ListNode head) {
        if(head==null || head.next==null || head.next.next==null) return;
        ListNode walk = head, run  = head, cur = head;
        
        while(run.next!=null&&run.next.next!=null){ 
            run = run.next.next;
            walk = walk.next;
        }
         
        reverse(walk);
        ListNode half = walk.next;
        walk.next = null;
        while(half!=null){
            ListNode h2 = half.next;
            half.next = cur.next;
            cur.next = half;
            half = h2;
            cur = cur.next.next;
        }
    }
    public void reverse(ListNode pr){
        if(pr==null || pr.next ==null) return ;
        ListNode cur=pr.next;
         while(cur.next!=null){
            ListNode t = cur.next.next; //牵引拔出元素后面的位置
            ListNode p2 = pr.next; // 牵引插入元素后面的位置
            pr.next=cur.next;
            pr.next.next = p2;
            cur.next = t;
        }  
    }

 

posted @ 2015-04-09 12:51  世界到处都是小星星  阅读(155)  评论(0编辑  收藏  举报