In this Leetcode Odd-Even Linked List problem solution, You are 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 that 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.

Leetcode Odd-Even Linked List problem solution


Problem solution in Python.

class Solution(object):
    def oddEvenList(self, head):      
        def helper(odd, even, node, level):
            if not node:
                return (odd, even)
            
            if level % 2 == 1:
                odd.next = node
                node = node.next
                    
                odd = odd.next
                odd.next = None
            else:
                even.next = node
                node = node.next
                
                even = even.next
                even.next = None
                
            return helper(odd, even, node, level + 1)
        
        dummyOdd = ListNode(0)
        dummyEven = ListNode(0)
        
        odd, even = helper(dummyOdd, dummyEven, head, 1)
        odd.next = dummyEven.next
        
        return dummyOdd.next



Problem solution in Java.

public ListNode oddEvenList(ListNode head) {
        if (head == null) return head;
        
        ListNode evenHead = head.next, oddWalker = head, evenWalker = evenHead;
        
        while(evenWalker != null && evenWalker.next != null) {
            oddWalker.next = oddWalker.next.next;
            evenWalker.next = evenWalker.next.next;
            oddWalker = oddWalker.next;
            evenWalker = evenWalker.next;
        }
        
        oddWalker.next = evenHead;
        
        return head;
    }


Problem solution in C++.

ListNode* oddEvenList(ListNode* head)
{
    ListNode **odd = &head, *even_head = NULL, **even = &even_head;
    while (*odd)
    {
        odd = &((*odd)->next);
        if (*even = *odd)
        {
            *odd = (*odd)->next;
            even = &((*even)->next);
        }   
    }
    *odd = even_head;
    return head;
}


Problem solution in C.

struct ListNode* oddEvenList(struct ListNode* head)
{
    if(head==NULL || head->next==NULL)
        return head;
    
    struct ListNode *p=head;
    struct ListNode *q=p->next;
    
    while(q!=NULL && q->next!=NULL)
    {
        struct ListNode *tmp=q->next;
        
        q->next = q->next->next;
        
        tmp->next=p->next;
        p->next=tmp;        
        
        p=p->next;
        q=q->next;
    }
    
    return head;
}