Odd Even Linked List

IF
AlgoAxiomStaff Engineers
JSTS
Medium20 mins

Given the head of a singly linked list, group all the nodes with odd indices together followed by the nodes with even indices, and return the reordered list.

The first node is considered odd (index 1), the second node is even (index 2), and so on.

Note that the relative order inside both the odd and even groups should remain as it was in the input.

You must solve the problem in O(1) extra space complexity and O(n) time complexity.

Examples

Example 1:

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

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

Explanation: Odd-indexed nodes: 1, 3, 5. Even-indexed nodes: 2, 4. Result: [1,3,5,2,4].

Example 2:

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

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

Explanation: Odd-indexed nodes: 2, 3, 6, 7. Even-indexed nodes: 1, 5, 4. Result: [2,3,6,7,1,5,4].

Example 3:

Input: head = [1]

Output: [1]

Explanation: Only one node, so the list is unchanged.

Constraints

  • The number of nodes in the list is in the range [0, 10⁴]
  • -10⁶ <= Node.val <= 10⁶
Source: Fast and Slow Pointers pattern — AlgoAxiom
JavaScript
Test Case 1
root = [1, 2, 3]
Test Case 2
root = [1, 2, 3, 4, 5]
Idle