Very easy to understand, single pass, in place C++ without nested dereferences


  • 0
    R

    This solution has been designed in order to minimize pointer dereferences, that can be sources of bugs ( It has Zero nested dereferences) .It passed indeed with no error with the first try.

    ListNode* oddEvenList(ListNode* head) 
    {
        ListNode dummy_even{0}, dummy_odd{0};
        ListNode *even_head=&dummy_even, *odd_head=&dummy_odd;
        bool is_odd = true;
        while ( head )
        {
            if (is_odd) {
                odd_head->next = head;
                odd_head = head;
            } else {
                even_head->next = head;
                even_head = head;
            }
            
            head = head->next;
            is_odd = !is_odd;
        }
        
        even_head->next = 0;
        odd_head->next = dummy_even.next;
        return dummy_odd.next;   
    }

Log in to reply
 

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