首页 > 其他 > 详细

[LeetCode] Merge k Sorted Lists

时间:2014-07-16 12:27:17      阅读:362      评论:0      收藏:0      [点我收藏+]

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

#include<iostream>
#include<vector>
using namespace std;

struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};

class Solution {
public:
    ListNode *mergeKLists(vector<ListNode *> &lists) {
        int lSize= lists.size();
        if(lSize == 0)
            return NULL;
        else if(lSize == 1)
            return lists[0];
        for(int i=1;i<lSize;i++)
        {
            lists[0] = Merge(lists[0],lists[i]);

        }
        return lists[0];
    }
private:
    ListNode* Merge(ListNode *list1,ListNode *list2)
    {
        ListNode *head = new ListNode(0);
        ListNode *p = head;
        ListNode *l1 = list1,*l2 = list2;
        while(l1!=NULL && l2 !=NULL)
        {
            if(l1->val < l2->val)
            {
                p->next = l1;
                l1 = l1->next;
                p = p->next;
            }
            else
            {
                p->next = l2;
                l2 = l2->next;
                p = p->next;
            }
        }
        while(l1 != NULL)
        {
            p->next = l1;
            l1 = l1->next;
            p = p->next;
        }
        while(l2 != NULL)
        {
            p->next = l2;
            l2 = l2->next;
            p = p->next;
        }
        p->next = NULL;
        return head->next;
    }
};

思路:第0个List和第1个Merge,将结果写入第0个,然后第0个和第2个Merge,将结果写入第0个,依次进行。

每次两两Merge都将结果写入第0个这样做避免了用额外的空间。

[LeetCode] Merge k Sorted Lists,布布扣,bubuko.com

[LeetCode] Merge k Sorted Lists

原文:http://www.cnblogs.com/Xylophone/p/3848342.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!