Simple C++ solution, O(n) time, O(1) space


  • 31
    C
        ListNode* oddEvenList(ListNode* head) 
        {
            if(!head) return head;
            ListNode *odd=head, *evenhead=head->next, *even = evenhead;
            while(even && even->next)
            {
                odd->next = odd->next->next;
                even->next = even->next->next;
                odd = odd->next;
                even = even->next;
            }
            odd->next = evenhead;
            return head;
        }

  • 0
    X

    Straightforward, thanks~


  • 0
    V

    can this be treated as in place?


  • -4
    P

    I would not call this an 'in place' solution.


  • 0
    C

    @vishnu5 yes, this is in place solution as we are not creating 'n' new ListNodes


  • 0
    V

    cool code.. thanks :)


  • 9
    W

    Maybe better solution (Deduced 4 times '->' operator call within the loop) :

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

  • 0
    L

    u solution is better than mine.Very good!


  • 0
    V

    @csk If we switch the first two lines of the while loop,like even->next=even->next->next comes first then I am getting a null pointer error,could you highlight why?


  • 0
    C

    @wfxr I can't understand your solution about this problem,for instance,
    odd=odd->next=even->next? why do it ?


  • 0
    C

    @wfxr said in Simple C++ solution, O(n) time, O(1) space:

    Maybe better solution (Deduced 4 times '->' operator call within the loop) :

    ListNode* oddEvenList(ListNode* head) {
        if (!head) return head;
        
        auto odd = head, evenHead = head->next, even = evenHead;
        while (even && even->next) {
            odd = odd->next = even->next;???
            even = even->next = odd->next;
        }
        odd->next = evenHead;
        
        return head;
    }

Log in to reply
 

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