题目出处: https://leetcode-cn.com/problems/copy-list-with-random-pointer/
思路:两次遍历链表。
1. 第一次遍历源链表时创建每个节点的副本,同时将各个副本节点按照next指针相连,并用哈希表记录源节点到对应副本节点的映射。
2. 第二次同时遍历源链表和副本链表,并将源节点随机指针指向的节点的哈希映射节点找出,将该副本节点随机指针指向找出的映射节点,直至遍历完所有节点。
3. 返回副本节点。
/*
// 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) {
Node* newp = new Node(-1);
Node* res = newp;
Node* p = head;
unordered_map<Node*, Node*> mp;
while(p != nullptr){
Node* newNode = new Node(p->val);
newp->next = newNode;
mp[p] = newNode;
newp = newp->next;
p = p->next;
}
p = head;
newp = res->next;
while(p != nullptr){
newp->random = mp[p->random];
p = p->next;
newp = newp->next;
}
return res->next;
}
};