leetcode 23合并K个链表(带输入输出版本)

因为白板面试,手撕代码,并没有leetcode上自动输入输出,面试官可能需要你自己写案例,自己写输入输出,所以写了个输入输出版本的题解。

#include <iostream>
#include <vector>
using namespace std;
struct ListNode{
    int val;
    ListNode* next;
    ListNode(int x):val(x),next(nullptr){}
};
class Solution {
public:
    ListNode* mergeKLists(vector<ListNode*>& lists) {
        return merge(lists,0,lists.size()-1);
    }
private:
    ListNode* merge(vector<ListNode*>& lists,int l,int r){
        if(l>r) return nullptr;
        if(l==r) return lists[l];
        if(l+1==r) return mergeTwoLists(lists[l],lists[r]);
        int m = l+(r-l)/2;
        auto l1 = merge(lists,l,m-1);
        auto l2 = merge(lists,m,r);
        return mergeTwoLists(l1,l2);
    }
    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2){
        ListNode d(0);
        // ListNode* head = &d;
        ListNode* tail = &d;
        ListNode* n;
        while(l1&&l2){
            if(l1->val>l2->val) swap(l1,l2);
            // head->next = l1;
            n = l1->next;

            l1->next = tail->next;
            tail->next = l1;
            tail = tail->next;

            l1 = n;
        }
        tail->next = l1?l1:l2;
        return d.next;
    }
};
int main() {
    vector<ListNode*> lists;
    ListNode* l1 = new ListNode(1);
    ListNode* l2 = new ListNode(4);
    ListNode* l3 = new ListNode(5);
    l1->next = l2;
    l2->next = l3;

    ListNode* l4 = new ListNode(1);
    ListNode* l5 = new ListNode(3);
    ListNode* l6 = new ListNode(4);
    l4->next = l5;
    l5->next = l6;

    ListNode* l7 = new ListNode(2);
    ListNode* l8 = new ListNode(6);
    l7->next = l8;

    lists.push_back(l1);
    lists.push_back(l4);
    lists.push_back(l7);

    class Solution s;
    s.mergeKLists(lists);
    while(lists[0]){
        cout<<lists[0]->val<<" ";
        lists[0] = lists[0]->next;
    }
    cout<<endl;
    delete l1;
    delete l2;
    delete l3;
    delete l4;
    delete l5;
    delete l6;
    delete l7;
    return 0;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值