《数据结构——队列》

目录

一、队列

1.1 队列理论知识

二、代码实现

实现功能↓

队列结构体类型

queue.h

queue.c

main.c


一、队列

1.1 队列理论知识

1> 队列也是操作受限的线性表,只允许在一端进行插入、另一端进行删除 ​

2> 能插入的一端称为队尾、能删除的一端称为队头 ​

3> 特点:先进先出(FIFO) ​

4> 顺序存储的栈叫顺序队列、链式存储的栈叫链队列

二、代码实现

实现功能↓

//创建
seQueue *create();
//判空
int empty(seQueue *S);
//判满
int full(seQueue *S);
//入队
int push(seQueue *S,datatype e);
//遍历
void show(seQueue *S);
//出队
int pop(seQueue *S);
//销毁
void destroy(seQueue *S);
//返回长度
int len(seQueue *S);

队列结构体类型

typedef int datatype;

typedef struct
{
	datatype data[MAX];  //存放数据队列
	int front;        //记录队头位置
	int tail;        //记录队尾位置
}seQueue;

queue.h

#ifndef __QUEUE_H__
#define __QUEUE_H__

#define MAX 8
typedef int datatype;

typedef struct
{
	datatype data[MAX];  //存放数据队列
	int front;        //记录队头位置
	int tail;        //记录队尾位置
}seQueue;
//创建
seQueue *create();
//判空
int empty(seQueue *S);
//判满
int full(seQueue *S);
//入队
int push(seQueue *S,datatype e);
//遍历
void show(seQueue *S);
//出队
int pop(seQueue *S);
//销毁
void destroy(seQueue *S);
//返回长度
int len(seQueue *S);
#endif

queue.c

#include<stdlib.h>
#include"queue.h"
#include<stdio.h>
//创建
seQueue *create()
{
	seQueue *S=(seQueue*)malloc(sizeof(seQueue));
	if (NULL==S)
	{
		printf("创建失败\n");
	}
	//初始化
	S->front=S->tail=0;
	printf("创建成功\n");
	return S;
}
//判空
int empty(seQueue *S)
{
	return S->front==S->tail?1:0; //1空 0非空
}
//判满
int full(seQueue *S)
{
	return (S->tail+1)%MAX==S->front?1:0; //1满 0未满
}
//入队
int push(seQueue *S,datatype e)
{
	//判断逻辑
	if (NULL==S || full(S))
	{
		printf("入队失败\n");
		return -1;
	}
	//入队元素
	S->data[S->tail]=e;
	//队尾后移
	S->tail=(S->tail+1)%MAX;
	printf("入队成功\n");
	return 0;
}
//遍历
void show(seQueue *S)
{
	//判断逻辑
	if (NULL==S || empty(S))
	{
		printf("遍历失败\n");
		return ;
	}
	//遍历
	printf("从队头到队尾的元素分别是:");
	for(int i=S->front;i!=S->tail;i=(i+1)%MAX)
	{
		printf("%d\t",S->data[i]);
	}printf("\n");
}
//出队
int pop(seQueue *S)
{
	//判断逻辑
	if (NULL==S||empty(S))
	{
		printf("出队失败\n");
		return -1;
	}
	//出队
	printf("出队成功\t%d\n",S->data[S->front]);
	S->front=(S->front+1)%MAX;
	return 0;
}
//销毁
void destroy(seQueue *S)
{
	if (NULL!=S)
	{
		free(S);
		S=NULL;
	}
	printf("销毁成功\n");
}
//返回长度
int len(seQueue *S)
{
	return (MAX+S->tail-S->front)%MAX;
}

main.c

#include<stdlib.h>
#include"queue.h"
#include<stdio.h>
int main(int argc, const char *argv[])
{
	seQueue *S=create();
	if (NULL==S)
	{
		return -1;
	}
	//调用入队函数
	push(S,1);
	push(S,2);
	push(S,3);
	push(S,4);
	push(S,5);
	push(S,6);
	push(S,7);
	printf("队列长度为:%d\n",len(S));
	show(S);
	//调用出队函数
	pop(S);
	show(S);
	//调用销毁函数
	destroy(S);
	S=NULL;
	
	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值