MediumLinked ListTwo PointersStackRecursion

1 approach, code in every language

Problem description

You are given the head of a singly linked list L0 -> L1 -> ... -> Ln-1 -> Ln. Rearrange it in place so the nodes interleave from both ends inward: L0 -> Ln -> L1 -> Ln-1 -> L2 -> Ln-2 -> and so on.

You may not change any node values; the reordering must be done by adjusting the next pointers only.

Example 1

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

Output: [1,4,2,3]

Front node 1, then back node 4, then the next front node 2, then the next back node 3.

Example 2

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

Output: [1,5,2,4,3]

With an odd count the middle node 3 ends up last after the alternating merge.

Constraints

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

After the pattern

Now solve one you haven't seen.

Fold the Signal Relay Chain is our own problem on the technique behind Reorder List: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.

1,194 problems · 15,062 graded tests · free