Easy understanding O(n) solution


  • 0
    L
    ListNode* oddEvenList(ListNode* head) 
    {
        ListNode oddDummy(-1), *preOdd;
        ListNode evenDummy(-1), *preEven;
        
        preOdd = &oddDummy;
        preEven = &evenDummy;
        
        while(head && head->next)
        {
            preOdd = preOdd->next = head;
            head = head->next;
            preEven = preEven->next = head;
            head = head->next;
        }
        preEven->next = nullptr;
        
        if(head)
            preOdd = preOdd->next = head;
        
        preOdd->next = evenDummy.next;
        
        return oddDummy.next;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.