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


  • 3
    ListNode* oddEvenList(ListNode* head) {
        if(head == NULL)
            return head;
        ListNode *head_even = head->next;
        ListNode *a = head, *b = head_even;
        
        while(b != NULL && b->next != NULL){
            a->next = b->next;
            a = a->next;
            b->next = a->next;
            
            b = b->next;
        }
        a->next = head_even;
        return head;
    }

  • 0
    A

    HI, I think the idea is right.

    but there are some bug in this system. Notice that if you swap the while condition to
    while(b->next != NULL && b !=NULL), you will get the RunTime error


  • 0
    Z

    if b!=NULL is false, this cycle will be directly ended and will not check b->next. However if b is NULL and you keep checking for b->next, I think this may cause some problem I guess?


Log in to reply
 

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