Odd Even Linked List
Reorder a list so odd-indexed nodes come first, then even-indexed, preserving relative order — two interleaved chains.
3 min read
linked-list
Problem#
Reorder a singly linked list so that all odd-indexed nodes (1-indexed) come before all even-indexed nodes, preserving relative order in each group. Do it in O(1) extra space.
Examples#
[1,2,3,4,5]→[1,3,5,2,4][2,1,3,5,6,4,7]→[2,3,6,7,1,5,4]
Constraints#
0 <= n <= 10^4.
Approach#
Maintain two interleaved chains: odd and even, each starting at the first/second node and stepping by 2. After the loop, link the odd tail to the even head.
Solution#
class Solution {public: ListNode* oddEvenList(ListNode* head) { if (!head) return head; ListNode *odd = head, *even = head->next, *evenHead = even; while (even && even->next) { odd->next = even->next; odd = odd->next; even->next = odd->next; even = even->next; } odd->next = evenHead; return head; }};func oddEvenList(head *ListNode) *ListNode { if head == nil { return head } odd, even := head, head.Next evenHead := even for even != nil && even.Next != nil { odd.Next = even.Next odd = odd.Next even.Next = odd.Next even = even.Next } odd.Next = evenHead return head}from typing import Optional
class Solution: def oddEvenList(self, head: Optional[ListNode]) -> Optional[ListNode]: if head is None: return head odd = head even = head.next even_head = even while even is not None and even.next is not None: odd.next = even.next odd = odd.next even.next = odd.next even = even.next odd.next = even_head return headfunction oddEvenList(head) { if (head === null) return head; let odd = head, even = head.next; const evenHead = even; while (even !== null && even.next !== null) { odd.next = even.next; odd = odd.next; even.next = odd.next; even = even.next; } odd.next = evenHead; return head;}class Solution { public ListNode oddEvenList(ListNode head) { if (head == null) return head; ListNode odd = head, even = head.next, evenHead = even; while (even != null && even.next != null) { odd.next = even.next; odd = odd.next; even.next = odd.next; even = even.next; } odd.next = evenHead; return head; }}function oddEvenList(head: ListNode | null): ListNode | null { if (head === null) return head; let odd: ListNode = head; let even: ListNode | null = head.next; const evenHead: ListNode | null = even; while (even !== null && even.next !== null) { odd.next = even.next; odd = odd.next; even.next = odd.next; even = even.next; } odd.next = evenHead; return head;}Editorial#
Both chains weave forward simultaneously, each picking nodes at stride 2. The loop guard handles both odd and even total lengths. After the weave, the odd chain points at evenHead to form the final list.
Complexity#
- Time: O(n).
- Space: O(1).
Concept revision#
Related#