Clean C++ O(n) time O(1) space 15ms beats 97.4%


  • 0
        ListNode* oddEvenList(ListNode* head) {
            if(!head||!head->next||!head->next->next) return head;
            ListNode* oddCur=head;
            ListNode* evenCur=head->next;
            ListNode* oddNext=evenCur->next;
            ListNode* evenNext=oddNext->next;
            ListNode* evenHead=evenCur;
            
            while(oddNext||evenNext){
                oddCur->next=oddNext;
                oddCur=oddNext;
                oddNext=evenNext?evenNext->next:NULL;
                
                evenCur->next=evenNext;
                evenCur=evenNext;
                evenNext=oddNext?oddNext->next:NULL;
            }
            oddCur->next=evenHead;
            return head;
        }
    

Log in to reply
 

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