循環隊列

#include <stdio.h>
#include <stdlib.h>

#define MAX 6

typedef struct {
	int *data;
	int rear;	//尾“指針”,指向隊列尾元素的下一個位置
	int front;	//頭“指針”,指向隊列頭元素
}SqQueue;

void Init_Queue(SqQueue *Q) {
	Q->data = (int *)malloc(MAX * sizeof(int));
	Q->front = Q->rear = 0;
}

void Add_Queue(SqQueue *Q, int e) {
	if ((Q->rear + 1) % MAX == Q->front) {
		printf("Full!\n");
	}
	else {
		Q->data[Q->rear] = e;
		Q->rear = (Q->rear + 1) % MAX;
	}
}

void Delet_Queue(SqQueue *Q, int *e) {
	if (Q->front == Q->rear) {
		printf("Empty!\n");
	}
	else {
		*e = Q->data[Q->front];
		Q->front = (Q->front + 1) % MAX;
	}
}

void Print_Queue(SqQueue Q) {
	for (; Q.front < Q.rear; Q.front++) {
		printf("%d\n", Q.data[Q.front]);
	}
}

int main() {
	SqQueue queue;
	Init_Queue(&queue);
	int num = 0;
	do {
		printf("Input numbers\n");
		scanf("%d", &num);
		if (num != -1) {
			Add_Queue(&queue, num);
		}
	} while (num != -1);
	Print_Queue(queue);
	return 0;
}

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