/* // 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]; } };