这道题看答案了,哈希做法很不错。
class Solution {
public:
Node* copyRandomList(Node* head) {
if (head == nullptr) return nullptr;
Node* cur = head;
unordered_map<Node*, Node*> map;
while (cur != nullptr) {
map[cur] = new Node(cur->val);
cur = cur->next;
}
cur = head;
while (cur != nullptr) {
map[cur]->next = map[cur->next];
map[cur]->random = map[cur->random];
cur = cur->next;
}
return map[head];
}
};