//复杂链表复制的头文件mlist.h:
#ifndef __MLIST_H__
#define __MLIST_H__
#include <stdio.h>
#include <stdlib.h>
#include<assert.h>
typedef int Datatype;
typedef struct node
{
Datatype data;
struct node* random;
struct node* next;
}Node,*pNode,*pList;
pNode CreaList(Datatype d);//创建
void PushBack(pList p_list, Datatype data);//尾插
void PrintList(pList p_list);//打印链表
pNode CopyRandomList(pList p_list);//复制链表
//pList BuyNode(INT d);
#endif //__MLIST_H__
//复杂链表复制的源文件mlist.c
#include"mList.h"
pNode p_list = NULL;
pNode CreaList(Datatype d)//创建
{
pNode p_list = (pNode)malloc(sizeof(Node));
if (p_list == NULL)
{
return NULL;
}
p_list->data = d;
p_list->next = NULL;
p_list->random = NULL;
return p_list;
}
void PushBack(pList p_list, Datatype d)//尾插
{
pNode p1 = p_list;
pNode p2 = NULL;
p2 = (pNode)malloc(sizeof(Node));
if (p2 == NULL)
{
return;
}
while (p1->next != NULL)
{
p1 = p1->next;
}
p2->data = d;
p1->next = p2;
p2->next = NULL;
p2->random =p1;//设置p2节点random->为上一个p1节点
}
void PrintList(pList p_list)
{
assert(p_list);
while (p_list->next!= NULL)
{
printf("%d->", p_list->data);
p_list = p_list->next;
}
printf("%d->NULL\n", p_list->data);
}
pNode CopyRandomList(pList p_list)//复杂链表复制
{
//构造复杂链表
pNode p = p_list;
pNode p2 = NULL;
while (p_list != NULL)
{
pNode q = p_list->next;
pNode p1 = p_list;
p2 = (pNode)malloc(sizeof(Node));
if (p2 == NULL)
return;
p2->data = p_list->data;
p_list = p_list->next;
p1->next = p2;
p2->next = q;
}
//random指向复制
pNode q3 = p;
while (p->next->next != NULL)
{
pNode q2 = p;
pNode q1 = p;
if (q1->random == NULL)
{
p->next->random = NULL;
p = q2->next->next;
}
else {
p->next->random = q1->random->next;
p = q2->next->next;
}
}
pNode ptr = q3;
pNode w1 = q3;
pNode w2 = q3->next;
pNode ptr1 = w1;
pNode ptr2 = w2;
while (ptr->next->next!=NULL)
{
ptr = ptr->next->next;
/*pNode ptr1 = w1;
pNode ptr2 = w2;*/
pNode w3 = w2->next;
w1->next = w3;
w2->next = w3->next;
w1 = w1->next;
w2 = w2->next;
/*w1->next->next = NULL;
w2->next->next = NULL;*/
if (ptr->next->next==NULL)
{
w3->next = NULL;
break;
}
}
return ptr2;
}
//复杂链表复制的test.c
#include"mList.h"
void test()
{
pNode p = CreaList(5);
PushBack(p, 4);
PushBack(p, 3);
PushBack(p, 2);
PushBack(p, 1);
PushBack(p, 0);
PushBack(p, 9);
PrintList(p);
pNode q=CopyRandomList(p);
PrintList(q);
}
int main()
{
test();
system("pause");
return 0;
}