☰ All problems

33. Reorder List

You are given the head of a singly linked list whose nodes, in order, are L0, L1, L2, …, Ln.

Rearrange it in place so that the nodes alternate from the two ends: L0, Ln, L1, Ln-1, L2, Ln-2, …

Only change the next links; do not modify the values stored in the nodes. The function returns nothing; the list starting at head is checked afterwards.

Example 1
Input: head = [5,6,7,8]
Output: [5,8,6,7]
Example 2
Input: head = [10,20,30,40,50]
Output: [10,50,20,40,30]

Explanation: With an odd number of nodes, the middle node ends up last.

Constraints

  • The number of nodes is in the range [1, 5 * 10^4]
  • -1000 <= Node.val <= 1000
💡 Hint 1

The new order interleaves the first half of the list with the second half read backwards.

💡 Hint 2

Find the middle with slow and fast pointers, then reverse the second half in place.

💡 Hint 3

Finally merge the two halves by alternating one node from each, starting with the first half.

/**
 * Definition for singly-linked list (provided):
 * function ListNode(val, next) { this.val = val ?? 0; this.next = next ?? null; }
 *
 * @param {ListNode} head
 * @return {void} Reorder the list in place.
 */
function reorderList(head) {

}
Ctrl/⌘ + ' run · Ctrl/⌘ + Enter submit
esc