Reorder List Medium 0 attempts
LeetCode ↗

Reorder List

Medium Linked List LeetCode

A singly linked list is given as L0→L1→...→Ln. Rearrange its nodes in place so they follow the pattern L0→Ln→L1→Ln-1→L2→Ln-2→..., alternating between the front and back of the original order.

Input Format
Implement reorderList(head). Inputs below show JavaScript function arguments; there is no stdin parsing. Linked lists use value arrays. The editor passes nodes with val and next properties; [] becomes null.
Output Format
Modify argument 1 in place. The editor compares its final value; the function return value is ignored. Returned list heads are displayed as value arrays; a null head is [].

Sample Input and Output

Example 1 · Run Sample

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
Test Cases (2)
Case 1
Args: [[1,2,3,4]] Expected: [1,4,2,3]
Case 2
Args: [[1]] Expected: [1]
Topics

Find Middle + Reverse + Merge

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)

Saved in this browser only. Private to you.

JavaScript