题解 | #合并k个已排序的链表#

合并k个已排序的链表

https://www.nowcoder.com/practice/65cfde9e5b9b4cf2b6bafa5f3ef33fa6

/**
 * struct ListNode {
 *	int val;
 *	struct ListNode *next;
 *	ListNode(int x) : val(x), next(nullptr) {}
 * };
 */
#include<algorithm>
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param lists ListNode类vector 
     * @return ListNode类
     */
     #include<algorithm>
    static bool compare(int a,int b)
    {
            return a<b; //升序排列
    }
    ListNode* mergeKLists(vector<ListNode*>& lists) {
        // write code here
        vector<int> result;
        int sum=lists.size();
        ListNode *next=NULL;
        if(lists.empty())
            return NULL;
        for(int i=0;i<sum;i++)
        {
            while(lists[i]!=NULL)
            {
                next=lists[i]->next;
                result.push_back(lists[i]->val);
                lists[i]=next;
            }
        }
        if(result.empty())
            return NULL;
        std::sort(result.begin(),result.end(),compare);
        ListNode *head=new ListNode(result[0]);
        head->next=NULL;
        ListNode *last=head;
        
        for(int i=1;i<result.size();i++)
        {
            ListNode *tmp=new ListNode(result[i]);
            last->next=tmp;
            tmp->next=NULL;
            last=tmp;
        }
        return head;
    }
};

全部评论

相关推荐

09-17 19:25
已编辑
太原理工大学 游戏测试
叁六玖:公司名发我,我要这个HR带我打瓦
我的秋招日记
点赞 评论 收藏
分享
赛博小保安:不行你就找点东西继续干干直接等明年走社招吧,学历差的在秋招真的没戏。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务