struct RandomListNode {
int label;
struct RandomListNode *next, *random;
RandomListNode(int x) :
label(x), next(nullptr), random(nullptr) {
}
};
RandomListNode* Clone(RandomListNode* pHead)
{
if (pHead == nullptr)
return nullptr;
RandomListNode* cur = pHead;
//复制链表
while (cur){
RandomListNode* newnode = new RandomListNode(cur->label);
newnode->next = cur->next;
cur->next = newnode;
cur = cur->next->next;
}
//置random
cur = pHead;
while (cur != nullptr){
//注意当一个节点的随机指针为空时不能对它进行操作
if (cur->random) {
cur->next->random = cur->random->next;
}
cur = cur->next->next;
}
//拆分链表
cur = pHead;
RandomListNode* Clone = pHead->next;
while (cur != nullptr) {
RandomListNode* Clonecur = cur->next;
cur->next = Clonecur->next;
cur = cur->next;
//注意当cur为空是不能操作cur->next,这样会指针操作越界
if (cur != nullptr) {
Clonecur->next = cur->next;
}
}
return Clone;
}
复杂链表链表的复制
最新推荐文章于 2021-11-27 17:16:23 发布