The Odd Even Linked List problem requires rearranging a linked list so that all nodes at odd positions appear before all nodes at even positions.

Problem

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

The first node is considered to be at index 1. The relative order of the nodes within the odd and even groups should remain the same.

Example(s)

Consider the following examples to understand the expected input and output.

Example 1

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

Example 2

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

Solution

This solution uses two pointers to maintain separate odd and even linked lists. The odd pointer connects nodes at odd positions, while the even pointer connects nodes at even positions.

We move both pointers forward together. After processing all nodes, we connect the end of the odd list to the beginning of the even list. This rearranges the list in-place while preserving the relative order within each group.
class Solution {
    public ListNode oddEvenList(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }

        ListNode odd = head;
        ListNode even = head.next;
        ListNode 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;
    }
}

Complexity

Each node is processed once, so the time complexity is O(n), where n is the number of nodes in the linked list.

The list is rearranged in-place using only a few pointers, so the extra space complexity is O(1).
Nagesh Chauhan

Nagesh Chauhan

Principal Software Engineer • Java • Python • Distributed Systems • AI/ML

Principal Software Engineer with 14+ years of experience designing and delivering large-scale distributed systems, cloud-native applications, and AI-powered platforms.

Passionate about solving complex engineering problems using strong data structures and algorithms, along with expertise in Java, Spring Boot, Python, System Design, Microservices, Cloud, Kafka, Elasticsearch, and Generative AI.

Share this Article

💬 Comments

Join the Discussion