复杂链表的复制

复杂链表的复制

复杂链表不仅包括数据域和指针域,还包括一个random域,并且该域可以为空。

复杂链表的拷贝主要分为三步:
(1)拷贝原始链表的每一个节点,插入到当前节点的后面。

(2)调整random指针

(3)分离两个链表



代码实现:
#include 
    
    
     
     
#include 
     
     
      
      
typedef int DataType;
typedef struct ComplexNode
{
	DataType _data;
	struct ComplexNode* _next;
	struct ComplexNode* _random;
}ComplexNode, *pComplexNode, *pComplexList;

pComplexNode CreateComplexNode(DataType x)
{
	pComplexNode tmp = (pComplexNode)malloc(sizeof(ComplexNode));
	if (tmp == NULL)
	{
		perror("malloc");
		return NULL;
	}
	tmp->_data = x;
	tmp->_next = NULL;
	tmp->_random = NULL;
	return tmp;
}

void Printf(pComplexList s1)
{
	pComplexNode cur = s1;
	while (cur)
	{
		printf("[%d]->random->", cur->_data);
		if (cur->_random)
		{
			printf("[%d]-->", cur->_random->_data);
		}
		else
		{
			printf("NULL-->");
		}
		cur = cur->_next;
	}
}

pComplexList CloneComplex(pComplexList plist)
{
	//拷贝原始链表的每一个节点,插入到当前节点的后面
	pComplexNode cur = plist;
	pComplexNode s1 = NULL;
	pComplexNode s2 = NULL;
	pComplexNode tail = NULL;  

	while (cur)
	{
		pComplexNode tmp = CreateComplexNode(cur->_data);
		tmp->_next = cur->_next;
		cur->_next = tmp;
		cur = cur->_next->_next;
	}

	//调整random指针
	
	cur = plist;
	while (cur)
	{
		cur->_next->_random = cur->_random->_next;
		cur = cur->_next->_next;
	}
	
	//分离两个链表
	s1 = plist;
	if (s1)
	{
		s2 = s1->_next;
		tail = s2;
	}
	while (tail->_next)
	{
		s1->_next = tail->_next;
		s1 = s1->_next;
		tail->_next = s1->_next;
		tail = tail->_next;
	}
	s1->_next = NULL;
	return s2;

}
void Test()
{
	pComplexList l1;
	pComplexNode cur1 = CreateComplexNode(1);
	pComplexNode cur2 = CreateComplexNode(2);
	pComplexNode cur3 = CreateComplexNode(3);
	pComplexNode cur4 = CreateComplexNode(4);
	cur1->_next = cur2;
	cur2->_next = cur3;
	cur3->_next = cur4;

	cur1->_random = cur4;
	cur2->_random = cur1;
	cur3->_random = cur2;
	cur4->_random = cur3;

	l1 = CloneComplex(cur1);
	Printf(cur1);
	printf("\n");
	Printf(l1);
}
     
     
    
    



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值