复杂链表的复制
程序代码如下:
Complex.h
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
typedef int DataType;
typedef struct Node
{
DataType data;
struct Node* next;
struct Node* rand;
}Node, *pNode, List, *pList;
// 复杂链表的复制
pNode CopyComplex(pNode pHead);
Complex.c
#include "Linklist Interface.h"
//复杂链表的复制
pNode CopyComplex(pNode pHead)
{
//assert(pHead);
pNode cur1 = pHead;
pNode cur2 = NULL;
pNode CopyNode = NULL;
if (NULL == pHead)
return NULL;
// copy node and link to every node 复制节点并连接到每个节点
while (cur1)
{
cur2 = cur1->next;
cur1->next = BuyNode(cur1->data);
cur1->next->next = cur2;
cur1 = cur2;
}
cur1 = pHead;
// set copy node rand 设置复制节点的rand随机指针域
while (cur1)
{
CopyNode = cur1->next;
CopyNode->rand = (cur1->rand != NULL) ? cur1->rand->next : NULL;
cur1 = CopyNode->next;
}
cur1 = pHead;
pNode ret = cur1->next;
// split 分离链表,返回复制成功后的新链表
while (cur1)
{
cur2 = cur1->next->next;
CopyNode = cur1->next;
cur1->next = cur2;
CopyNode->next = (cur2 != NULL) ? cur2->next : NULL;
cur1 = cur2;
}
return ret;
}
void PrintLinkList(pList plist)
{
pNode tmp = plist;
while (tmp)
{
//复杂链表打印
printf("%d::%d -->", tmp->data, tmp->rand->data);
tmp = tmp->next;
}
printf("NULL\n");
}
test.c
#include "Linklist Interface.h"
Test()
{
pList plist, cplist;
pNode newNode1, newNode2, newNode3, newNode4, newNode5;
plist = BuyNode(0);
newNode1 = BuyNode(1);
newNode2 = BuyNode(2);
newNode3 = BuyNode(3);
newNode4 = BuyNode(4);
newNode5 = BuyNode(5);
plist->next = newNode1;
newNode1->next = newNode2;
newNode2->next = newNode3;
newNode3->next = newNode4;
newNode4->next = newNode5;
newNode5->next = NULL;
plist->rand = newNode4;
newNode1->rand = newNode3;
newNode2->rand = plist;
newNode3->rand = newNode5;
newNode4->rand = newNode1;
newNode5->rand = newNode2;
PrintLinkList(plist);
cplist = CopyComplex(plist);
PrintLinkList(cplist);
}
int main()
{
Test();
system("pause");
return 0;
}
程序运行结果如下: