Copy List with Random Pointer

406 篇文章 0 订阅
406 篇文章 0 订阅

1,题目要求

A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.

Return a deep copy of the list.

Example 1:在这里插入图片描述

Input:
{"$id":"1","next":{"$id":"2","next":null,"random":{"$ref":"2"},"val":2},"random":{"$ref":"2"},"val":1}

Explanation:
Node 1's value is 1, both of its next and random pointer points to Node 2.
Node 2's value is 2, its next pointer points to null and its random pointer points to itself.

Note:
You must return the copy of the given head as a reference to the cloned list.

给出链表,使得每个节点包含一个附加的随机指针,该指针可以指向列表中的任何节点或为空。

返回列表的深层副本。

2,题目思路

对于这道题,要求对一个含有随机指针的链表进行拷贝。

如果只是拷贝一个单纯的单链表,直接复制即可。但是题目给定的单链表有一个新的参数——random参数,这个指针会指向链表中的某一个节点。而且,复制的时候,是深拷贝,因此,需要利用开辟新新空间的方法来拷贝新的链表。

在问题的实现上,我们使用map来解决问题:
其中,key是原始链表中的节点,value是新链表中的节点。

如果mp[head]非空,则说明当前节点已经被拷贝了,直接返回这个节点即可。
如果为空,则对该节点进行创建——val、next和random。

3,代码实现

/*
// Definition for a Node.
class Node {
public:
    int val;
    Node* next;
    Node* random;

    Node() {}

    Node(int _val, Node* _next, Node* _random) {
        val = _val;
        next = _next;
        random = _random;
    }
};
*/
static auto speedup = [](){
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    return nullptr;
}();

class Solution {
public:
    Node* copyRandomList(Node* head) {
        if(!head)
            return nullptr;
        if(mp[head]!=nullptr)
            return mp[head];    //拷贝链表已经有了这个节点
        mp[head] = new Node(head->val);
        mp[head]->next = copyRandomList(head->next);
        mp[head]->random = copyRandomList(head->random);
        return mp[head];
    }
private:
    unordered_map<Node*, Node*> mp;
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值