题目:
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.
思路:如果没有random pointer那是极容易的,顺着链表走读一遍 ,逐个拷贝节点并链接即可,有了random pointer后,其实也就是加上了记录random pointer的关系而已,考虑到random pointer可以往前指,也可以往后指,则必须全部遍历完才能完整地建立起random pointer对应关系表,记录对应关系,当然用map的数据结构啦,c++不太熟,查了下文档也不难写这么个基本的数据结构,用两个map,一个保存原始链表的random指向,另一个记录原始链表和新建链表按照节点顺序建立的对应关系,这样在走读完原始链表所有节点后,再刷一遍两个map就可以恢复新建链表中与原始链表random指向对应的random 指针了,为了省空间,当然map的元素都用int*表示
代码:
/**
* 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==NULL)
{
return NULL;
}
std::map<RandomListNode*, RandomListNode*> parall;
std::map<RandomListNode*, RandomListNode*> randpoint;
RandomListNode * pleft=head;
RandomListNode * copyList=new RandomListNode(pleft->label);
RandomListNode * pright=copyList;
parall.insert(std::pair<RandomListNode*,RandomListNode*>(pleft,pright));
randpoint.insert(std::pair<RandomListNode*,RandomListNode*>(pleft,pleft->random));
pleft=pleft->next;
while(pleft!=NULL)
{
//create corresponding node
RandomListNode* tmpRight=new RandomListNode(pleft->label);
pright->next=tmpRight;
pright=pright->next;
parall.insert(std::pair<RandomListNode*,RandomListNode*>(pleft,pright));
randpoint.insert(std::pair<RandomListNode*,RandomListNode*>(pleft,pleft->random));
pleft=pleft->next;
}
for( std::map<RandomListNode*, RandomListNode*>::iterator ii=randpoint.begin(); ii!=randpoint.end(); ++ii)
{
if((*ii).second!=NULL)
{
parall[(*ii).first]->random=parall[(*ii).second];
}
}
return copyList;
}
};