c语言链表的复制,c 语言 复杂链表的复制

//头文件

#pragma once

typedef int DataType;

typedef struct ComplexNode

{

DataType _data;// 数据

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

struct ComplexNode* _random;// 指向随机节点

}ComplexNode,*pComplexNode;

void BuyNode(pComplexNode& pNode,DataType x);

void PushBack(pComplexNode& pHead,DataType x);

void CopyCplexList(pComplexNode pHead,pComplexNode& NewpHead);

pComplexNode Find(pComplexNode pHead, DataType Data);

void PrintLinkList(pComplexNode pHead);

//函数文件

#include

#include"ComplexList.h"

#include

#include

//创建节点

void BuyNode(pComplexNode& pNode, DataType x)

{

pNode = (pComplexNode)malloc(sizeof(ComplexNode));

pNode->_data = x;

pNode->_next = NULL;

pNode->_random = NULL;

}

//头插

void PushBack(pComplexNode& pHead,DataType x)

{

pComplexNode tmp = pHead;

if (pHead == NULL)

{

BuyNode(pHead, x);

return;

}

while (tmp->_next != NULL)

{

tmp = tmp->_next;

}

BuyNode(tmp->_next, x);

}

//复杂链表复制

void CopyCplexList(pComplexNode pHead, pComplexNode& NewpHead)

{

pComplexNode tmp = pHead;

pComplexNode head = pHead;

if (pHead == NULL)

return;

while (head != NULL)

{

tmp = head->_next;

BuyNode(NewpHead, head->_data);

head->_next = NewpHead;

NewpHead->_next = tmp;

head = tmp;

}

head = pHead;

while (head != NULL)

{

tmp = head->_next;

if (head->_random == NULL)

tmp->_random == NULL;

else

tmp->_random = head->_random->_next;

head = head->_next->_next;

}

head = pHead;

NewpHead = head->_next;

while (head!=NULL)

{

tmp = head->_next;

head->_next = tmp->_next;

head = tmp->_next;

if (head == NULL)

return;

tmp->_next = head->_next;

}

}

//查找

pComplexNode Find(pComplexNode pHead, DataType Data)

{

pComplexNode tmp = pHead;

assert(pHead);

while (tmp)

{

if (tmp->_data == Data)

return tmp;

tmp = tmp->_next;

}

return NULL;

}

//输出

void PrintLinkList(pComplexNode pHead)

{

pComplexNode tmp = pHead;

if (pHead == NULL)

{

printf("链表为空!\n");

}

while (tmp)

{

printf("%d ", tmp->_data);

tmp = tmp->_next;

}

printf("\n");

}

//测试用例 主函数

#include

#include"ComplexList.h"

void test1()

{

pComplexNode pHead=NULL,NewpHead=NULL;

PushBack(pHead, 1);

PushBack(pHead, 2);

PushBack(pHead, 3);

PushBack(pHead, 4);

PrintLinkList( pHead);

Find(pHead, 1)->_random = Find(pHead, 3);

Find(pHead, 2)->_random = Find(pHead, 4);

Find(pHead, 3)->_random = Find(pHead, 2);

Find(pHead, 4)->_random = Find(pHead, 1);

CopyCplexList(pHead, NewpHead);

PrintLinkList(NewpHead);

}

int main()

{

test1();

return 0;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值