顺序队列(c示例)

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

#define MAXSIZE 10            //数组队列的最大大小

//先入先出

typedef struct Queue
{
	int data[MAXSIZE];        //队列的总大小
	int front;                //记录队列首元素的下边标量
	int rear;                 //记录队尾元素的小标变量
}queue_q, *Queue_q;

//初始化队列
Queue_q Init_queue(void)
{
	Queue_q sq = malloc(sizeof(queue_q));    //申请结构体大小的内存空间,sq指向这片内存空间

	if(sq != NULL)
	{
		sq->front = MAXSIZE - 1;
		sq->rear = MAXSIZE -1;

		return sq;
	}

	return 0;
}

//是否为空
bool Is_Empty(Queue_q sq)
{
	//为空返回true 否则返回false
	return sq->rear == sq->front;       
}

//是否已满
bool Is_Full(Queue_q sq)
{
	//当(sq->reat + 1) % SIZE和sq->front相等时,返回true(满) 否则返回false(不满)
	return (sq->rear + 1) % MAXSIZE == sq->front;
}

//入队
bool Push_queue(Queue_q sq, int n)
{
	if(Is_Full(sq))
	{
		printf("队列已满!\n");
		return false;
	}

	sq->rear = (sq->rear + 1) % MAXSIZE;  //先让队尾下标进行偏移
	sq->data[sq->rear] = n;           //赋值
	return true;

}

//出队
bool Out_queue(Queue_q sq, int *t)
{
	if(Is_Empty(sq))
	{
		printf("队列空!\n");
		return false;
	}

	sq->front = (sq->front + 1) % MAXSIZE;
	*t = sq->data[sq->front];
	return true;

}

//打印队列
bool Show_queue(Queue_q sq)
{
	if(Is_Empty(sq))
	{
		printf("队列空!\n");
		return false;
	}

	for(int i = (sq->front + 1 ) % MAXSIZE; i <= sq->rear; i = (i+1) % MAXSIZE)
	{
		printf("%d ", sq->data[i]);
	}
	printf("\n");
}

int main()
{
	Queue_q sq = Init_queue();

	for(int i = 0; i < 5; i++)
	{
		Push_queue(sq, i);
	}

	Show_queue(sq);

	int temp;

	Out_queue(sq, &temp);

	printf("out:%d\n", temp);

	Show_queue(sq);
}

结果:
在这里插入图片描述

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

trust Tomorrow

感谢支持!

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

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

打赏作者

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

抵扣说明:

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

余额充值