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

``````/**
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int x) { val = x; }
* }
*/
public class Solution {

while(p2.next!=null && p2.next.next!=null){
p1 = p1.next;
p2 = p2.next.next;
}
//then p1 indicate the medium
//reverse after the medium
// 1->2->3->4->5->6 to 1->2->3->6->5->4
ListNode preMid = p1;
ListNode preCur = p1.next;

//preMid.next indicate the head, cur connect with the preMid.next
while(preCur.next!=null){
ListNode cur = preCur.next;
preCur.next = cur.next;
}

p2 = preMid.next;
while(p1!=preMid){
p2.next = p1.next;
p1.next = p2;
p1 = p2.next;
p2 = preMid.next;
}

}
}
``````

``````/**
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int x) { val = x; }
* }
*/
public class Solution {
//find the medium
while(fast.next!=null && fast.next.next!=null){
slow = slow.next;
fast = fast.next.next;
}

//reverse after the medium
ListNode prev = null, cur = slow.next;

while(cur!=null){
ListNode next = cur.next;
cur.next = prev;
slow.next = cur;
prev = cur;
cur = next;
}

ListNode first = head, second = slow.next;
slow.next = null;
while(first!=null && second!=null){
ListNode fNext = first.next;
ListNode sNext = second.next;
first.next = second;
second.next = fNext;
first = fNext;
second = sNext;
}
}
}
``````