Help "time limited exceed"


  • 3
    W

    I don't know why it reports "time limited exceed" as I think time complexity is O(n)
    My code:

     void reorderList(ListNode *head) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
        if(head!=NULL){
        vector<ListNode*> ln; // store listnode into vector
        ListNode *p=head;
        while(p!=NULL){
            ln.push_back(p);
            p=p->next;
        }
        int l=ln.size()-1; // from end
        int i=0;           // from begin
        while(i!=l&&l-i!=1){ // reorder
            ln[i]->next=ln[l];
            ln[l]->next=ln[i+1];
            i++;l--;
        }
        
        }
    }

  • 4

    I think your program has a common bug within Linked List problems. You probably forgot to assign the last node's next to NULL.

    For example,

    1->2->3->NULL
    

    After calling your function, it should return:

    1->3->2->NULL
    

    But according your function, the last node's (with value 2) next is still pointing to the node with value 3, therefore causing a loop in the returned list.


  • 2
    C

    I think you did not set the point to null. For example, 1->2->3->4, as your algorithm, it would be 1->4->2->3->4, there is a loop. you need set 3.next = null.
    you just need add: ln[l]->next = NULL; after while loop to fix this bug.


  • 0
    K

    Is this in place when you introduced vector here?


Log in to reply
 

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