复杂链表复制

//复杂链表复制的头文件mlist.h:

#ifndef __MLIST_H__
#define __MLIST_H__
#include <stdio.h>
#include <stdlib.h>
#include<assert.h>

typedef int Datatype;
typedef struct node
{
	Datatype data;
	struct node* random;
	struct node* next;
}Node,*pNode,*pList;

pNode CreaList(Datatype d);//创建
void PushBack(pList p_list, Datatype data);//尾插
void PrintList(pList p_list);//打印链表

pNode CopyRandomList(pList p_list);//复制链表

//pList BuyNode(INT d);


#endif //__MLIST_H__

//复杂链表复制的源文件mlist.c
#include"mList.h"


pNode p_list = NULL;
pNode CreaList(Datatype d)//创建
{
	pNode p_list = (pNode)malloc(sizeof(Node));
	if (p_list == NULL)
	{
		return NULL;
	}
	p_list->data = d;
	p_list->next = NULL;
	p_list->random = NULL;
	return p_list;
	
}

void PushBack(pList p_list, Datatype d)//尾插
{
	pNode p1 = p_list;
	pNode p2 = NULL;
	p2 = (pNode)malloc(sizeof(Node));
	if (p2 == NULL)
	{
		return;
	}
	while (p1->next != NULL)
	{
		p1 = p1->next;
	}
	p2->data = d;
	p1->next = p2;
	p2->next = NULL;
	p2->random =p1;//设置p2节点random->为上一个p1节点
}


void PrintList(pList p_list)
{
	assert(p_list);
	while (p_list->next!= NULL)
	{
		printf("%d->", p_list->data);
		p_list = p_list->next;

	}

	printf("%d->NULL\n", p_list->data);
}
pNode CopyRandomList(pList p_list)//复杂链表复制
{
	//构造复杂链表
	pNode p = p_list;
	pNode p2 = NULL;
	while (p_list != NULL)
	{
		pNode q = p_list->next;
		pNode p1 = p_list;
		p2 = (pNode)malloc(sizeof(Node));
		if (p2 == NULL)
			return;
		p2->data = p_list->data;
		p_list = p_list->next;
		p1->next = p2;
		p2->next = q;

	}

	//random指向复制
	pNode q3 = p;
	while (p->next->next != NULL)
	{
		pNode q2 = p;
		pNode q1 = p;
	
		if (q1->random == NULL)
		{
			p->next->random = NULL;
			p = q2->next->next;

		}
		else {
			p->next->random = q1->random->next;
			p = q2->next->next;
		}
		
	}
	pNode ptr = q3;
	pNode w1 = q3;
	pNode w2 = q3->next;
	pNode ptr1 = w1;
	pNode ptr2 = w2;
	while (ptr->next->next!=NULL)
	{

	    ptr = ptr->next->next;
		/*pNode ptr1 = w1;
		pNode ptr2 = w2;*/
		pNode w3 = w2->next;
		w1->next = w3;
		w2->next = w3->next;
		w1 = w1->next;
		w2 = w2->next;
		/*w1->next->next = NULL;
		w2->next->next = NULL;*/
		if (ptr->next->next==NULL)
		{
			w3->next = NULL;
			break;
		}
	}
	
	return ptr2;
}

//复杂链表复制的test.c
#include"mList.h"


void test()
{
	pNode p = CreaList(5);
	PushBack(p, 4);
	PushBack(p, 3);
	PushBack(p, 2);
	PushBack(p, 1);
	PushBack(p, 0);
	PushBack(p, 9);
	PrintList(p);
	pNode q=CopyRandomList(p);
	PrintList(q);
}

int main()
{
	test();
	system("pause");
	return 0;
}





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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

멋진

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值