7.9数据结构(双向循环链表)

1.头文件

#ifndef __loop__
#define __loop__
#include <string.h>
#include <stdio.h>
#include <stdlib.h>

typedef int datatype;

typedef struct node
{
	union
	{
		datatype data;
		int len;
	};
	struct node* next;
	struct node* pri;
}node,*node_p;

//创建双向循环链表
node_p create_loop();
//创建节点
node_p create_node(datatype a);
//判空
int empty(node_p Q);
//尾插
int add_tail(node_p Q,datatype a);
//尾删
int dele_tail(node_p Q);
//输出
int show(node_p Q);
//销毁
void release(node_p *Q);

#endif

2.功能函数

#include "loop.h"
//创建双向循环链表
node_p create_loop()
{
	node_p H=(node_p)malloc(sizeof(node));
	if(H==NULL)
	{
		printf("堆区空间申请失败\n");
		return NULL;
	}
	H->next=H;
	H->pri=H;
	H->len=0;
	printf("双向循环链表创建成功\n");
	return H;
}
//创建节点
node_p create_node(datatype a)
{
	node_p new=(node_p)malloc(sizeof(node));
	if(new==NULL)
	{
		printf("节点空间申请失败\n");
		return NULL;
	}
	new->next=NULL;
	new->pri=NULL;
	new->data=a;
	return new;
}
//判空
int empty(node_p Q)
{
	if(Q==NULL)
	{
		printf("参数传入失败\n");
		return -1;
	}
	if(Q->len==0)
	{
		printf("链表为空\n");
		return 1;
	}
	else
	{
		return 0;
	}
}
//尾插
int add_tail(node_p Q,datatype a)
{
	if(Q==NULL)
	{
		printf("参数传入失败\n");
		return -1;
	}
	node_p H=create_node(a);
	node_p p=Q;
	for(int i=0;i<Q->len;i++)
	{
		p=p->next;
	}
	p->next->pri=H;
	H->next=p->next;
	H->pri=p;
	p->next=H;
	Q->len++;
	return 1;
}
//尾删
int dele_tail(node_p Q)
{
	if(Q==NULL)
	{
		printf("参数传入失败\n");
		return -1;
	}
	if(empty(Q))
	{
		return 0;
	}
	node_p p=Q;
	for(int i=0;i<Q->len;i++)
	{
		p=p->next;
	}
	p->next->pri=p->pri;
	p->pri->next=p->next;
	free(p);
	Q->len--;
	return 1;
}
//输出
int show(node_p Q)
{
	if(Q==NULL)
	{
		printf("参数传入失败\n");
		return -1;
	}
	if(empty(Q))
	{
		return 0;
	}
	node_p p=Q;
	for(int i=0;i<Q->len;i++)
	{
		p=p->next;
		printf("%d\t",p->data);
	}
	putchar(10);
	return 1;
}
//释放
void release(node_p *Q)
{
	if((*Q)==NULL)
	{
		printf("参数传入失败\n");
		return ;
	}
	int k=(*Q)->len;
	node_p p=(*Q);
	for(int i=0;i<k;i++)
	{
		node_p temp=p;
		p=p->next;
		free(temp);
	}
	free(p);
	*Q=NULL;
	printf("链表已释放\n");
	return;
}

3.主函数

#include "loop.h"

int main()
{
	node_p H=create_loop();
	add_tail(H,12);
	add_tail(H,13);
	add_tail(H,14);
	add_tail(H,15);
	show(H);
	dele_tail(H);
	dele_tail(H);
	add_tail(H,21);
    show(H);
	release(&H);
	return 1;
}

实现效果

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值