数组实现
#include <stdio.h>
#include <stdlib.h>
typedef int E;
typedef struct Queue {
E *array;
int capacity;
int rear,front; //队尾,队首指针
} *ArrayQueue;
_Bool initQueue(ArrayQueue queue) {
queue->array = malloc(sizeof(E) * 10);
if(queue->array == NULL ) return 0;
queue->capacity = 10;
queue->front = 0;//默认情况下队首和队尾都指向0的位置
queue->rear = 0;
return 1;
}
//入队操作
_Bool offerQueue(ArrayQueue queue,E element) {
if((queue->rear + 1)%queue->capacity == queue->front){ //队满
return 0;
}
queue->rear = (queue->rear + 1)%queue->capacity;//队尾先向后移动一位,注意取余计算才能实现循环
queue->array[queue->rear] = element;
return 1;
}
void printQueue(ArrayQueue queue) {//遍历队列
printf("<<< ");
int i = queue->front;
do {
i = (i+1)%queue->capacity;
printf("%d ",queue->array[i]);
} while (i != queue->rear);
printf("<<<\n");
}
_Bool isEmpty(ArrayQueue queue) {
return queue->rear == queue->front;//如果相等就是空
}
E pollQueue(ArrayQueue queue) {
queue->front = (queue->front + 1) % queue->capacity;//队首后移
return queue->array[queue->front]; //返回出队元素
}
int main() {
struct Queue queue;
initQueue(&queue);
for(int i = 1;i<=9;++i) {
offerQueue(&queue,i*100);
}
printQueue(&queue);
while(!isEmpty(&queue)) {
printf("%d ", pollQueue(&queue));
}
}