隊列的數組(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.運行結果
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章