Skip to problem
←

Reorder List

Medium 0 attempts

Given a nonempty singly linked list with nodes L0 → L1 → … → Ln, reorder its original nodes in place as:

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

Alternate from the front and back of the original list, using every node exactly once. The labels identify node positions, not values. Rewire next pointers without changing node values or creating replacement nodes. End the list with null and use constant extra space.

For [1, 2, 3, 4], produce [1, 4, 2, 3]. For [1, 2, 3, 4, 5], produce [1, 5, 2, 4, 3]; the middle node appears once at the end.

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 reorderList(head). Linked lists use value arrays. The editor passes nodes with val and next properties; [] becomes null.

Output: Modify the original list in place by rewiring its nodes. The return value is ignored; the runner checks the list reached from the original head.

Example 1

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

Example 2

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

Split, Reverse, and Merge Alternately

Use slow and fast pointers to find the end of the first half. Detach the second half so the first list ends with null. For an odd-length input, the first half contains the middle node and is one node longer.

Reverse the second half iteratively, making its nodes available from the original tail inward. Then weave one second-half node after each first-half node. Save both next pointers before rewiring, so neither remaining chain is lost.

Stop when the second half is exhausted. The extra middle node, if any, already ends the first half. All original nodes and values are preserved, and detaching before merging prevents leftover links from creating a cycle.

javascript
function reorderList(head) {
  let slow = head,
    fast = head;
  while (fast.next && fast.next.next) {
    slow = slow.next;
    fast = fast.next.next;
  }
  let prev = null,
    curr = slow.next;
  slow.next = null;
  while (curr) {
    const next = curr.next;
    curr.next = prev;
    prev = curr;
    curr = next;
  }
  let l1 = head,
    l2 = prev;
  while (l2) {
    const n1 = l1.next,
      n2 = l2.next;
    l1.next = l2;
    l2.next = n1;
    l1 = n1;
    l2 = n2;
  }
}

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

Loading discussion…

Saved in this browser only. Private to you.

JavaScript