LeetCode 138. Copy List with Random Pointer

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;
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值