//
// main.c
// testQueue
//
// Created by lan on 16/3/12.
// Copyright © 2016年 lan. All rights reserved.
//
/*
静态队列:用数组实现
静态队列通常必须是循环队列
因为:无论是出队还是入队,头指针和尾指针都必须只加不减
如果不是循环队列,之前分配的内存不能再次使用
*/
#include <stdio.h>
#include <malloc/malloc.h>
#include <stdlib.h>
#include <stdbool.h>
typedef struct Queue {
int * pBase;
int front;
int rear;
}QUEUE, * PQUEUE;
void init(PQUEUE);
bool en_queue(PQUEUE, int);
bool out_queue(PQUEUE, int *);
bool is_empty(PQUEUE);
bool is_full(PQUEUE);
void traverse(PQUEUE);
int main(int argc, const char * argv[]) {
QUEUE Q;
int val;
init(&Q);
if (is_empty(&Q)) {
printf("队列为空\n");
}
en_queue(&Q, 1);
en_queue(&Q, 2);
en_queue(&Q, 3);
en_queue(&Q, 4);
en_queue(&Q, 5);
en_queue(&Q, 6);
en_queue(&Q, 7);
if ( is_full(&Q)) {
printf("队列已满\n");
}
traverse(&Q);
out_queue(&Q, &val);
printf("出队列的值 = %d\n", val);
traverse(&Q);
out_queue(&Q, &val);
printf("出队列的值 = %d\n", val);
traverse(&Q);
}
void init(PQUEUE pQ) {
pQ->pBase = (int *)malloc(sizeof(int) * 6);
//实际有效元素只有 5 个,其中留出 1 个方便对队列进行操作
// 如果不留出一个元素,当frout == rear 不能判断队列是空还是满
if (NULL == pQ->pBase) {
printf("内存分配失败,程序退出!\n");
exit(-1);
}
pQ->front = 0;
pQ->rear = 0;
return;
}
bool en_queue(PQUEUE pQ, int val) {
if (is_full(pQ)) {
return false;
}
pQ->pBase[pQ->rear] = val;
pQ->rear = (pQ->rear + 1) % 6;
return true;
}
bool out_queue(PQUEUE pQ, int * pVal) {
if (is_empty(pQ)) {
return false;
}
*pVal = pQ->pBase[pQ->front];
pQ->front = (pQ->front + 1) % 6;
return true;
}
bool is_empty(PQUEUE pQ) {
if (pQ->front == pQ->rear) {
return true;
} else {
return false;
}
}
bool is_full(PQUEUE pQ) {
if ((pQ->rear + 1) % 6 == pQ->front) {
return true;
} else {
return false;
}
}
void traverse(PQUEUE pQ) {
printf("遍历队列: ");
int cnt = pQ->front;
while (cnt != pQ->rear) {
printf("%d ", pQ->pBase[cnt]);
cnt = (cnt + 1) % 6;
}
printf("\n");
}
输出结果:
队列为空
队列已满
遍历队列: 1 2 3 4 5
出队列的值 = 1
遍历队列: 2 3 4 5
出队列的值 = 2
遍历队列: 3 4 5
Program ended with exit code: 0