题解 | #复杂链表的复制# 先复制单向链表,再处理随机指针
复杂链表的复制
https://www.nowcoder.com/practice/f836b2c43afc4b35ad6adc41ec941dba
/* struct RandomListNode { int label; struct RandomListNode *next, *random; RandomListNode(int x) : label(x), next(NULL), random(NULL) { } }; */ class Solution { public: RandomListNode* Clone(RandomListNode* pHead) { RandomListNode *tmp = pHead, *res = nullptr; RandomListNode *path = nullptr; if(tmp != nullptr){ res = new RandomListNode(tmp->label); tmp = tmp -> next; path = res; }else{ return nullptr; } // 完成单向链表的拷贝 while(tmp != nullptr){ RandomListNode* tt = new RandomListNode(tmp->label); path->next = tt; path = path -> next; tmp = tmp -> next; } // 完成random指针的拷贝 tmp = pHead; path = res; while(tmp != nullptr){ if(tmp->random != nullptr){ path -> random = new RandomListNode(tmp->random->label); } path = path->next; tmp = tmp -> next; } return res; } };