LeetCode 138. 复制带随机指针的链表(哈希 / 深拷贝)

1. 题目

给定一个链表,每个节点包含一个额外增加的随机指针,该指针可以指向链表中的任何节点或空节点。

要求返回这个链表的深拷贝。
在这里插入图片描述
《剑指Offer》同题:面试题35. 复杂链表的复制

2. 解题

类似题目:LeetCode 1484. 克隆含随机指针的二叉树(哈希/递归)

  • 哈希表存储映射《原节点,新节点》
class Solution {
public:
    Node* copyRandomList(Node* head) {
        if(head == NULL)
            return NULL;
        unordered_map<Node*, Node*> m;//原节点-新节点 哈希表
        Node *cur = head, *newNode;
        while(cur != NULL)//先创建新节点,赋值
        {
            newNode = new Node(cur->val);
            m[cur] = newNode;
            cur = cur->next;
        }
        cur = head;
        while(cur != NULL)//再次遍历,查表,把新节点指针付进去
        {
            m[cur]->next = m[cur->next];
            m[cur]->random = m[cur->random];
            cur = cur->next;
        }
        return m[head];
    }
};

在这里插入图片描述

  • 原地算法,先复制一遍链表 a ->a.-> b-> b.-> ...
  • 接好新链表random
  • 拆开两条链表
class Solution {
public:
    Node* copyRandomList(Node* head) {
        if(!head)
            return NULL;
        Node* cur = head, *newNode, *H;
        while(cur)//复制一遍原链表 a a` b b`... 
        {
        	newNode = new Node(cur->val);
        	newNode->next = cur->next;
        	cur->next = newNode;
        	cur = newNode->next;
        }
        cur = head;
        newNode = cur->next;
        while(cur)//把新链表的random接好
        {
            if(cur->random)
        	    newNode->random = cur->random->next;
        	cur = cur->next->next;
            if(cur)
        	    newNode = cur->next;
        }
        cur = head;
        H = newNode = cur->next;
        while(newNode->next)//两条链表拆开
        {
            cur->next = newNode->next;
        	newNode->next = newNode->next->next;
            cur = cur->next;
        	newNode = newNode->next;
        }
        cur->next = NULL;
        return H;
    }
};
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Michael阿明

如果可以,请点赞留言支持我哦!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值