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}
.
Subscribe to see which companies asked this question.
/**
* 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 slow = head;
ListNode fast = head.next;
while (fast != null) {
slow = slow.next;
if (fast.next == null)
break;
fast = fast.next.next;
}
slow = reverse(slow);
fast = head.next;
while (slow != null && fast != null) {
head.next = slow;
head = head.next;
slow = slow.next;
if (slow != null) {
head.next = fast;
head = head.next;
fast = fast.next;
}
}
return;
}
private ListNode reverse(ListNode head) {
if (head.next == null)
return head;
ListNode temp = reverse(head.next);
head.next.next = head;
head.next = null;
return temp;
}
}