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}
.
Difficulty: Medium
/**
* 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 || head.next.next == null) return;
ListNode ans = head;
int count = 0; ListNode curr = head;
while(curr != null){
count++;
curr = curr.next;
}
curr = head;
ListNode pre = head, next = null;
for(int i = 0; i < count/2 + count%2; i++){
pre = curr;
curr = curr.next;
}
pre.next = null;
pre = curr; next = curr.next; curr.next = null;
while(next != null){
curr = next;
next = curr.next;
curr.next = pre;
pre = curr;
}
ListNode headNext = null;
ListNode currNext = null;
while(curr != null){
headNext = head.next;
currNext = curr.next;
head.next = curr;
curr.next = headNext;
head = headNext;
curr = currNext;
}
head = ans;
return;
}
}