本篇博客将实现一般队列的数组结构,具体实现的操作有入队、出队、计算队列长度、判断队列是否为空、为满等。详细工程代码如下:
1.头文件Queue_Array.h
#pragma once
#ifndef QUEUE_ARRAY
#define QUEUE_ARRAY
#define NumOfQueue 20
typedef int ElementType;
struct queue
{
int Capacity;
int size;
int front;
int rear;
ElementType* Array;
};
typedef struct queue* Queue;
Queue CreatQueue();//创建空队列;
int IsEmpty(Queue Q);//判断队列是否为空;
int IsFull(Queue Q);//判断队列是否为满;
void MakeEmpty(Queue Q);//置空
int LengthOfQueue(Queue Q);//计算队列长度
void EnQueue(Queue Q, ElementType data);//入队
void DeQueue(Queue Q);//出队
void PrintQueue(Q);//打印队列
#endif // !QUEUE_ARRAY
2.源文件Queue_Array.c
#include<stdio.h>
#include<malloc.h>
#include"Queue_Array.h"
Queue CreatQueue()//创建空队列;
{
Queue Q = malloc(sizeof(struct queue));
if (Q == NULL)
{
printf("out of space!!!");
exit(1);
}
Q->Array = malloc(sizeof(ElementType) * NumOfQueue);
if (!Q->Array)
{
printf("out of space!!!");
exit(1);
}
Q->front = Q->rear = 0;
Q->size = 0;
Q->Capacity = NumOfQueue;
return Q;
}
int IsEmpty(Queue Q)//判断队列是否为空;
{
return Q->front == Q->rear;
}
int IsFull(Queue Q)//判断队列是否为满;
{
return Q->rear == Q->Capacity-1;
}
void MakeEmpty(Queue Q)//置空
{
Q->front = Q->rear = 0;
Q->size = 0;
}
int LengthOfQueue(Queue Q)//计算队列长度
{
return Q->rear - Q->front;
}
void EnQueue(Queue Q, ElementType data)//入队
{
if (IsFull(Q))
{
printf("Enqueue Error:the queue is full !!!");
exit(1);
}
Q->Array[Q->rear++] = data;
++Q->size;
}
void DeQueue(Queue Q)//出队
{
if (IsEmpty(Q))
{
printf("Dequeue Error: the queue is empty !!!");
exit(1);
}
++Q->front;
--Q->size;
}
void PrintQueue(Queue Q)//打印队列
{
if (IsEmpty(Q))
{
printf("Print warning: the queue is empty !!!");
}
int i = Q->front;
for (; i < Q->rear; i++)
{
printf("%d ", Q->Array[i]);
}
printf("\n");
}
3.主程序main.c
/********************************************************************************************************
Function:队列的数组实现
Date:2020/06/02
*********************************************************************************************************/
#include"Queue_Array.h"
int main()
{
Queue Q=CreatQueue();//创建一个空队列
for (int i = 0; i < 10; i++)
{
EnQueue(Q, i);//入队
}
PrintQueue(Q);//打印队列
printf("the length of the queue is:%d\n", LengthOfQueue(Q));//打印队列长度
for (int i = 0; i < 3; i++)
{
DeQueue(Q);//出队
}
PrintQueue(Q);//打印队列
printf("the length of the queue is:%d\n", LengthOfQueue(Q));//打印队列长度
MakeEmpty(Q);//置空
PrintQueue(Q);//打印队列
printf("the length of the queue is:%d\n", LengthOfQueue(Q));//打印队列长度
return 0;
}
4.运行结果