Odd Even Linked List - Problem
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, and the second node is even, and so on.
Note: The relative order inside both the even and odd 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.
Input & Output
Example 1 — Basic Case
$
Input:
head = [1,2,3,4,5]
›
Output:
[1,3,5,2,4]
💡 Note:
Group odd indices (1st, 3rd, 5th nodes) first: [1,3,5], then even indices (2nd, 4th nodes): [2,4]. Final result: [1,3,5,2,4]
Example 2 — Even Length
$
Input:
head = [2,1,3,5,6,4,7]
›
Output:
[2,3,6,7,1,5,4]
💡 Note:
Odd positions (1st,3rd,5th,7th): [2,3,6,7], even positions (2nd,4th,6th): [1,5,4]. Result: [2,3,6,7,1,5,4]
Example 3 — Two Nodes
$
Input:
head = [1,2]
›
Output:
[1,2]
💡 Note:
Only two nodes: 1st node (odd) stays first, 2nd node (even) stays second. Order unchanged.
Constraints
- The number of nodes in the linked list is in the range [0, 104]
- -106 ≤ Node.val ≤ 106
Visualization
Tap to expand
Understanding the Visualization
1
Input
Original linked list [1,2,3,4,5]
2
Group by Position
Separate odd positions (1,3,5) and even positions (2,4)
3
Output
Rearranged list [1,3,5,2,4]
Key Takeaway
🎯 Key Insight: Maintain two separate chains for odd and even positioned nodes, then connect them to achieve O(1) space complexity
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code