143. Reorder List
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}.
/**
* 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) {
if(head == null) return ;
ListNode p = head;
ListNode q = head.next;
while(q != null && q.next != null){
p = p.next;
q = q.next;
if(q != null) q = q.next;
}
q = p.next;
p.next = null;
ListNode newHead = null;
while(q != null){
ListNode tmp = q.next;
q.next = newHead;
newHead = q;
q = tmp;
}
p = head;
q = newHead;
ListNode dummy = new ListNode(-1);
ListNode tail = dummy;
while(p != null || q != null){
if(p != null){
tail.next = p;
p = p.next;
tail = tail.next;
}
if(q!= null){
tail.next = q;
q = q.next;
tail = tail.next;
}
}
head = dummy.next;
}
}