This topic is the deep replication of the linked list, that is, all nodes are allocated space, which is not difficult to achieve. What is difficult is the assignment of the random pointer of the new linked list. There is no good way to think about it, MAP is used to store the ing relationships between two linked lists. During the first time, only new nodes are created and a linked list is created, so that the random value of the nodes in the new linked list is equal to the value of the old linked list. The second traversal is then mapped one by one based on the map.
1 class Solution { 2 public: 3 RandomListNode *copyRandomList(RandomListNode *head) { 4 if(head == NULL) 5 return NULL; 6 RandomListNode* nHead = new RandomListNode(head->label); 7 RandomListNode* optr; 8 RandomListNode* nptr; 9 optr = head;10 nptr = nHead;11 map<RandomListNode*,RandomListNode*> m1;12 m1[optr] = nptr;13 nptr->random = optr->random;14 optr = optr->next;15 while(optr != NULL)16 {17 RandomListNode* tmp = new RandomListNode(optr->label);18 nptr->next = tmp;19 nptr = tmp;20 nptr->random = optr->random;21 m1[optr]=nptr;22 optr = optr->next;23 24 }25 nptr->next = NULL;26 nptr = nHead;27 while(nptr != NULL)28 {29 if(nptr->random != NULL)30 {31 nptr->random = m1[nptr->random];32 }33 nptr = nptr->next;34 }35 return nHead;36 }37 };
Copy list with random pointer