Skip to main content
mediumBlind 75

Reorder List

Reorder list to L0 → Ln → L1 → Ln-1 → L2 → Ln-2 → ... Example: [1,2,3,4] => [1,4,2,3]

Given the head of a singly linked list L0, L1, ..., Ln, reorder its nodes in place to L0, Ln, L1, Ln-1, L2, Ln-2, and so on, then return the head. Only change the links between nodes; do not modify their values. For example, [1,2,3,4,5] becomes [1,5,2,4,3]. The list contains 1 to 5000 nodes, each with an integer value from 1 to 1000.

Examples

You write

reorder_list(head: Optional[ListNode])

  1. Example 1

    Input
    [1,2,3,4]
    returns
    [1,4,2,3]
  2. Example 2

    Input
    [1,2,3,4,5]
    returns
    [1,5,2,4,3]

The pattern behind it

Linked Lists

I reach for it when

  • Nodes point to the next node, and you cannot index into the list.
  • You must reverse, merge, reorder or remove a node.

Say this before you type. Say which pointers you hold and which link you are about to change.

All 12 Linked Lists problems

Stack

I reach for it when

  • Things must close in the reverse order they opened.
  • You need the nearest earlier or later item that is bigger or smaller.

Say this before you type. Say what each item on the stack is waiting for, and what lets you pop it.

All 17 Stack problems

Meet Coco

Coco is an AI study partner, not a person. She listens while you explain your code, asks what a line does and never hands you the fix. Sign in free to type with Coco, up to a daily limit. The editor and Run stay open without an account. Anyone can open the editor and run their code.

1Reorder Listmedium