标签:leetcode
链接:https://leetcode.com/problems/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.
Hide Tags Hash Table Linked List
深度复制一个链表,这就要求我们要开辟新的内存空间。关键问题就是如何处理random指针的指向问题。这里额我的解决方案是用一个map存映射关系,第一次遍历原链表创建新链表时,原链表和新链表的节点值一一对应。再次遍历原链表时,因为有了映射关系,新链表的random值也就可以定下来了。
class Solution {
public:
RandomListNode *copyRandomList(RandomListNode *head) {
map<RandomListNode *,RandomListNode *> m;
m[NULL]=NULL;
RandomListNode *t=new RandomListNode(0);
RandomListNode *p1=head,*p2=t;
while(p1)
{
p2->next=new RandomListNode(p1->label);
m[p1]=p2->next;
p1=p1->next;
p2=p2->next;
}
p1=head;
p2=t->next;
while(p1)
{
p2->random=m[p1->random];
p1=p1->next;
p2=p2->next;
}
p2=t->next;
delete t;
return p2;
}
};
还有一种更巧妙的解法,如下图所示。蓝色节点属于原链表,红色节点属于新链表。第一遍遍历的时候插入新的节点。以2这个节点p为例,p->next->random=p->random->next;这样新链表的random指针就复制完成了。
参考链接:http://www.2cto.com/kf/201310/253477.html
class Solution {
public:
RandomListNode *copyRandomList(RandomListNode *head) {
if(head == NULL)return NULL;
RandomListNode *p1=head,*p2,*t=new RandomListNode(0),*result=t;
while(p1)
{
p2=p1->next;
p1->next=new RandomListNode(p1->label);
p1->next->next=p2;
p1=p2;
}
p1=head;
while(p1)
{
if(p1->random)
p1->next->random=p1->random->next;
p1=p1->next->next;
}
p1=head;
while(p1)
{
p2=p1->next->next;
result->next=p1->next;
p1->next=p2;
p1=p1->next;
result=result->next;
}
result=t->next;
delete t;
return result;
}
};
138 Copy List with Random Pointer
标签:leetcode
原文地址:http://blog.csdn.net/efergrehbtrj/article/details/46152485