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

[LeetCode] Merge k Sorted Lists

时间:2014-07-16 15:17:03      阅读:188      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   color   os   for   

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

标签:des   style   blog   color   os   for   

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

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