Odd Even Linked List
Medium
Linked ListTwo Pointers
Problem
Rearrange a linked list so all nodes at odd positions come before all nodes at even positions (1-indexed). O(1) extra space.
Example 1
Input: [1,2,3,4,5]
Output: [1,3,5,2,4]
Example 2
Input: [2,1,3,5,6,4,7]
Output: [2,3,6,7,1,5,4]
Constraints
- 0 ≤ length ≤ 10⁴
Approach — Two Pointers
This is a Two Pointers problem. The idea: walk two indices through the data together (or toward each other), turning an O(n²) pair search into one linear pass. Work through the reference code below line by line, then re-derive it yourself in the editor — that's how the pattern sticks.
Complexity: O(n) time, O(1) extra space.
Solution code
Python
class Solution:
def oddEvenList(self, head):
if not head:
return head
odd = head
even = head.next
even_head = even
while even and even.next:
odd.next = even.next
odd = odd.next
even.next = odd.next
even = even.next
odd.next = even_head
return head
Java
class Solution {
public ListNode oddEvenList(ListNode head) {
if (head == null) return null;
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;
}
}
Practice it
Reading a solution isn't the same as being able to write it under pressure. Open this problem in the in-browser editor, hide the solution, and solve it from scratch — your code runs against real test cases instantly.
Solve Odd Even Linked List interactively → ← All solutions