赞
踩
#include <iostream> #include <malloc.h> using namespace std; // 循环队列的实现 #define MAX_SIZE 9 typedef int ElemType; // 定义结构体 typedef struct QueueNode{ ElemType data[MAX_SIZE]; // 存数据 int front, rear; // 头尾下标 } *Queue; // 函数声明 Queue Init(); bool In(Queue &Q, ElemType e); bool Out(Queue &Q, ElemType &e); bool IsEmpty(Queue &Q); bool IsFull(Queue &Q); void Print(Queue &Q); //初始化 Queue Init(){ Queue ans = (Queue) malloc(sizeof(QueueNode)); if (ans->data == NULL) return NULL; ans->front = ans->rear = 0; return ans; } //入队 bool In(Queue &Q, ElemType e){ // 若已满 if(IsFull(Q)) return false; Q->data[Q->rear] = e; // 先存入元素 ++Q->rear %= MAX_SIZE; // 再将尾下标循环加1 return true; } //出队 bool Out(Queue &Q, ElemType &e){ if(IsEmpty(Q)) return false; e = Q->data[Q->front]; ++Q->front %= MAX_SIZE; return true; } //判空 bool IsEmpty(Queue &Q){ return Q->rear == Q->front; } //判满,留出1个空间表示队满状态 bool IsFull(Queue &Q){ return (Q->rear + 1) % MAX_SIZE == Q->front; } // 打印 void Print(Queue &Q){ printf("\n"); // 计算元素总数 int sum = (Q->rear + MAX_SIZE - Q->front) % MAX_SIZE; for(int cur = 0; cur < sum; cur++){ printf("%d ", Q->data[(Q->front + cur) % MAX_SIZE]); } printf("\n"); } int main() { Queue Q = Init(); ElemType e; if(Q == NULL) { printf("初始化失败"); return 0; } else printf("初始化成功"); for(int i = 0; i < 10; i++){ In(Q, i); } Print(Q); for(int i = 0; i < 5; i++){ if (!Out(Q, e)) printf("队列为空"); else printf("出队:%d\n", e); } printf("当前元素:"); Print(Q); for(int i = 0; i < 10; i++){ if (!In(Q, i * 2)) { printf("队满\n"); break; } else printf("入队:%d\n", i * 2); } printf("当前元素:"); Print(Q); return 0; }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。