就是用回溯法。用一个hash_map来存储访问过的节点。
class Solution {
private:
unordered_map<Node*, Node*> all;
public:
Node* copyRandomList(Node* head) {
if(head == NULL) return NULL;
if(all.count(head) == 0) {
all[head] = new Node(head->val);
all[head]->next = copyRandomList(head->next);
all[head]->random = copyRandomList(head->random);
//return newNode;
}
return all[head];
}
};
本文介绍了一种使用回溯法和哈希映射的数据结构来解决链表复制问题的方法。通过一个unordered_map存储访问过的节点,确保了在复制过程中能够正确地处理每一个节点及其相关联的random指针。
574

被折叠的 条评论
为什么被折叠?



