题目描述
输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的head。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)

代码:
/*
struct RandomListNode {
int label;
struct RandomListNode *next, *random;
RandomListNode(int x) :
label(x), next(NULL), random(NULL) {
}
};\
while (p!=NULL){
nex=p->next;
curr->label=p->label;
p->next=curr;
curr->next=nex;
p=nex;
}
a=new RandomListNode(2);
p=pHead;
while (p!=NULL){
nex=p->next;
nex->random=p->random->next;
p=nex->next;
}
a=pHead->next;
p=pHead->next;
while(a!=NULL){
RandomListNode *cloneNode = a->next;
a->next=cloneNode->next;
cloneNode->next=cloneNode->next==NULL?NULL:cloneNode->next->next;
a=a->next;
a=a->next;
}
*/
class Solution {
public:
RandomListNode* Clone(RandomListNode* pHead)
{
if(pHead==NULL)
return NULL;
RandomListNode* p,* curr,;
p=pHead;
while (p!=NULL){
curr=new RandomListNode(p->label);
curr->next=p->next;
p->next=curr;
p=curr->next;
}
p=pHead;
while (p!=NULL){
curr=p->next;
curr->random=(p->random!=NULL?p->random->next:NULL);
p=curr->next;
}
RandomListNode *head = pHead->next;
RandomListNode *cur = head;
RandomListNode *pCur = pHead;
//拆分链表
while(pCur!=NULL){
pCur->next = pCur->next->next;
if(cur->next!=NULL)
cur->next = cur->next->next;
cur = cur->next;
pCur = pCur->next;
}
return head;
}
};
本文介绍了一种复杂链表的复制算法,该链表包含节点值、指向下一个节点的指针和特殊指针。通过插入克隆节点并调整指针,实现了链表的深度克隆。
1313

被折叠的 条评论
为什么被折叠?



