C++编译器
基本操作思想
循环队列(逻辑上,留一个空间为空)
定义存放元素的数组最大长度MAXSIZE。
定义表头指针front,表尾指针rear。且初始化表头表尾指针相等且为0。
判断是否队列是否为空:front==rear。
判断队列是否已满:front==(rear+1)%MAXSIZE。
获取队列长度:(rear-front+MAXSIZE)%MAXSIZE。
进队后队尾指针操作:rear = (rear+1)%MAXSIZE。
出队后队头指针操作:front = (front+1)%MAXSIZE。
源代码
#include <stdio.h>
#define MAXSIZE 10
#define INITQUEUESTATUS 0
#define NAN -999999
struct Queue {
int data[MAXSIZE];
int front;
int rear;
/*
初始化队列
*/
void initQueue() {
this->front = INITQUEUESTATUS;
this->rear = INITQUEUESTATUS;
}
/*
入队操作
*/
void enQueue(int value) {
if (this->isFull()) {
printf("this Queue is full,can not push\n");
return;
}
this->data[this->rear] = value;
this->rear = (this->rear + 1) % MAXSIZE;
}
/*
出队操作
*/
int deQueue() {
if (this->isEmpty()) {
printf("this Queue is empty,can not pop\n");
return NAN;
}
int value = this->data[this->front];
this->front = (this->front + 1) % MAXSIZE;
return value;
}
/*
获取队头元素值
*/
int getHead() {
if (this->isEmpty()) {
printf("this Queue is empty,not have head element");
return NAN;
}
return this->data[this->front];
}
/*
获取队列长度
*/
int lenth() {
return (this->rear - this->front + MAXSIZE) % MAXSIZE;
}
/*
判断队列是否已满
*/
bool isFull() {
return (this->rear + 1) % MAXSIZE == this->front;
}
/*
判断队列是否为空
*/
bool isEmpty() {
return this->front == this->rear;
}
void print() {
if (this->isEmpty()) {
printf("this Queue is empty\n");
return;
}
int index = this->front;
while (index != this->rear) {
printf("%d ", this->data[index]);
index = (index + 1) % MAXSIZE;
}
printf("lenth=%d\n", this->lenth());
}
};
int main() {
Queue queue;
queue.initQueue();
for (int i = 0; i < 10; i++) {
queue.enQueue(i);
}
queue.print();
for (int i = 0; i < 5; i++) {
queue.deQueue();
}
queue.print();
printf("this Queue head value=%d\n", queue.getHead());
for (int i = 0; i < 6; i++) {
queue.enQueue(i);
}
queue.print();
printf("this Queue head value=%d\n", queue.getHead());
for (int i = 0; i < 10; i--) {
int value = queue.deQueue();
if (value == NAN) {
break;
}
}
return 0;
}
运行截图