队列的数组(C语言)实现

本篇博客将实现一般队列的数组结构,具体实现的操作有入队、出队、计算队列长度、判断队列是否为空、为满等。详细工程代码如下:

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.运行结果
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值