Skip to contentKEEP THE CRAFTTHE SANCTUARY

Reorder List

Rearrange a list as first, last, second, second-to-last, and so on, in place.

The problem

Implement Solution.reorderList(head). The list is L0 -> L1 -> ... -> Ln. Rearrange the nodes into L0 -> Ln -> L1 -> Ln-1 -> L2 -> Ln-2 -> ..., so you take one node from the front, then one from the back, and repeat. For example, 1 -> 2 -> 3 -> 4 -> 5 becomes 1 -> 5 -> 2 -> 4 -> 3. Move the existing nodes by changing their next links; do not change any node values or create new nodes. Return head, the same first node. The list has 1 to 50,000 nodes.

Starter code

class Solution:
    def reorderList(self, head):
        pass

Public examples

  1. head = [1, 2, 3, 4]gives[1, 4, 2, 3]
  2. head = [3, 9]gives[3, 9]
  3. head = [4, 7, 2]gives[4, 2, 7]

Solving it in the practice book needs an active paid plan.

Open it in the practice book
One thought at a time.