版权声明:本文为原创博客,未经允许,请勿转载。 https://blog.csdn.net/u013095333/article/details/88599643
题目描述
输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的head。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)
链接
代码
/*
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* head = pHead;
while(head){
RandomListNode* temp = (RandomListNode*)malloc(sizeof(RandomListNode));
temp->label = head->label;
RandomListNode* next = head->next;
head->next = temp;
temp->next = next;
head = next;
}
head = pHead;
while(head){
if(head->next){
if(head->random){
head->next->random = head->random->next;
}
else{
head->next->random = head->random;
}
head = head->next->next;
}
}
// 奇数节点串起来是原来的,偶数节点串起来是需要的
// RandomListNode* ans = pHead->next;
// head = ans;
// while(head){
// if(head->next){
// head->next = head->next->next;
// }
// head = head->next;
// }
// 原链表需要还原,否则错误
head = pHead;
RandomListNode* ans = head->next;
RandomListNode* pClone = ans;
while(head){
if(head->next){
head->next = head->next->next;
}
if(pClone->next){
pClone->next = pClone->next->next;
}
head = head->next;
pClone = pClone->next;
}
return ans;
}
};
/*
int main()
{
RandomListNode *root = new RandomListNode(1);
RandomListNode *r1 = new RandomListNode(2);
RandomListNode *r2 = new RandomListNode(3);
RandomListNode *r3 = new RandomListNode(4);
RandomListNode *r4 = new RandomListNode(5);
root->next = r1;
r1->next = r2;
r2->next = r3;
r3->next = r4;
root->random = r2;
r1->random = r4;
r2->random = NULL;
r3->random = r1;
r4->random = NULL;
Solution *s = new Solution();
RandomListNode* ans, *head;
ans = s->Clone(root);
head = ans;
while(head){
cout << head->label << " ";
head = head->next;
}
return 0;
}
*/