Given a singly linked list L: L0→L1→…→Ln-1→Ln,
reorder it to: L0→Ln→L1→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}
.
/**
* 解题思路:
* 1.将整个链表一分为二,左子链和右子链;
* 2.翻转右子链;
* 3.合并左右子链。
*
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode findMiddle( ListNode head ){
ListNode slow = head;
ListNode quick = head.next;
while( quick!=null && quick.next!=null ){
slow = slow.next;
quick = quick.next.next;
}
return slow;
}
private ListNode reverseList(ListNode head) {
ListNode newHead = null;
while (head != null) {
ListNode temp = head.next;
head.next = newHead;
newHead = head;
head = temp;
}
return newHead;
}
public void reorderList(ListNode head) {
if( head==null )
return;
ListNode left = null;
left = head;
ListNode right = null;
ListNode mid = findMiddle(head);
right = reverseList(mid.next);
mid.next = null;
head = new ListNode(0);
ListNode tail = head;
while( left!=null && right!=null ){
tail.next = left;
left = left.next;
tail = tail.next;
tail.next = right;
right = right.next;
tail = tail.next;
}
if( left!=null ){
tail.next = left;
left.next = null;
tail = null;
left = null;
}
}
}