复杂链表的赋值

来源:互联网 发布:软件开发的岗位 编辑:程序博客网 时间:2024/05/29 17:58
#include<iostream>
#include<stdio.h>
using namespace std;


struct ComplexNode{ 


int  _data ; // 数据 


struct ComplexNode * _next; // 指向下一个节点的指针 


struct ComplexNode * _random; // 指向随机节点(可以是链表中的任意节点 or 空) 


};




ComplexNode* CreatComplexNode(int data)
{
ComplexNode*  Node=(ComplexNode*)malloc(sizeof(ComplexNode));
if(Node==NULL)
{
printf("out of memeory\n!!");
return NULL;
}
Node->_data=data;
Node->_next=NULL;
Node->_random=NULL;


return Node;


}


ComplexNode* CreatComplexList()
{
ComplexNode*  n1=CreatComplexNode(1);


ComplexNode*  n2=CreatComplexNode(2);
ComplexNode*  n3=CreatComplexNode(3);
ComplexNode*  n4=CreatComplexNode(4);


n1->_next=n2;
n2->_next=n3;
n3->_next=n4;
n4->_next=NULL;


n1->_random=n3;
n2->_random=NULL;
n3->_random=n2;
n4->_random=n4;


return n1;
}
ComplexNode*  CopyComplexNode(ComplexNode* pHead)
{
ComplexNode* newnode=NULL;
ComplexNode* cur=pHead;
while(cur)//给新节点赋值
{
newnode= CreatComplexNode(cur->_data);
newnode->_next=cur->_next;
cur->_next=newnode;
cur=newnode->_next;
}
//给新节点的random赋值
cur=pHead;
ComplexNode* Nextnode=NULL;
while(cur)
{
Nextnode=cur->_next;
Nextnode->_random=cur->_random;
cur=Nextnode->_next;
}
//拆分
newnode=pHead->_next;
Nextnode=newnode;
cur=Nextnode->_next;
pHead->_next=cur;
while(cur)
{
newnode=cur->_next;
newnode=newnode->_next;
cur->_next=newnode->_next;
cur=cur->_next;

}
return newnode;




}
void print(ComplexNode* pHead)
{
if(pHead==NULL)
return ;
ComplexNode* p=pHead;
while(p)
 {
if(p->_random)
{
printf("%d:random->%d \n",p->_data,p->_random->_data);
}
else
{
printf("%d:random->NULL\n",p->_data);
}
 p= p->_next;
 }  


}
int main()
{
ComplexNode pNode;
ComplexNode* ll=CreatComplexList( );
print(ll);
ComplexNode* l2=CopyComplexNode(ll);
print(l2);
system("pause");
return 0;
}