Why my code get Runtime Error ?


  • 0
    D
    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    bool cmp(ListNode *a,ListNode *b){
    	if(a->val<=b->val) return true;
    	else return false;
    }
    class Solution{
    public:
    	ListNode *mergeKLists(vector<ListNode *> &lists){
    		vector<ListNode*> v;
    		int len=lists.size();
    		for(int i=0;i<len;i++) if(lists[i]!=NULL) v.push_back(lists[i]);
    		sort(v.begin(),v.end(),cmp);
    		len=v.size();
    		ListNode *head,*t;
    		head=t=new ListNode(-1);
    		while(len>0){
    			t->next=v[0];
    			t=t->next;
    			v[0]=v[0]->next;
    			if(v[0]==NULL) v.erase(v.begin());
    			else move(v,len);
    			len=v.size();
    		}
    		return head->next;
    	}
    	void move(vector<ListNode*> &v,int &len){
    	    ListNode *t;
    	    for(int i=0;i<len-1;i++){
    	        if(v[i+1]!=NULL&&v[i]->val>v[i+1]->val){ t=v[i+1]; v[i+1]=v[i]; v[i]=t;}
    	        else break;
    	    }
    	}
    };

  • 0
    D

    In the function cmp, should change operator <= to <. But why?


  • 0
    K

    I also had runtime error but got accepted after considering boundary cases when some of the sorted lists are empty.


  • 0
    D

    I had considered the NULL lists. And I found that, in the function cmp, if the compare operator is '<=' then after sort the vector wouldn't change.


  • 0
    O

    i also meet the same problem. do you know why?


Log in to reply
 

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