LeetCode Copy List with Random Pointer

Copy List with Random Pointer

  Total Accepted: 8155  Total Submissions: 37086 My Submissions

A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.

Return a deep copy of the list.


忽略random pointer这个干扰项,先把链表复制出来。然后再复制random pointer,为了这个要在第一次复制时记录好map。

= =划归真是个好东西。。。

尼玛昨天晚上写的,今天一运行竟然有BUG!胡乱折腾以后,认为自己不会用指针!终于在午睡睡醒以后把BUG调出来了。。。果然lab2是个磨练意志的好玩意,祖国大好青年我再也不怕BUG了!

/**
 * 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 {
	map<RandomListNode *, RandomListNode *> mapping;

	public:
	RandomListNode *copyRandomList(RandomListNode *head) {
		if (!head)	return NULL;

		RandomListNode *ans = new RandomListNode(head->label);
		mapping[head] = ans;
		/* copy without random pointer */
		RandomListNode *old = head;
		RandomListNode *cur = ans;
		while (old->next) {
			old = old->next;
			cur -> next = new RandomListNode(old->label);
			cur = cur->next;
			mapping[old] = cur;
		}
		/* copy random pointer */
		old = head;
		cur = ans;
		while (old) {
			if (old->random)
				cur -> random = mapping[old->random];
			old = old->next;
			cur = cur->next;
		}

		return ans;
	}
};




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值