解题思路:
- 本题要求进行深拷贝,而且存在一个随机指针,这个指针的指向可能还没在当前链表中,所以要先进行存储,这里采用hashmap进行存储,其中key表示原结点,val表示新创建的结点
- 注意:
1.递归结束条件为head==nullptr
2.map的存储问题
/*
// 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) {
if(!head)return {};
vector<Node*>vNode;
Node* res = new Node(-1);
Node* mhead = res;
while(head != nullptr){
Node* tempNode = new Node(head->val);
vNode.push_back(tempNode);
if(!head->random){
tempNode->random = nullptr;
}else{
tempNode->random = vNode[head->random->val];
}
res->next = tempNode;
head = head->next;
res = res->next;
}
return mhead->next;
}
};