专题一:线性结构的两种常见应用之一 队列

队列

一、定义

一种可以实现“先进先出”的存储结构(只在一端进行操作)

二、分类

1.链式队列 --链表实现
2.静态队列 --数组实现

三、应用

所有和时间有关的操作都有队列的影子

四、程序

/**
**实现功能:基于数组的循环队列实现
**作者:坚强的大猪猪
**最后修改日期:2019.03.03
**/

//头文件
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>

#define LEN 5	//宏定义,队列长度(数组中预留一位不赋值,方便操作,例LEN=5时,队列实际可用长度为4)

//结构体
typedef struct Queue	
{
	int * pBase;		//指向数组指针
	int front;			//队头
	int rear;			//队尾

}QUEUE, *PQUEUE;

//函数声明
void initQueue(PQUEUE);			//初始化队列
bool isFull(PQUEUE);			//判断队列是否满
bool isEmpty(PQUEUE);			//判断队列是否空
bool inQueue(PQUEUE, int);		//入队
bool outQueue(PQUEUE);			//出队
void displayQueue(PQUEUE);		//显示队列

//主函数
int main()
{
	QUEUE Queue;			//创建一个队列
	initQueue(&Queue);		//初始化
	inQueue(&Queue, 1);		//将1入队
	outQueue(&Queue);		//出队
	inQueue(&Queue, 1);		//将1入队
	displayQueue(&Queue);	//显示队列

	return 0;
}

//初始化队列
void initQueue(PQUEUE pQueue)
{
	pQueue->pBase = (int *)malloc(sizeof(int) * LEN);		//给数组分配内存
	pQueue->front = 0;			//对头、对尾都指向数组的第一个空间(例a[0])
	pQueue->rear = 0;
}

//判断队列是否已满,当对尾加一取余等于对头的时候说明队列已满
bool isFull(PQUEUE pQueue)
{
	//三目运算符,满则返回true,否则返回flase
	return (pQueue->rear + 1) % LEN == pQueue->front ? true : false;		
}

//判断队列是否为空,当队列对头等于对尾时说明队列为空
bool isEmpty(PQUEUE pQueue)
{
	//三目运算符,空则返回true,否则返回flase
	return pQueue->rear == pQueue->front ? true : false;
}

//入队
bool inQueue(PQUEUE pQueue, int val)
{
	if (isFull(pQueue))							//判断队列是否已满
	{
		printf("队列已满,无法入队!\n");
		return false;
	}

	pQueue->pBase[pQueue->rear] = val;			//当队列没满时,入队的元素存放在队尾的位置
	pQueue->rear = (pQueue->rear + 1) % LEN;	//队尾向后移一位

	return true;
}

//出队
bool outQueue(PQUEUE pQueue)
{
	if (isEmpty(pQueue))						//判断队列是否为空
	{
		printf("队列为空,无法出队!\n");
		return false;
	}
	
	pQueue->front = (pQueue->front + 1) % LEN;	//因为不需要释放空间,所以直接将对头向后移一位

	return true;
}

//遍历队列
void displayQueue(PQUEUE pQueue)
{
	int p = pQueue->front;					//定义一个当前队列要输出的数组的下标

	while (p != pQueue->rear)
	{
		printf("%d  ", pQueue->pBase[p]);	//输出
		p = (p + 1) % LEN;					//更新下标,使其指向下一个
	}

	printf("\n");

	return;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值