Skip to problem
←

Reorder a Linked List

Medium 0 attempts

Given a nonempty singly linked list with nodes L0 → L1 → … → Ln, reorder it in place by alternating nodes from the two ends inward:

L0 → Ln → L1 → Ln-1 → L2 → Ln-2 → …

These labels identify original node positions, not values. Rewire the original nodes without changing their values or replacing them with copies. Include every node exactly once and end the list with null. Use constant extra space.

For [1, 2, 3, 4, 5], the final list is [1, 5, 2, 4, 3]; for [1, 2, 3, 4], it is [1, 4, 2, 3]. A one-node or two-node list keeps its existing order.

Your function receives nodes with val and next properties. Modify the list starting at the original head; the function's return value is ignored.

Function contract

Implement rearrange(head). Linked lists use value arrays. The editor passes nodes with val and next properties; [] becomes null.

Output: Rewire the original list in place. The runner inspects the original head after the call and ignores the return value; it displays the resulting node values.

Example 1

Input
head = [1,2,3,4,5]
Output
[1,5,2,4,3]

Example 2

Input
head = [1]
Output
[1]
Constraints
  • 1 to 5 * 10^4 nodes
  • 1 <= Node.val <= 1000

Split, Reverse, and Interleave

Find the end of the first half using slow and fast pointers. Detach the second half by setting slow.next to null; this prevents the later weaving step from retaining an old link that creates a cycle.

Reverse the second half iteratively. Its nodes are now in the order needed from the far end of the original list. Alternate a node from the first half with a node from the reversed half, saving both next pointers before changing links.

For odd lengths, the first half has one extra node, which naturally remains at the end. No node values change and no replacement nodes are allocated.

javascript
function rearrange(head) {
  let slow = head,
    fast = head;
  while (fast.next && fast.next.next) {
    slow = slow.next;
    fast = fast.next.next;
  }
  let second = slow.next;
  slow.next = null;
  let prev = null;
  while (second) {
    const next = second.next;
    second.next = prev;
    prev = second;
    second = next;
  }
  let first = head;
  second = prev;
  while (second) {
    const n1 = first.next,
      n2 = second.next;
    first.next = second;
    second.next = n1;
    first = n1;
    second = n2;
  }
}

Time: O(n) | Space: O(1)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript