leetCode练习(143)

题目:Reorder List

难度:medium

问题描述:

Given a singly linked list L: L0L1→…→Ln-1Ln,
reorder it to: L0LnL1Ln-1L2Ln-2→…

You may not modify the values in the list's nodes, only nodes itself may be changed.

Example 1:

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

Example 2:

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

求解思路:

  step1.找到后半段的链表(4-5)
  step2.翻转链表 1-2-3-5-4
  step3.插入

代码如下:

public static 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 middlePoint = p1;//中间节点(偏左)
        //翻转middlePoint后面的节点
        ListNode p = middlePoint.next;
        middlePoint.next = null;
        while(p!=null){
        	ListNode t = p;
        	p = p.next;
        	t.next = middlePoint.next;
        	middlePoint.next = t;
        }
        //将middlePoint插到前面去
        p = head;
        ListNode tail = middlePoint.next;
        middlePoint.next = null;
        while(tail!=null){
        	ListNode t = tail;
        	tail = tail.next;
        	t.next = p.next;
        	p.next = t;
        	p = t.next;
        }
    }


你可能感兴趣的:(leetCode)