28-Merge Two Sorted Lists

本文介绍了一种通过映射的方式合并两个有序链表的方法。利用map来存储链表节点,根据值进行排序后重新连接链表。这种方法的时间复杂度为O(m+n),空间复杂度同样为O(m+n)。

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

easy
21. Merge Two Sorted Lists
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
思路:利用map映射,值->指针集合,然后按值从小到大将指针链接起来。时间复杂度O(m+n),空间O(m+n)

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
        map<int,vector<ListNode*> > maps;
        push_into_map(l1,maps);
        push_into_map(l2,maps);
        ListNode *now=NULL,*pre=NULL,*head;
        map<int,vector<ListNode*> >::const_iterator it = maps.begin();
        if(it!=maps.end()){
                head = (it->second)[0];
        }
        else head = NULL;
        while(it!=maps.end())
        {
            cout<<(it->second).size()<<endl;
            for(int k=0;k<(it->second).size();++k)
            {
                pre = now;
                now = (it->second)[k];
                if(pre!=NULL)pre->next = now;
            }
            it++;
        }
        return head;
    }
    void push_into_map(ListNode* l,map<int,vector<ListNode*> > &maps)
    {
        while(l!=NULL)
        {
            maps[l->val].push_back(l);
            l= l->next;
        }
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值