题解 | #复杂链表的复制#
复杂链表的复制
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: // step1: 生成新节点链接到原节点后面 void clone_new_node_connect(RandomListNode* pHead) { RandomListNode* pNode = pHead; RandomListNode* pTmp = nullptr; while (pNode != nullptr) { pTmp = new RandomListNode(pNode->label); pTmp->next = pNode->next; pNode->next = pTmp; pNode = pTmp->next; } } // step2: 处理random节点 void handle_random(RandomListNode* pHead) { RandomListNode* pNode = pHead; while (pNode != nullptr) { if (pNode->random) { // handle clone node's random point pNode->next->random = pNode->random->next; } pNode = pNode->next->next; // 跳过clone节点 } return; } // step3: 拆分链表, 返回clone节点 RandomListNode* reconnect_list(RandomListNode* pHead) { RandomListNode* pNode = pHead; RandomListNode* pCloneHead = nullptr; RandomListNode* pCloneNode = nullptr; if (pNode != nullptr) { pCloneNode = pCloneHead = pNode->next; pNode->next = pCloneNode->next; // 原始链表的下一个节点是链表的下一个节点 pNode = pNode->next; } while (pNode != nullptr) { pCloneNode->next = pNode->next; pCloneNode = pCloneNode->next; pNode->next = pCloneNode->next; pNode = pNode->next; } return pCloneHead; } RandomListNode* Clone(RandomListNode* pHead) { clone_new_node_connect(pHead); handle_random(pHead); return reconnect_list(pHead); } };
2023 剑指-链表 文章被收录于专栏
2023 剑指-链表