Skip to contentKEEP THE CRAFTTHE SANCTUARY

Odd Even Linked List

Move the nodes at odd positions in front of the nodes at even positions, keeping each group in order.

The problem

Implement Solution.oddEvenList(head). head is the first node of a singly linked list with up to 10,000 nodes, or None for an empty list. Count positions from 1. Relink the existing nodes so all nodes at odd positions (1st, 3rd, 5th, ...) come first, followed by all nodes at even positions (2nd, 4th, ...), with each group in its original order. For 1 -> 2 -> 3 -> 4 -> 5 the result is 1 -> 3 -> 5 -> 2 -> 4. Return the new head. Reuse the original nodes instead of creating new ones, and use O(1) extra space.

Starter code

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

Public examples

  1. head = [1, 2, 3, 4, 5]gives[1, 3, 5, 2, 4]
  2. head = [-1000000]gives[-1000000]
  3. head = [4, 7]gives[4, 7]

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

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