题解 | #复杂链表的复制#
复杂链表的复制
https://www.nowcoder.com/practice/f836b2c43afc4b35ad6adc41ec941dba
/* struct RandomListNode { int label; struct RandomListNode *next, *random; RandomListNode(int x) : label(x), next(NULL), random(NULL) { } }; */ #include <unordered_map> class Solution { public: RandomListNode* Clone(RandomListNode* pHead) { if(pHead==nullptr){ return nullptr; } unordered_map<RandomListNode*, RandomListNode*> map;//创建哈希表,将原来的链表每个点都copy一份。 RandomListNode* cur=pHead; while(cur!=nullptr){ map[cur]=new RandomListNode(cur->label); cur=cur->next; } cur=pHead; while(cur!=nullptr){ map[cur]->next=map[cur->next]; map[cur]->random=map[cur->random]; cur=cur->next; } return map[pHead]; } };