复杂链表的复制

本文深入探讨了复杂链表的复制算法,包括节点的复制、随机指针的设置及链表的分离过程。通过具体代码实现,展示了如何在保持原有链表结构的同时,创建一个完全独立且结构相同的链表副本。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


复杂链表的复制


程序代码如下:


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;

}

程序运行结果如下:


在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值