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 || head.next == null) {
return;
}
ListNode p1 = head, p2 = head;
while (p2.next != null && p2.next.next != null) {
p1 = p1.next;
p2 = p2.next.next;
}
ListNode prevMid = p1, curr = p1.next;
while (curr.next != null) {
ListNode temp = curr.next;
curr.next = temp.next;
temp.next = prevMid.next;
prevMid.next = temp;
}
p1 = head;
p2 = prevMid.next;
while (p1 != prevMid) {
prevMid.next = p2.next;
p2.next = p1.next;
p1.next = p2;
p1 = p2.next;
p2 = prevMid.next;
}
}
}