题解 | #合并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
    }
};

全部评论

相关推荐

迟缓的马里奥求你们别...:我双2,FPGA方向,在成都找工作投了上百家,收到面试的不超过10家,是成都这个地方太有说法了。西南柬埔寨
秋招,不懂就问
点赞 评论 收藏
分享
2025-12-31 14:19
门头沟学院 产品经理
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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