Saturday, April 18, 2015

[LeetCode] Merge k Sorted Lists

Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */

class Solution {
public:
    ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
        ListNode node(0);
        ListNode *head = &node;
        
        while(l1 && l2)
        {
            if(l1->val > l2->val)
            {
                head->next = l2;
                l2 = l2->next;
            }
            else
            {
                head->next = l1;
                l1 = l1->next;
            }
            head = head->next;
        }
        if(l1) head->next = l1;
        else head->next = l2;
        
        return node.next;
    }
    ListNode* mergeSort(vector<ListNode *> &lists, int start, int end)
    {
        if(end - start == 1) return mergeTwoLists(lists[start], lists[end]);
        if(start == end) return lists[start];
        return mergeTwoLists(mergeSort(lists, start, (start+end)/2), 
                             mergeSort(lists,(start+end)/2 + 1, end));
    }
    ListNode *mergeKLists(vector<ListNode *> &lists) 
    {
        if(0 == lists.size()) return NULL;
        return mergeSort(lists, 0, lists.size()-1);
    }
};