/*
// 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 *cur=head;
unordered_map<Node*,Node*> map;
while(cur)
{//哈希表对每个结点映射到 new 结点,此时new结点只包含val,没有next和random指针
map [cur]= new Node(cur->val);
cur=cur->next;
}
cur=head;//cur指针归零
while(cur)
{//对每一个cur键值的映射也就是new结点next和random赋值
map[cur]->next=map[cur->next];
map[cur]->random=map[cur->random];
cur=cur->next;
}
return map[head];
}
};
剑指 Offer 35. 复杂链表的复制
最新推荐文章于 2024-11-10 22:49:00 发布