leetcode 23. Merge k Sorted Lists

本文介绍了一种链表合并算法,该算法首先实现两个有序链表的合并,然后递归地将多个链表两两合并,直至得到最终的有序链表。此方法适用于计算机科学中的数据结构操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

class Solution {

public:

    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {

        ListNode* current1=l1;

        ListNode* current2=l2;

        ListNode* res=new ListNode(0);

        ListNode* result=res;

        if(!l1) return l2;

        if(!l2) return l1;

        while(current1&&current2)

        {

            if(current1->val<current2->val)

            {

                res->next=current1;

                current1=current1->next;

            }

            else

            {

                res->next=current2;

                current2=current2->next;

            }

            res=res->next;

        }

        if(!current1)

            res->next=current2;

        if(!current2)

            res->next=current1;

        

        return result->next;

    }

    ListNode* mergeKLists(vector<ListNode*>& lists) {

        int size=(int)lists.size();

        if(size==0)

            return NULL;

        if(size==1)

            return lists[0];

        vector<ListNode*> l1;

        vector<ListNode*> l2;

        for(int i=0;i<=size/2-1;i++)

            l1.push_back(lists[i]);

        for(int i=size/2;i<=size-1;i++)

            l2.push_back(lists[i]);

        ListNode* res1=mergeKLists(l1);

        ListNode* res2=mergeKLists(l2);

        return mergeTwoLists(res1, res2);

    }

};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值