队列的封装


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

#define N 100			//宏定义队列的大小
#define datatype char	//定义队列数据类型

struct queue
{
	datatype data[N];
	int front;  //队列开头
	int rear;	//队列结尾
};

typedef struct queue Q;

void init(Q *MyQueue);				//初始化队列
int isEmpty(Q *MyQueue);			//判断是否队列为空
void enQueue(Q *MyQueue, datatype num); //入队
datatype deQueue(Q *MyQueue);			//出队
void printQueue(Q *MyQueue);			//打印队列成员
datatype getHead(Q *MyQueue);			//取得队首元素


//queue.c 文件

#include "queue.h"
//队列先入先出
void init(Q *MyQueue)//初始化结构体
{
	//一开始队列为空,那么front=rear = 0
	MyQueue->front = MyQueue->rear = 0;
}

int isEmpty(Q *MyQueue)
{
	if (MyQueue->front == MyQueue->rear)
	{
		return 1;  //返回真 说明时空的
	}
	else
	{
		return 0;
	}
}

void enQueue(Q *MyQueue, datatype num)
{
	if (N == MyQueue->rear)
	{
		printf("入队列失败\n");
		return; //入队列失败
	}
	else
	{
		MyQueue->data[MyQueue->rear] = num; //先赋值在增加
		MyQueue->rear += 1;
	}
}
datatype deQueue(Q *MyQueue)//出队
{
	if (MyQueue->front == MyQueue->rear)
	{
		//队列空
		printf("出队列失败!\n");
		return -1;
	}
	else
	{
		MyQueue->front += 1;
		//返回出队列的元素
		return MyQueue->data[MyQueue->front - 1];
	}

}
void printQueue(Q *MyQueue)//打印队列成员
{
	printf("\n");
	if (MyQueue->front == MyQueue->rear)
	{
		printf("队列为空!\n");
	}
	else
	{
		for (int i = MyQueue->front; i < MyQueue->rear; i++)
		{
			printf("%c ", MyQueue->data[i]);
		}
	}
}

datatype getHead(Q *MyQueue)
{
	if (MyQueue->front == MyQueue->rear)
	{
		printf("队列为空!无法找到首出队的数\n");
		return -1;
	}
	else
	{
		return MyQueue->data[MyQueue->front];
	}
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值