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.
首先搞清楚什么是浅拷贝和深拷贝:
浅拷贝,把一个变量中的数据地址直接给另一个变量,删除其中任何一个变量,另一个变量中就没有了地址数据。
深拷贝,创建一个新的空间保存这个变量的值,所以,当删除任何一个变量时,就不会出错,因为它们的地址不同
如下列:
#include<iostream>
#include<cstdlib>
#include<memory>
int main()
{
int* p1 = new int(1);
std::auto_ptr<int> p(new int(*p1) );
int* p2 = p.get();
delete p1;
std::cout<<*p2<<std::endl;
system("PAUSE");
return 0;
}
下面是用map来写的一个程序,第一次提交就通过了,暗暗高兴中。
/**
* 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 == nullptr) return nullptr;
map<RandomListNode *, RandomListNode *> nodesmap;
nodesmap = copyList(head);
randomPtr(nodesmap);
return nodesmap[head];
}
map<RandomListNode *, RandomListNode*> copyList(RandomListNode *head)
{
RandomListNode * node = head;
map<RandomListNode *, RandomListNode*> nodesmap;
RandomListNode *chead = new RandomListNode(*node);
nodesmap[node] = chead;
RandomListNode *cur = chead;
while (node->next != nullptr)
{
RandomListNode *ctemp = new RandomListNode(*(node->next));
nodesmap[node->next] = ctemp;
cur->next = ctemp;
cur = ctemp;
node = node->next;
}
cur->next = nullptr;
return nodesmap;
}
void randomPtr(map<RandomListNode *, RandomListNode*> &nodesmap)
{
auto iter = nodesmap.begin();
for(; iter != nodesmap.end(); iter++)
{
iter->second->random = nodesmap[iter->first->random];
}
}
};
和 clone graph这道题的算法一样,算是其简易版本。
http://blog.csdn.net/kenden23/article/details/18624191
//2014-2-19 update
RandomListNode *copyRandomList(RandomListNode *head)
{
unordered_map<int, RandomListNode *> ump_ir;
return copyRL(head, ump_ir);
}
RandomListNode *copyRL(RandomListNode *h, unordered_map<int, RandomListNode*>&ump_ir)
{//&ump_ir 写出 ump_ir导致出错
if (!h) return nullptr;
if (ump_ir.count(h->label)) return ump_ir[h->label];
RandomListNode *nh = new RandomListNode(h->label);
ump_ir[h->label] = nh;
nh->next = copyRL(h->next, ump_ir);
//nh->random = copyRL(h->random, ump_ir);
if (h->random) nh->random = ump_ir[h->random->label];
return nh;
}
//2014-2-19_2 update
RandomListNode *copyRandomList(RandomListNode *head)
{
unordered_map<RandomListNode *, RandomListNode *> ump_ir;
return copyRL(head, ump_ir);
}
RandomListNode *copyRL(RandomListNode *h,
unordered_map<RandomListNode *, RandomListNode *> &ump_ir)
{
if (!h) return nullptr;
if (ump_ir.count(h)) return ump_ir[h];
RandomListNode *nh = new RandomListNode(h->label);
ump_ir[h] = nh;
nh->next = copyRL(h->next, ump_ir);
nh->random = ump_ir[h->random];//copyRL(h->random, ump_ir);
return nh;
}