题目描述:请实现 copyRandomList
函数,复制一个复杂链表。在复杂链表中,每个节点除了有一个 next
指针指向下一个节点,还有一个 random
指针指向链表中的任意节点或者 null
。
思路来自b站up主@小美算法讲解 ,他的视频和图解对不太明白题目解法的人(比如我)很有帮助。
视频地址:小美算法 剑指offer35题 复杂链表的复制java版_哔哩哔哩_bilibili
/*
// Definition for a Node.
class Node {
public:
int val;
Node* next;
Node* random;
Node(int _val) {
val = _val;
next = NULL;
random = NULL;
}
};
*/
class Solution {
public:
Node* copyRandomList(Node* head) {
//创建一个哈希表,用于存放原链表与子链表对应结点;
//创建一个cur指针,指向当前结点
unordered_map<Node*, Node*> m;
Node* cur;
//第一次遍历,复制Node结点的val值
for(cur=head; cur!=NULL; cur=cur->next)
{
//插入的键值对为两链表中对应位置的结点
m.emplace(cur, new Node(cur->val));
}
//第二次遍历,复制next指针和random指针
cur=head;
//不知道为什么,我这里使用for循环会出错 runtime error: member access within null pointer of type 'Node' 空指针错误,只好改用while循环
//for(Node* cur=head; cur->next!=NULL; cur=cur->next)
while(cur!=NULL)
{
//由于at方法会在访问哈希表元素时判断是否越界,这里存在random为空的情况,不能使用
m[cur]->next = m[cur->next];
m[cur]->random = m[cur->random];
cur=cur->next;
}
//返回的是哈希表的头结点,其实我没有想到。。。
return m[head];
}
};