typedef struct ComplexList
{
DataType _data; //数据
struct ComplexList *_next; //指向下一节点的指针
struct ComplexList *_random;
}ComplexList, *PComplexList;
void InitList(PComplexList& pHead)
{
pHead = NULL;
}
ComplexList *BuyNode(DataType x)
{
ComplexList *newNode;
newNode = (ComplexList*)malloc(sizeof(ComplexList));
newNode->_data = x;
newNode->_next = NULL;
newNode->_random = NULL;
return newNode;
}
// 创建一个复杂单链表
void InsertNode(PComplexList& pHead)
{
ComplexList *tmp = pHead;
ComplexList *cur = pHead;
int index=1;
if(pHead == NULL)
{
pHead = BuyNode(1);
pHead->_random = NULL;
}
tmp = pHead;
for(;index<6;index++)
{
ComplexList *prve = tmp;
tmp->_next = BuyNode(index+1);
tmp = tmp->_next;
tmp->_random = prve;
}
pHead->_random = tmp;
}
void PrintList(ComplexList* pHead)
{
while(pHead != NULL)
{
printf("%d->",pHead->_data);
pHead=pHead->_next;
}
printf("NULL\n");
}
//复制
ComplexList *CopyList(PComplexList& pHead)
{
ComplexList *begin = pHead;
ComplexList *cur ;
ComplexList *prve ;
ComplexList *pa ;
ComplexList *pb;
if(pHead == NULL)
{
return NULL;
}
//将此单链表的每个元素拷贝一份,插入到每个原来单链表节点的后面
while(begin != NULL)
{
ComplexList *tmp =begin;
ComplexList *prve = begin->_next;
ComplexList *newNode =BuyNode(begin->_data);
begin = begin->_next;
newNode->_next =prve;
tmp->_next = newNode;
}
//将每个新插入节点的_random连接起来
cur =pHead;
prve = pHead->_next;
while(cur)
{
prve->_random = cur->_random->_next;
if(prve->_next == NULL)
{
break;
}
prve = prve->_next->_next ;
cur = cur->_next->_next ;
}
//拆分成两个单链表
pa = pHead;
pb = pHead->_next ;
while(pa)
{
if(pb->_next == NULL)
{
pa->_next =NULL;
break;
}
ComplexList *prveA = pa;
ComplexList *curA = pa->_next->_next;
ComplexList *prveB = pb;
ComplexList *curB = pb->_next->_next;
prveA->_next = curA;
prveB->_next = curB;
pa= pa->_next ;
pb = pb->_next;
}
return pb;
}
转载于:https://blog.51cto.com/fengbaoli/1710775