【数据结构】复杂链表的复制

单链表的实现:https://blog.csdn.net/weixin_41892460/article/details/82855823

1.什么是复杂链表

一个链表的每个节点,有一个指向next指针指向下一个节点, 还有一个random指针指向这个链表中的一个随机节点或者NULL。

typedef struct ComplexNode
{
	DataType _data;
	struct ComplexNode* _next;
	struct ComplexNode* _random;
}ComplexNode;

2.复杂链表的复制

思路

1)在每一个结点的后面连节一个和它相同数据的结点。
2)创建新结点的random,它的random 就是前面新结点的random的next。
3)将链表分离。


ComplexNode* CopyList(ComplexNode* plist)
{
	ComplexNode* cur = plist;
	ComplexNode* tmep = NULL;
	ComplexNode* newlist = NULL;
	//创建结点
	while (cur != NULL)
	{
		ComplexNode* tmp = cur->_next;
		ComplexNode* newnode = BuyComplexNode(cur->_data);
		assert(newnode);
		newnode->_next = tmp;
		cur->_next = newnode;
		cur = tmp;
	}
	//②复制random域
	cur = plist;
	while (cur != NULL)
	{
		tmep = cur->_next;
		if (cur->_random != NULL)
			tmep->_random = cur->_random->_next;
		cur = tmep->_next;
	}
	//③拆除链表
	cur = plist;
	tmep = cur->_next;
	newlist = tmep;
	while (cur != NULL)
	{
		cur->_next = tmep->_next;
		if (cur->_next != NULL)
			tmep->_next = cur->_next->_next;
		cur = cur->_next;
		tmep = tmep->_next;
	}
	return newlist;
}


void PrintComplexList(ComplexNode* plist)
{
	ComplexNode* cur = plist;
	while (cur)
	{
		printf("%d:", cur->_data);
		if (cur->_random != NULL)
		{
			printf("(%d)-->", cur->_random->_data);
		}
		else
		{
			printf("(NULL)-->");
		}
		cur = cur->_next;
	}
	printf("over\n");
}





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值