Copy List with Random Pointer [LeetCode]

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.

Solution: Uses map to recorde node mapping between old linked list and new linked list.

 1     RandomListNode *copyRandomList(RandomListNode *head) {

 2         map<RandomListNode *, RandomListNode *> old_to_new;

 3         RandomListNode * current = head;

 4         RandomListNode * new_head = NULL;

 5         RandomListNode * pre = NULL;

 6         while(current != NULL) {

 7             RandomListNode * node = new RandomListNode(current->label);

 8             old_to_new[current] = node;    

 9             if(new_head == NULL){

10                 new_head = node;

11                 pre = node;

12             }else if(pre != NULL){

13                 pre->next = node;

14                 pre = pre->next;

15             }

16             

17             current = current->next;

18         }

19         

20         current = head;

21         RandomListNode * new_current = new_head;

22         while(current != NULL && new_current != NULL) {

23             if(current->random != NULL)

24                 new_current->random = old_to_new[current->random];   

25             else

26                 new_current->random = NULL; 

27             current = current->next;

28             new_current = new_current->next;

29         }

30         return new_head;

31     }

 

你可能感兴趣的:(LeetCode)