数据结构day5:双向循环链表 代码作业

一、dLoopLink.h

#ifndef __DLOOPLINK_H__
#define __DLOOPLINK_H__

#include <stdio.h>
#include <stdlib.h>

typedef int DataType;

typedef struct node
{
	union
	{
		int len;
		DataType data;
	};
	struct node* next;
	struct node* prior;
}dLoopLink, *dLoopLinkPtr;

//创建
dLoopLinkPtr create();

//判空
int empty(dLoopLinkPtr H);

//尾插
int tail_add(dLoopLinkPtr H, DataType e);

//遍历
void show(dLoopLinkPtr H);

//尾删
int tail_del(dLoopLinkPtr H);

//销毁
void my_free(dLoopLinkPtr H);

#endif


二、dLoopLink.c

#include "dLoopLink.h"

//创建
dLoopLinkPtr create()
{
	dLoopLinkPtr H = (dLoopLinkPtr)malloc(sizeof(dLoopLink));
	if(NULL == H)
	{
		printf("创建失败!\n");
		return NULL;
	}
	H->len = 0;
	H->next = NULL;
	H->prior = NULL;
	printf("创建成功!\n");
	return H;
}

//判空
int empty(dLoopLinkPtr H)
{
	if(NULL == H)
	{
		printf("判空失败!\n");
		return -1;
	}
	return H->len==0;
}

//尾插
int tail_add(dLoopLinkPtr H, DataType e)
{
	if(NULL == H || empty(H))
	{
		printf("插入失败!\n");
		return 0;
	}
	
	dLoopLinkPtr p = (dLoopLinkPtr)malloc(sizeof(dLoopLink));
	if(NULL == p)
	{
		printf("申请节点失败!\n");
		return 0;
	}
	p->data = e;
	p->next = NULL;
	p->prior = NULL;

	dLoopLinkPtr q = H;
	for(int i=0; i<H->len; i++)
	{
		q = q->next;
	}
	p->next = H->next;
	p->prior = q;
	H->prior = p;
	q->next = p;

	H->len++;
	return 1;
}

//遍历
void show(dLoopLinkPtr H)
{
	if(NULL == H || empty(H))
	{
		printf("遍历失败!\n");
		return ;
	}
	
	dLoopLinkPtr p = H;
	while(H->next != H)
	{
		p = p->next;
		printf("%d ", p->data);
	}
	printf("\n");
}

//尾删
int tail_del(dLoopLinkPtr H)
{
	if(NULL == H || empty(H))
	{
		printf("删除失败!\n");
		return 0;
	}
	dLoopLinkPtr p = H;
	while(p->next != H)
	{
		p = p->next;
	}
	p->prior->next = H;
	H->prior = p->next->prior;
	
	free(p);
	p=NULL;
	return 1;
}

//销毁
void my_free(dLoopLinkPtr H)
{
	if(NULL == H)
	{
		return ;
	}
	while(H->next != H)
	{
		tail_del(H);
	}
	free(H);
	H=NULL;
	printf("销毁成功!\n");
}


三、main.c

#include "dLoopLink.h"

int main()
{
	dLoopLinkPtr H = create();
	//尾插
	tail_add(H, 10);
	tail_add(H, 20);
	tail_add(H, 30);
	tail_add(H, 40);
	tail_add(H, 50);
	//遍历
	show(H);
	//尾删
	tail_del(H);
	show(H);
	//销毁
	my_free(H);
	H=NULL;

	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值