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

合并k个已排序的链表

https://www.nowcoder.com/practice/65cfde9e5b9b4cf2b6bafa5f3ef33fa6?tpId=295&tqId=724&sourceUrl=%2Fexam%2Foj%3FquestionJobId%3D10%26subTabName%3Donline_coding_page

/**
 * struct ListNode {
 *	int val;
 *	struct ListNode *next;
 *	ListNode(int x) : val(x), next(nullptr) {}
 * };
 */
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param lists ListNode类vector 
     * @return ListNode类
     */
    ListNode* Merge(ListNode* pHead1, ListNode* pHead2) {
        // write code here
        ListNode dummy(0);
        ListNode *cur=&dummy;
        while(pHead1!=nullptr&&pHead2!=nullptr){
            if(pHead1->val<pHead2->val){
                cur->next=pHead1;
                pHead1=pHead1->next;
            }
            else{
                cur->next=pHead2;
                pHead2=pHead2->next;
            }
            cur=cur->next;
        }
        cur->next=pHead1?pHead1:pHead2;
        return dummy.next;
    }
    ListNode* mergeKLists(vector<ListNode*>& lists,int left,int right) {
        // write code here
         if(left > right)
            return NULL;
        //中间一个的情况
        else if(left == right)
            return lists[left];
        //从中间分成两段,再将合并好的两段合并
        int mid = (left + right) / 2;
        return Merge(mergeKLists(lists, left, mid), mergeKLists(lists, mid + 1, right));
    }
     
    ListNode *mergeKLists(vector<ListNode *> &lists) {
        //k个链表归并排序
        return mergeKLists(lists, 0, lists.size() - 1);
    }
};

全部评论

相关推荐

牛客嘻嘻子:建议可以把mentor布置的任务和AI沟通一下
点赞 评论 收藏
分享
2025-12-18 11:24
山西大学 测试工程师
A_SOUL_Off...:疑似加班加出幻觉了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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