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

合并k个已排序的链表

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

/**
 * struct ListNode {
 *	int val;
 *	struct ListNode *next;
 *	ListNode(int x) : val(x), next(nullptr) {}
 * };
 */
#include <cstddef>
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param lists ListNode类vector 
     * @return ListNode类
     */
     ListNode* Merge2(ListNode* phead1,ListNode* phead2){
        if(!phead1) return phead2;
        if(!phead2) return phead1;
        ListNode *newhead = new ListNode(0);
        ListNode *begin = newhead;
        ListNode *tmp = NULL;
        while (phead1&&phead2) {
            if(phead1->val<=phead2->val){
                tmp = phead1->next;
                begin->next = phead1;
                phead1 = tmp;
            }
            else{
                tmp = phead2->next;
                begin->next = phead2;
                phead2 = tmp;
            }
            begin = begin->next;
            if(!phead2) begin->next = phead1;
            if(!phead1) begin->next = phead2;
        }
        newhead = newhead->next;
        return newhead;
     }
     ListNode* divideMerge(vector<ListNode*> &lists,int left,int right){
        if(left > right){
            return NULL;
        }
        if(left==right){
            return lists[right];
        }
        int mid = (left + right) / 2;
        return Merge2(divideMerge(lists,left,mid), divideMerge(lists,mid+1,right));
     }
    ListNode* mergeKLists(vector<ListNode*>& lists) {
        return divideMerge(lists,0,lists.size()-1);
        // write code here
    }
};

全部评论

相关推荐

后端转测开第一人:wlb不好吗 非得卷
点赞 评论 收藏
分享
2025-12-17 17:53
门头沟学院 Web前端
海梨花:我之前面试也是问我非技术问题,问过我怎么统计北京出租车数量,不借助任何网络或者其他平台的帮助,有足够多的人可以帮忙
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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