Copy List with Random Pointer

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.

题目要求返回的是深度拷贝,因此拷贝时必须重新申请空间。关于deep copy 和 shallow copy,可以参考http://blog.csdn.net/andrewseu/article/details/26852217

如果先建立节点再寻找每个节点的random指针,思路简单,但是时间复杂度为O(n^2),会超时。因此必须转换思维,先把新的节点查到旧节点的后面,这样相对关系就很明显,寻找random指针也很简单,并且时间复杂度为O(n)。不过要注意的一点是不要在寻找random指针的同时拆分链表,因为拆分链表破坏了链表的结构,如果有random 指针指向当前前面的节点,新节点的random指针指向的节点时错误的!表示在此纠结了很久,哭、、、

/**
* 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) {
		if (!head)
			return NULL;
		RandomListNode *copyHead=NULL,*copyCurrent=NULL;
		RandomListNode *current = head;
		while (current)
		{
			if (current == head)
			{
				copyHead = new RandomListNode(head->label);
				copyCurrent = copyHead;
			}
			else
			{
				RandomListNode *rNode = new RandomListNode(current->label);
				copyCurrent = rNode;
			}
			copyCurrent->next = current->next;
			current->next = copyCurrent;
			current = copyCurrent->next;
		}

		current = head;
		while (current)
		{
			if (current->random)
			{
				current->next->random = current->random->next;
			}
			current = current->next->next;
		}
		current = head;
		copyCurrent = copyHead;
		while (current)
		{
			current->next = copyCurrent->next;
			current = current->next;
			if (!current)
				break;
			copyCurrent->next = current->next;
			copyCurrent = copyCurrent->next;
		}
		return copyHead;
	}
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值