码迷,mamicode.com
首页 > 其他好文 > 详细

Merge k Sorted Lists

时间:2014-06-04 21:08:57      阅读:381      评论:0      收藏:0      [点我收藏+]

标签:des   c   style   class   blog   code   

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

bubuko.com,布布扣
/**
 * 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;
    }
}; 
bubuko.com,布布扣

Merge k Sorted Lists,布布扣,bubuko.com

Merge k Sorted Lists

标签:des   c   style   class   blog   code   

原文地址:http://www.cnblogs.com/erictanghu/p/3759291.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!