复杂链表的复制


复杂链表的复制过程如下图所示:




#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
typedef  int DataType;

typedef  struct ComplexNode{
	DataType data;
	struct ComplexNode* next;
	struct ComplexNode* random;
}ComplexNode;

ComplexNode* BuyComplexNode(DataType d)
{
	ComplexNode* temp = (ComplexNode*)malloc(sizeof(ComplexNode));
	if (temp == NULL){
		perror("use mallloc");
		exit(EXIT_FAILURE);
	}
	memset(temp, 0, sizeof(ComplexNode));
	temp->data = d;
	temp->next = NULL;
	temp->random = NULL;
	return temp;
}
void PrintComplexList(ComplexNode* p)
{
	while (p != NULL){

		printf("%d->%d ", p->data, p->random->data);
		p = p->next;
	}
	printf("\n");
}
ComplexNode* CopyComplexList(ComplexNode *head)
{
	ComplexNode* cur = head;
	ComplexNode* ptr = NULL;
	ComplexNode* newhead = NULL;
	//复制节点,并串成一条链
	if (cur == NULL)
	{
		return NULL;
	}
	while (cur != NULL)
	{
		ptr = cur;
		ComplexNode* temp = NULL;
		temp = BuyComplexNode(cur->data);
		cur = cur->next;
		ptr->next = temp;
		temp->next = cur;

	}
	//复制随机指针
	cur = head->next;
	ptr = head;
	while (cur->next != NULL)
	{
		cur->random = ptr->random->next;
		ptr = ptr->next->next;
		cur = cur->next->next;
	}
	cur->random = ptr->random->next;
	//将混合链分开

	cur = head->next;
	ptr = head;
	newhead = head->next;
	while (cur->next != NULL)
	{
		ptr->next = cur->next;
		ptr = ptr->next;
		cur->next = ptr->next;
		cur = cur->next;
	}
	ptr->next = NULL;
	return newhead;
}

void test8(){
	ComplexNode* head = NULL;
	ComplexNode* temp = NULL;
	temp = BuyComplexNode(1);
	head = temp;
	temp = BuyComplexNode(2);
	head->next = temp;
	temp = BuyComplexNode(3);
	head->next->next = temp;
	temp = BuyComplexNode(4);
	head->next->next->next = temp;
	head->random = head->next->next;
	head->next->random = head;
	head->next->next->random = head->next;
	head->next->next->next->random = head->next->next;
	PrintComplexList(head);
	CopyComplexList(head);
	PrintComplexList(head);

}
int main(){

	test8();
	system("pause");
	return 0;
}

欢迎各位批评指正!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值