Why my code has Runtime Error? C++


  • 0
    S
    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    private:
        struct cmp{
            bool operator ()(ListNode * a, ListNode *b){
                return a->val > b->val;//greater than comp
            }
        };    
    public:
        ListNode *mergeKLists(vector<ListNode *> &lists) {
        priority_queue<ListNode*, vector<ListNode *>, cmp> myque;
        cout << myque.size() << endl;
        int k = lists.size();
        if(k == 0) return NULL;
        for(int i = 0; i <k; i++){
          if(lists[k])
    	myque.push(lists[k]);
        }
        ListNode *fake = new ListNode(0);
        ListNode *cur = fake;
        while(!myque.empty()){
          ListNode * node = myque.top();
          myque.pop();
          cur->next = node;
          cur = node;
          if(node->next) myque.push(node->next);
        }
        cur = fake->next;
        delete(fake);
        return cur;
        }
    };

  • 1
    N

    Should use 'i' instead of 'k' as the index:
    for(int i = 0; i <k; i++){
    if(lists[k])
    myque.push(lists[k]);
    }


Log in to reply
 

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