题目描述:
输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针random指向一个随机节点),请对此链表进行深拷贝,并返回拷贝后的头结点。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)
题解:
/*
struct RandomListNode {
int label;
struct RandomListNode *next, *random;
RandomListNode(int x) :
label(x), next(NULL), random(NULL) {
}
};
*/
class Solution {
public:
RandomListNode* Clone(RandomListNode* pHead)
{
if(pHead == NULL)
return NULL;
RandomListNode *p = pHead;
while(p)
{
RandomListNode *temp = new RandomListNode(p->label);
temp->next = p->next;
p->next = temp;
p = p->next->next;
}
p = pHead;
while(p)
{
if(p->random == NULL)
p->next->random = NULL;
else
p->next->random = p->random->next;
p=p->next->next;
}
p = pHead;
RandomListNode *fakehead = new RandomListNode(-1);
RandomListNode *q = fakehead;
while(p)
{
RandomListNode* t = p->next->next;
q->next = p->next;
q = q->next;
p->next = t;
p=p->next;
}
RandomListNode *res = fakehead->next;
delete fakehead;
return res;
}
};
解题思路:
(1)先在每个节点后边构造一个相同的节点
(2)对随机节点的复制,注意随机节点为空的情况
(3)将两个量表分离;