189 ms C++ solution. Just store everything in vector and then sort it. Again go in it and create new list. complexity is the same for heap's solution.


  • 0
    M
    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
     void add_node(ListNode **head, int val)
    {
    	if (*head == NULL)
    	{
    		ListNode *node = new ListNode(val);
    		*head = node;
    	}
    	else
    	{
    		ListNode *temp = *head;
    		while (temp->next)
    			temp = temp->next;
    		ListNode *node = new ListNode(val);
    		temp->next = node;
    	}
    }
     
     
    class Solution {
    public:
        ListNode* mergeKLists(vector<ListNode*>& lists) 
    {
    	ListNode* head = NULL;
    	vector<int> v;
    	bool stop = false;
    	while (!stop)
    	{
    		stop = true;
    		for (int i = 0; i < lists.size(); i++)
    		{
    			if (lists[i])
    			{
    				stop = false;
    				v.push_back(lists[i]->val);
    				lists[i] = lists[i]->next;
    			}
    		}
    	}
    	sort(v.begin(), v.end());
    	for (auto it : v)
    	{
    		add_node(&head, it);
    	}
    	
    	return head;
    }
    };
    

Log in to reply
 

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