LC138复习笑(*^_^*)是生活的解药

/*
// Definition for a Node.
class Node {
public:
    int val;
    Node* next;
    Node* random;
    
    Node(int _val) {
        val = _val;
        next = NULL;
        random = NULL;
    }
};
*/
class Solution {
public:
    //hash-map way
    Node* copyRandomList(Node* head) {
        if(!head) return{};
        
        //hash part
        Node* root=head;
        unordered_map<Node*,Node*> m;
        
        while(head->next)
        {
            Node* clone=new Node(head->val);
            m[head]=clone;
            head=head->next;
        }
        Node* clone=new Node(head->val);
        m[head]=clone;
        //最重要的一步,有时链接值为NULL,就会缺乏对应造成问题
        m[NULL]=NULL;
        
        //link
        head=root;
        for(int i=0;i<m.size()-1;++i)
        {
            m[head]->next=m[head->next];
            m[head]->random=m[head->random];
            head=head->next;
        }
        
        return m[root];
        
    }
};

猜你喜欢

转载自www.cnblogs.com/Marigolci/p/12313182.html