• 【leetcode】Merge k Sorted Lists(按大小顺序连接k个链表)


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

    题意:把k个排序成一个有序链表。


    用优先队列先把k个链表遍历一遍把值存起来,在建一个新链表吧数从优先队列里一个个放进去,注意空指针的判断。


    /**
     * 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) {
            int i,j,len=lists.size();
            priority_queue<int,vector<int>,greater<int>> q;
            int flag=1;
            while(flag!=0)
            {
                flag=0;
                for(i=0;i<len;++i)
                {
                    if(lists[i])
                    {
                        flag=1;
                        q.push(lists[i]->val);
                        lists[i]=lists[i]->next;
                    }
                }
            }
            if(q.empty())return NULL;
            ListNode *root,*now;
            root=new ListNode(q.top());
            root->next=NULL;
            now=root;
            q.pop();
            while(!q.empty())
            {
                 now->next=new ListNode(q.top());
                 now=now->next;
                 q.pop();
                 now->next=NULL;
            }
            return root;
        }
    };


  • 相关阅读:
    FFT模板
    树链剖分模板
    295. 数据流的中位数
    我罗斯方块最终篇
    面向对象程序设计寒假作业3
    2020面向对象寒假作业(二)
    2020面向对象程序设计寒假作业1
    违规二哥
    士大夫和为啥
    啥给测试
  • 原文地址:https://www.cnblogs.com/pangblog/p/3341720.html
Copyright © 2020-2023  润新知