复制一个复杂链表。在复杂链表中,每个节点有next 指针指向下一个结点外,还有pSibling指向链表任何结点或者NULL。
根据作者思路实现这个需求,代码没有作者简洁。
#include <iostream>
using namespace std;
struct complexLinklist{
char val;
complexLinklist *next;
complexLinklist *pSibling;
};
void copyListNode(complexLinklist *head)
{
complexLinklist *p=head,*pre=NULL;
char val;
while (p!=NULL)
{
pre=p;
val=p->val;
p=p->next;
complexLinklist *newNode=new complexLinklist;
if (newNode==NULL)
{
cout<<"memory errors \n";
}
newNode->val=val;
newNode->pSibling=NULL;
pre->next=newNode;
if (p==NULL)
{
newNode->next=NULL;
}
else{
newNode->next=p;
}
}
}
void connectPSibling(complexLinklist *head)
{
complexLinklist *pNode=head;
while (pNode!=NULL)
{
complexLinklist *clone=pNode->next;
if (pNode->pSibling!=NULL)
{
clone->pSibling=pNode->pSibling->next;
}
pNode=clone->next;
}
}
complexLinklist * reconnectLinklist(complexLinklist *head)
{
complexLinklist *pNode=head;
complexLinklist *pCloneHead=NULL,*pCloneNode=NULL;
/*
算法思想来自于剑指offer,但是代码没有写的像作者简介明了。
*/
if (pNode!=NULL)
{
pCloneHead=pCloneNode=pNode->next;
}
while (pNode!=NULL)
{
pNode->next=pCloneNode->next;
pNode=pCloneNode->next;
if (pNode==NULL)
{
pCloneNode->next=NULL;
}
else{
pCloneNode->next=pNode->next;
pCloneNode=pNode->next;
}
}
return pCloneHead;
}
complexLinklist *Clone(complexLinklist *head)
{
copyListNode(head);
connectPSibling(head);
return reconnectLinklist(head);
}
void PrintLinklist(complexLinklist *head)
{
cout<<"打印链表元素\n";
while (head!=NULL)
{
cout<<head->val<<endl;
if (head->pSibling!=NULL)
{
cout<<head->val<<"的psbling元素"<<head->pSibling->val<<endl;
}
head=head->next;
}
}
int main()
{
complexLinklist *head,*one,*two,*three;
head=new complexLinklist;
one=new complexLinklist;
two=new complexLinklist;
three=new complexLinklist;
head->pSibling=one->pSibling=two->pSibling=three->pSibling=NULL;
head->val='A';
one->val='B';
two->val='C';
three->val='D';
head->next=one;
one->next=two;
two->next=three;
three->next=NULL;
head->pSibling=two;
three->pSibling=one;
complexLinklist *testPoint;
testPoint=Clone(head);
PrintLinklist(testPoint);
return 0;
}