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

合并k个已排序的链表

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

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
#include <cstddef>
#include <queue>
class Solution {
public:
    ListNode *mergeKLists(vector<ListNode *> &lists) {
        if (lists.empty())  return NULL;
        if (lists.front() == lists.back())   return lists.back();
        ListNode* first = lists.back();
        lists.pop_back();
        ListNode* second =  lists.back();
        lists.pop_back();
        queue<ListNode*> merge;
        while(first !=NULL && second != NULL){
            if (first->val > second->val){
                merge.push(second);
                second = second->next;
            }else{
                merge.push(first);
                first = first->next;
            }
        }
        while(first != NULL){
            merge.push(first);
            first = first->next;
        }
        while(second != NULL){
            merge.push(second);
            second = second->next;
        }
        ListNode* start = merge.front();
        ListNode* index = start;
        merge.pop();
        while(!merge.empty()){
            index->next = merge.front();
            index = index->next;
            merge.pop();
        }
        index->next = NULL;
        lists.push_back(start);
        return mergeKLists(lists);
    }
};
/*
1)当lists中没有列表时,直接返还NULL(我一开始没考虑这个,w了一个点)
2)当lists中只有一个列表时,这个列表就是我们需要的列表
3)当lists中有多个列表时,取出两个合并并放回lists,重复2)3)
*/

#23届找工作求助阵地#
全部评论

相关推荐

06-28 22:48
已编辑
广东金融学院 Java
小浪_Coding:学院本+这俩项目不是buff叠满了嘛
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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