复杂链表的复制,有一个next指针指向下一个结点,还有一个random指针指向这个链表中的一个随机结点或者NULL,先要求复制这个链表,返回复制后的新链表。

定义一个简单的复杂链表。
在这里插入图片描述
注意
1.复杂链表的复制先处理复杂链表为空,这之间返回。
2.当复杂链表不为空,复制链表需要在原链表每个节点连接处插入新结点。
3.新结点随机指针域,(随机指针域为原结点随机指针域的下一个节点。
4.将新链表从原链表上拆下。


#include <stdlib.h>
#include <assert.h>

typedef struct CLNode {
	int data;
	struct CLNode *random;
	struct CLNode *next;
}	CLNode;

static CLNode * ComplexCreateNode(int data)
{
	CLNode *node = (CLNode *)malloc(sizeof(CLNode));
	node->data = data;
	node->random = NULL;
	node->next = NULL;

	return node;
}

CLNode * Copy(CLNode *list)
{
	CLNode *cur = list;
	// 1. 复制结点
	while (cur != NULL) {
		CLNode *newNode = ComplexCreateNode(cur->data);
		newNode->next = cur->next;
		cur->next = newNode;

		// 不能直接去 next
		cur = cur->next->next;
	}

	// 2. 复制 random
	cur = list;
	while (cur != NULL) {
		if (cur->random != NULL) {
			cur->next->random = cur->random->next;
		}

		cur = cur->next->next;
	}

	// 3. 拆分
	cur = list;
	CLNode *newList = cur->next;	//  保存新链表
	while (cur != NULL) {
		CLNode *node = cur->next;

		cur->next = node->next;
		if (cur->next != NULL) {
			node->next = cur->next->next;
		}
		else {
			node->next = NULL;
		}

		// 注意
		cur = cur->next;
	}

	return newList;
}

void PrintComplexList(CLNode *list)
{
	for (CLNode *cur = list; cur != NULL; cur = cur->next) {
		printf("[%d, random(%p)->%d] ", cur->data,
			cur->random,
			cur->random ? cur->random->data : 0);
	}
	printf("\n");
}

void TestComplex()
{
	CLNode *n1 = ComplexCreateNode(1);
	CLNode *n2 = ComplexCreateNode(2);
	CLNode *n3 = ComplexCreateNode(3);
	CLNode *n4 = ComplexCreateNode(4);

	n1->next = n2;
	n2->next = n3;
	n3->next = n4;

	n1->random = n3;
	n2->random = n1;
	n3->random = n3;

	CLNode *newList = Copy(n1);
	PrintComplexList(n1);
	PrintComplexList(newList);
}
int main()
{
	TestComplex();

	return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值