//循环队列 #include <stdio.h> #include<stdlib.h> #define MAXSIZE 5 #define status int struct Queue { int* base; int front; int real; }Q; status initQueue(Queue &Q) { Q.base=(int *)malloc(MAXSIZE*sizeof(int)); if(!Q.base) { printf(" 内存分配失败,程序终止!\n"); exit(-1); } Q.front=Q.real=0; return 1; } bool emptyQueue(Queue Q) { if(Q.front==Q.real) return true; return false; } bool full_Queue(Queue Q) //队满 { if((Q.real+1)%MAXSIZE==Q.front) return true; return false; } status QueueLenngth(Queue Q) { // 返回队列长度 return (Q.real-Q.front+MAXSIZE)%MAXSIZE; } int pop (Queue &Q,int &e) //出队 { if(!emptyQueue(Q)) { e=Q.base[Q.front]; Q.front=(Q.front+1)%MAXSIZE; return 1; } else { printf("队为空,出队失败!\n"); return 0; } } int push(Queue &Q,int &e) //入队 { if((Q.real+1)%MAXSIZE==Q.front ) // 队满 { printf("队已满,入队失败!\n"); return 0; } Q.base[Q.real]=e; Q.real=(Q.real+1)%MAXSIZE; return 1; } void QueueTraverse(Queue Q) { int t=Q.front; while(t!=Q.real) { printf("%d ",Q.base[t]); t=(t+1)%MAXSIZE; } printf("\n"); return; } int main() { Queue Q; int i,e; initQueue(Q); for(i=1;i<=5;++i) { push(Q,i); QueueTraverse(Q); } pop(Q,e);QueueTraverse(Q); pop(Q,e);QueueTraverse(Q); push(Q,e); QueueTraverse(Q); return 0; }
时间: 2024-10-28 21:16:38