23. Merge k Sorted Lists

时间:2019-10-15
本文章向大家介绍23. Merge k Sorted Lists,主要包括23. Merge k Sorted Lists使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

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;
    }
};

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