MediumLinked ListTwo PointersStackRecursion

Reorder List

LeetCode
1 approach, code in all languages

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
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.

750+ engineers trained · frontend, backend, AWS & AI

August 15 · 0d left
Enroll Now