#include <stdlib.h> #include <stdio.h> #include <stdbool.h> #include <math.h> /** 循环队列的顺序存储实现 队列头在队列第一个元素前 不指向元素 队列尾是指向队列最后一个元素 */ #define ERROR -1 #define ElementType int typedef int Position; struct QNode{ ElementType *Data; Position Front, Rear; // 队列头尾指针 int MaxSize; // 队列最大容量 }; typedef struct QNode *Queue; Queue CreateQueue(int MaxSize){ Queue Q = (Queue)malloc(sizeof(struct QNode)); Q->Data = (ElementType *)malloc(MaxSize * sizeof(ElementType)); Q->Front = 0; Q->Rear = 0; Q->MaxSize = MaxSize; return Q; } // 数组预留一个空位代表队列满 bool IsFull(Queue Q){ return ((Q->Rear+1)%Q->MaxSize == Q->Front); } bool AddQ(Queue Q,ElementType X){ if(IsFull(Q)){ printf("Queue is Full\n"); return false; }else{ Q->Rear = (Q->Rear+1)%Q->MaxSize; Q->Data[Q->Rear] = X; return true; } } bool IsEmpty(Queue Q){ return (Q->Front == Q->Rear); } ElementType DeleteQ(Queue Q){ // 出队 并返回出队的元素 if(IsEmpty(Q)){ printf("Queue is Empty\n"); return ERROR; }else{ Q->Front = (Q->Front+1)%Q->MaxSize; return Q->Data[Q->Front]; } } int main(){ Queue q = CreateQueue(10); AddQ(q, 0); AddQ(q, 1); int a; a = DeleteQ(q); printf("a = %d\n",a); AddQ(q, 2); a = DeleteQ(q); printf("a = %d\n",a); a = DeleteQ(q); printf("a = %d\n",a); a = DeleteQ(q); printf("a = %d\n",a); return 0; }
标签:顺序,return,队列,Queue,MaxSize,循环,Front,Rear From: https://www.cnblogs.com/xinrenbool/p/16886764.html