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.
这题用map做其实比较简单,但是一开始没想明白越想越乱,最后看了下别人的实现,思路还是很清晰的,代码如下所示:
1 /** 2 * Definition for singly-linked list with a random pointer. 3 * struct RandomListNode { 4 * int label; 5 * RandomListNode *next, *random; 6 * RandomListNode(int x) : label(x), next(NULL), random(NULL) {} 7 * }; 8 */ 9 10 class Solution {11 public:12 RandomListNode *copyRandomList(RandomListNode *head) {13 unordered_mapm;14 RandomListNode helper1(0), * p1 = &helper1, helper2(0), *p2 = &helper2;15 p1->next = head;16 while(p1->next){17 p1 = p1->next;18 RandomListNode * tmpNode = new RandomListNode(p1->label);19 m[p1] = tmpNode;20 p2 = p2->next = tmpNode;21 }22 p1 = &helper1;23 while(p1->next){24 p1 = p1->next;25 if(p1->random){26 m[p1]->random = m[p1->random];27 }28 }29 return helper2.next;30 }31 };