Sunday, March 24, 2013

Merge k Sorted Lists


/*

Merge k Sorted ListsFeb 14 '12
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 *mergeKLists(vector<ListNode *> &lists) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        int size = lists.size();
        if(size==0) return NULL;
        if(size==1 && lists[0]!=NULL) return lists[0];
        if(size==1 && lists[0]==NULL) return NULL;
        int const MaxVal = 500;
       
        int i;
        ListNode *node = NULL;
        ListNode *curr = NULL;
        int currVal = MaxVal;
        int k = -1;
        for(i=0; i<size; i++){
            if(lists[i]!=NULL){
                if(lists[i]->val < currVal){
                    currVal = lists[i]->val;
                    curr = lists[i];
                    k = i;
                }
            }
        }
        if(k!=-1){
            node = lists[k];
            lists[k] = lists[k]->next;
        }
        if(node!=NULL) node->next = mergeKLists(lists);
       
        return node;
    }
};

No comments:

Post a Comment