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
Odd Even Linked List Two-Pointer In-Place Rearrangement INPUT Original Linked List: 1 odd 2 even 3 odd 4 even 5 odd head = [1,2,3,4,5] indices: 1,2,3,4,5 (1-indexed) Odd index Even index odd ptr starts at node 1 even ptr starts at node 2 evenHead saves node 2 ALGORITHM STEPS 1 Initialize Pointers odd=head, even=head.next evenHead=even (save start) 2 Traverse List while(even AND even.next): relink odd and even nodes 3 Relink Nodes odd.next = even.next odd = odd.next even.next = odd.next even = even.next 4 Connect Lists odd.next = evenHead Join odd list to even list Pointer Movement: 1 --> 3 --> 5 odd list 2 --> 4 even list FINAL RESULT Reordered Linked List: Odd indices first 1 3 5 link Then even indices 2 4 NULL Output: [1, 3, 5, 2, 4] OK - Order preserved! Complexity: Time: O(n) | Space: O(1) Key Insight: Use two pointers to separate odd and even indexed nodes in-place. By saving the evenHead before traversing, we can connect the end of odd list to start of even list. No extra space needed as we only modify existing node pointers, achieving O(1) space complexity. TutorialsPoint - Odd Even Linked List | Two-Pointer In-Place Rearrangement
Asked in
Facebook 35 Microsoft 28 Amazon 22 Google 18
236.6K Views
Medium Frequency
~15 min Avg. Time
8.5K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen