首页 > 其他 > 详细

23. Merge k Sorted Lists

时间:2019-10-15 23:06:26      阅读:102      评论:0      收藏:0      [点我收藏+]

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

Example:

Input:
[
  1->4->5,
  1->3->4,
  2->6
]
Output: 1->1->2->3->4->4->5->6


直接复用归并排序即可

/**
 * 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) {
        ListNode *res=NULL;
        for(int i=0;i<lists.size();++i)
        {
            if(NULL==res)
            {
                res=lists[i];
                continue;
            }
            res=merge(res,lists[i]);
        }
        return res;
    }
    
    ListNode* merge(ListNode *l1,ListNode *l2) {
        if(NULL==l1)return l2;
        if(NULL==l2)return l1;
        if(l1->val<l2->val)
        {
            l1->next=merge(l1->next,l2);
            return l1;
        }
        
        l2->next=merge(l1,l2->next);
        return l2;
    }
};

 

23. Merge k Sorted Lists

原文:https://www.cnblogs.com/lychnis/p/11681717.html

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