Copy List with Random Pointer
原题链接Copy List with Random Pointer
深拷贝一个链表,链表节点的成员包括
- 指向下一个节点的指针
- 指向一个随机节点的指针
- 节点值
主要的影响在随机节点的拷贝,处理不好会引发递归拷贝,解决方法是采用一个map记录原节点和复制后的节点
代码如下
/**
* Definition for singly-linked list with a random pointer.
* struct RandomListNode {
* int label;
* RandomListNode *next, *random;
* RandomListNode(int x) : label(x), next(NULL), random(NULL) {}
* };
*/
class Solution {
public:
RandomListNode *copyRandomList(RandomListNode *head) {
unordered_map<RandomListNode*, RandomListNode*> hash;
return copyList(head, hash);
}
private:
RandomListNode* copyList(RandomListNode* head, unordered_map<RandomListNode*, RandomListNode*>& hash)
{
if(!head)
return nullptr;
/* 拷贝过,直接返回 */
if(hash.find(head) != hash.end())
return hash[head];
auto node = new RandomListNode(head->label);
hash[head] = node;
node->next = copyList(head->next, hash);
node->random = copyList(head->random, hash);
return node;
}
};