和LeetCode 133. Clone Graph一个意思,
深层拷贝意味着,对a进行拷贝,获得b, 使得b的成员变量不仅值与a中对应的成员变量相等,同时它们指向不同的内存空间。
维护一张map, 保存已创建好的结点即可。
因为题目并不像clone graph一样,本体没有说明label唯一,所以应该用label和next组成的pair来作为map的key;
但同时发现本题sample中的label都是唯一的,所以在代码1中,就直接用int label, 作为map的key了。
代码1(int label作为map的key):
class Solution
{
public:
RandomListNode *copyRandomList(RandomListNode *head)
{
if (head == NULL)
{
return NULL;
}
auto node = nodes[head->label];
if (node == NULL)
{
node = new RandomListNode(head->label);
nodes[head->label] = node;
node->next = copyRandomList(head->next);
node->random = copyRandomList(head->random);
}
return node;
}
private:
map<int, RandomListNode*> nodes;
};
代码2(struct Label作为map的key):
struct Label
{
Label(int label, RandomListNode* next) : label(label), next(next) {}
friend bool operator< (const Label& a, const Label& b)
{
return a.label < b.label;
}
int label;
RandomListNode* next;
};
class Solution
{
public:
RandomListNode *copyRandomList(RandomListNode *head)
{
if (head == NULL)
{
return NULL;
}
auto node = nodes[Label(head->label, head->next)];
if (node == NULL)
{
node = new RandomListNode(head->label);
nodes[Label(head->label, head->next)] = node;
node->next = copyRandomList(head->next);
node->random = copyRandomList(head->random);
}
return node;
}
private:
map<Label, RandomListNode*> nodes;
};