LeetCode-Copy List with Random Pointer

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.

class Solution {
public:
    RandomListNode *copyRandomList(RandomListNode *head) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        map<RandomListNode*,RandomListNode*> ptrs;
        RandomListNode* ret=NULL;
        RandomListNode* ptr=NULL,*ptr2=NULL,*ptr3=NULL;
        if(head!=NULL){
            ret=new RandomListNode(head->label);
            if(head->random!=NULL){
                ret->random=new RandomListNode(head->random->label);
                ptrs[head->random]=ret->random;
            }
            ptrs[head]=ret;
            head=head->next;
            ptr=ret;
        }
        else return NULL;
        while(head!=NULL){
            if(ptrs.find(head)==ptrs.end()){
                ptr2=new RandomListNode(head->label);
                ptrs[head]=ptr2;
                ptr->next=ptr2;
            }
            else{
                ptr2=ptrs[head];
                ptr->next=ptr2;
            }
            if(head->random!=NULL){
                if(ptrs.find(head->random)==ptrs.end()){
                    ptr2->random=new RandomListNode(head->random->label);
                    ptrs[head->random]=ptr2->random;
                }
                else{
                    ptr2->random=ptrs[head->random];
                }
            }
            head=head->next;
            ptr=ptr2;
        }
        return ret;
    }
};
View Code
原文地址:https://www.cnblogs.com/superzrx/p/3352745.html