C++ Solution using sort().


  • 0
    W
    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        ListNode* mergeKLists(vector<ListNode*>& lists) {
            int i;
            ListNode *result,*temp;
            result = new ListNode(0);
            temp = result;
            vector<int> tank = {};
            for(i=0;i<lists.size();++i){
                while(lists[i]!=NULL){
                    tank.push_back(lists[i]->val);
                    lists[i] = lists[i]->next;    
                }
            }
            sort(tank.begin(),tank.end());
            if(tank.empty())
                return NULL;
            for(i=0;i<tank.size()-1;++i){
                temp->val = tank[i];
                temp->next = new ListNode(0);
                temp = temp->next;
            }
            temp->val = tank[i];
            temp->next = NULL;
            return result;
        }
    };
    

Log in to reply
 

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