Copy list with random pointer

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.