Why this C++ solution will TimeLimit Exceeded?


  • 0
    J
    class Solution {
    public:
        ListNode* oddEvenList(ListNode* head) {
            // ListNode *newList = NULL;
            if((head==NULL)||(head->next == NULL) ||(head->next->next==NULL)){
                cout<<"wrong"<<endl;
                return head;
            }
            ListNode *odd=head,*even=head->next;
            ListNode *evenList = even;
            ListNode *oddList = odd;
            while(even->next != NULL){
                cout<<odd->val<<endl;
                // if(even->next == NULL)break;
                odd->next = even->next;
                odd = odd->next;
                cout<<even->val<<endl;
                if(odd->next == NULL)break;
                even->next = odd->next;
                even = even->next;
            }
            // cout<<"end while"<<endl;
            // cout<<odd->val<<endl;
            // cout<<"evenList's val"<<evenList->val<<endl;
            // cout<<"oddList's val"<<oddList->val<<endl;
            odd->next = evenList;
            return oddList;
        }
    };

  • 0
    H

    add

    even->next = NULL;

    b4 return


  • 0
    J

    Thanks, it works


Log in to reply
 

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