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 {
private:
    ListNode *merge(ListNode* list1,ListNode* list2)
    {
        if(list1==NULL && list2==NULL) return NULL;
        if(list1==NULL) return list2;
        if(list2==NULL) return list1;
        
        ListNode* head;
        if(list1->val>list2->val)
        {
            head=list2;
            list2=list2->next;
        }
        else
        {
            head=list1;
            list1=list1->next;
        }
        ListNode* p=head;
        p->next=NULL;
        while(list1!=NULL && list2!=NULL)
        {
            if(list1->val>list2->val)
            {
                p->next=list2;
                list2=list2->next;
            }
            else
            {
                p->next=list1;
                list1=list1->next;
            }
            p=p->next;
            p->next=NULL;
        }
        if(list1!=NULL || list2!=NULL)
        {
            if(list1==NULL) list1=list2;
            while(list1!=NULL)
            {
                p->next=list1;
                list1=list1->next;
                p=p->next;
                p->next=NULL;
            }
        }
        return head;
    }
public:
    ListNode *mergeKLists(vector<ListNode *> &lists) 
    {
        int len=lists.size();
        if(len==0return NULL;
        if(len==1return lists[0];
        ListNode * head=lists[0];
        for(int i=1;i<len;i++)
            head=merge(head,lists[i]);
        return head;
    }
}; 
posted @ 2014-05-29 15:48  erictanghu  阅读(92)  评论(0编辑  收藏  举报