Copy List with Random Pointer

来源:互联网 发布:15寸mac魔兽世界 编辑:程序博客网 时间:2024/06/06 15:44
/** * 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; multimap<RandomListNode*,RandomListNode*>hmap; RandomListNode* p,*pre,*result,*temp=head;
                 //deep 拷贝next,建立多对一哈希表 while(temp){ p=new RandomListNode(temp->label); hmap.insert(make_pair(temp->random,p));  if(temp!=head){ pre->next=p; pre=pre->next; } else  {pre=p;result=p; } temp=temp->next; } temp=head; pre=result;
                 //deep copy random 保证前向、后向也可以 while(temp){ if(hmap.find(temp)!=hmap.end()){      typedef multimap<RandomListNode*,RandomListNode*>::iterator iter;     typedef pair<iter,iter> Range;     Range range=hmap.equal_range(temp);     for(iter i=range.first;i!=range.second;i++)        i->second->random=pre; } temp=temp->next; pre=pre->next; } return result; } };

原创粉丝点击