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.
/** * 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) { map<RandomListNode*, RandomListNode*> old2new; RandomListNode*newhead=NULL; RandomListNode*oldpointer=head; RandomListNode*newpointer=NULL; RandomListNode*prevnew=NULL; //生成新链表构造旧链表结点和新链表结点的对应关系 while(oldpointer){ newpointer=new RandomListNode(oldpointer->label); if(prevnew==NULL)newhead=newpointer; else{ prevnew->next=newpointer; } prevnew=newpointer; old2new[oldpointer]=newpointer; oldpointer=oldpointer->next; } //更新random指针 oldpointer=head; newpointer=newhead; while(oldpointer){ newpointer->random=old2new[oldpointer->random]; oldpointer=oldpointer->next; newpointer=newpointer->next; } return newhead; } };
LeetCode: Copy List with Random Pointer [138],布布扣,bubuko.com
LeetCode: Copy List with Random Pointer [138]
原文:http://blog.csdn.net/harryhuang1990/article/details/35596033