C語言系列 : 環形佇列Circular Queue

複習以環形佇列的形式儲存資料。

完整程式碼:

//會浪費一個空間無法使用,但可以少一些判斷式
#include "pch.h"
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#define MAX 4
extern void EnQueue();
extern void DeQueue();
extern void Show();
extern int isQueueEmpty();
extern int isQueueFull();
int rear = 0, front = 0,i=0;
int cirque[MAX] = {0};
int main() {
	char option;
	while (1) {
		printf("\n ------------------------------------------ \n");
		printf("<1>enqueue   <2>dequeue   <3>show   <4>left \n");
		printf(" ------------------------------------------ ");
		printf("\n Please enter your choice...");
		option = _getche();//直接取得第一個輸入的字元
		switch (option) {
			case '1':
				EnQueue();
				break;
			case '2':
				DeQueue();
				break;
			case '3':
				Show();
				break;
			case '4':
				exit(1);
				break;
			default:
				printf("\n Input is error! \n");
		}
	}
}

extern void EnQueue() {
	if (isQueueFull() == false) { //Not Full
		printf("\n Please enter an element:");
		rear = (rear + 1) % MAX;
		scanf_s("%d",&cirque[rear]);
		printf("\n");
	}
	else {
		printf("\n The Circular Queue is Full! \n");//Full
	}
}
extern void DeQueue() {
	if (isQueueEmpty() == false) { //Not Empty
		printf("\n Delete the element.\n");
		front = (front + 1) % MAX;
	}
	else {
		printf("\n The Circular Queue is Empty! \n");//Empty
	}
}
extern void Show() {
	if (isQueueEmpty() == 1) {
		printf("\n The Circular Queue is Empty! \n");
	}
	else{
		if (isQueueFull() == 1) {
			printf("\n The Circular Queue is Full! \n");
		}
		i = front;
		printf("\n The Circular Queue: \n");
		printf("----------------------------\n");
		while (i != rear) {
			i = (i + 1) % MAX;
			printf("%d ", cirque[i]);
		}
		printf("\n ---------------------------- \n");
	}

}
extern int isQueueEmpty() {
	if (front == rear) {
		return 1;//empty
	}
	else return 0;
}
extern int isQueueFull() {
	if (front == (rear+1)%MAX) {
		return 1;//Full
	}
	else return 0;
}

執行結果:

 

_______________________________________________

我們透過閱讀,拼湊出真實世界的面貌,
並在反覆的探索及思維中,打破由自我無知與偏見所建立的籓籬。