剑指 Offer 35. 复杂链表的复制
最后更新于
最后更新于
输入:head = [[7,null],[13,0],[11,4],[10,2],[1,0]]
输出:[[7,null],[13,0],[11,4],[10,2],[1,0]]输入:head = [[1,1],[2,1]]
输出:[[1,1],[2,1]]输入:head = [[3,null],[3,0],[3,null]]
输出:[[3,null],[3,0],[3,null]]输入:head = []
输出:[]
解释:给定的链表为空(空指针),因此返回 null。class Solution {
public:
Node* copyRandomList(Node* head) {
unordered_map<Node*, Node*> mp;
for (Node* cur = head; cur != NULL; cur = cur->next) {
mp[cur] = new Node(cur->val);
}
for (Node* cur = head; cur != NULL; cur = cur->next) {
mp[cur]->next = mp[cur->next];
mp[cur]->random = mp[cur->random];
}
return mp[head];
}
};