剑指offer刷题笔记
题目描述:
输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的head。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)
思路:
- 复制复杂链表的label和next。并将新的复制的结点放在原结点后面,使原链表长度*2。
- 给复制的结点的random复制
- 拆分新链表
图解:
源码:
/*
struct RandomListNode {
int label;
struct RandomListNode *next, *random;
RandomListNode(int x) :
label(x), next(NULL), random(NULL) {
}
};
*/
class Solution {
public:
//第一步,复制复杂指针的label和next
void CloneNodes(RandomListNode* pHead){
RandomListNode* pNode = pHead;
while(pNode){
//复制一个相同的结点
RandomListNode* pCloned = new RandomListNode(0);
pCloned->label = pNode->label;
pCloned->next = pNode->next;
pCloned->random = NULL;
//将复制的结点插入原结点后面
pNode->next = pCloned;
pNode = pCloned->next;
}
}
//第二步,处理复杂指针的random
void ConnectSiblingNodes(RandomListNode* pHead){
RandomListNode* pNode = pHead;
while(pNode){
RandomListNode* pCloned = pNode->next;
//为复制的结点赋值其random,其random是原结点的random的一个复制的结点
if(pNode->random != NULL){
pCloned->random = pNode->random->next;
}
pNode = pCloned->next;
}
}
//第三步,拆分链表
RandomListNode* ReconnectNodes(RandomListNode* pHead){
RandomListNode* pNode = pHead; //原链表
RandomListNode* pClonedHead = NULL; //复制链表表头
RandomListNode* pClonedNode = NULL; //复制链表的结点
//拆分表头
if(pNode){
pClonedHead = pNode->next;
pClonedNode = pClonedHead;
pNode->next = pClonedNode->next;
pNode = pNode->next;
}
//拆分各结点
while(pNode){
pClonedNode->next = pNode->next;
pClonedNode = pClonedNode->next;
pNode->next = pClonedNode->next;
pNode = pNode->next;
}
return pClonedHead;
}
RandomListNode* Clone(RandomListNode* pHead)
{
CloneNodes(pHead);
ConnectSiblingNodes(pHead);
return ReconnectNodes(pHead);
}
};