剑指offer-复杂链表的复制

一、题目

在这里插入图片描述

二、思路

方法:哈希表

利用哈希表的查询特点,考虑构建 原链表节点新链表节点 的键值对映射关系,再遍历构建新链表各节点的 next 和 random 引用指向即可。

算法流程:

  • 1.若头节点 head 为空节点,直接返回 nullnull ;
  • 2.初始化: 哈希表 dic , 节点 cur 指向头节点;
  • 3.复制链表:
    建立新节点,并向 dic 添加键值对 (原 cur 节点, 新 cur 节点) ;
    cur 遍历至原链表下一节点(按next节点遍历);
  • 4.构建新链表的引用指向:
    构建新节点的nextrandom引用指向;
    cur 遍历至原链表下一节点;
    返回值: 新链表的头节点 dic[cur] ;

三、代码

/*
struct RandomListNode {
    int label;
    struct RandomListNode *next, *random;
    RandomListNode(int x) :
            label(x), next(NULL), random(NULL) {
    }
};
*/
class Solution {
public:
    //建立旧节点对应新节点的哈希表
    unordered_map<RandomListNode*,RandomListNode*>dic;
    RandomListNode* Clone(RandomListNode* pHead) {
        if(pHead==nullptr)
        {
            return nullptr;
        }
        //建立头结点
        RandomListNode *cur=pHead;
        
        //建立新旧节点的哈希对应关系
        while(cur)
        {
            dic[cur]=new RandomListNode(cur->label);
            cur=cur->next;
        }
        
        //建立链接关系
        cur=pHead;
        while(cur)
        {
            dic[cur]->next=dic[cur->next];
            dic[cur]->random=dic[cur->random];
            cur=cur->next;
        }
        return dic[pHead];
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值