代码:
#include<stdio.h> #include<malloc.h> #define MaxSize 5 typedef char ElemType; typedef struct { ElemType data[MaxSize]; int front,rear; }SqQueue; //初始化 void InitQueue(SqQueue *&q) { q=(SqQueue *)malloc(sizeof(SqQueue)); q->front=q->rear=0; } //销毁队列 void DestroyQueue(SqQueue *&q) { free(q); } //判空 bool QueueEmpty(SqQueue *q) { return(q->front==q->rear); } //入队 bool enQueue(SqQueue *&q,ElemType e) { if((q->rear+1)%MaxSize==q->front) return false; q->rear=(q->rear+1)%MaxSize; q->data[q->rear]=e; return true; } //出队 bool deQueue(SqQueue *&q,ElemType &e) { if(q->front==q->rear) return false; q->front=(q->front+1)%MaxSize; e=q->data[q->front]; return true; } //环形队列逆置 void ReverseQueue(SqQueue *q) { int len=((q->rear-q->front+MaxSize)%MaxSize); int a[MaxSize]; ElemType e; for(int i=0;i<len;i++) { deQueue(q,e); a[i]=e; } q->front=q->rear=0; for(int j=len-1;j>=0;j--) { q->rear=(q->rear+1)%MaxSize; q->data[q->rear]=a[j]; } } void main() { ElemType e; SqQueue *q; InitQueue(q); if(!enQueue(q,‘a‘)) printf("队满"); if(!enQueue(q,‘b‘)) printf("队满"); if(!enQueue(q,‘c‘)) printf("队满"); if(!enQueue(q,‘d‘)) printf("队满"); printf("\n"); printf("a、b、c、d进入环形队列\n"); ReverseQueue(q); printf("逆置:\n"); while(!QueueEmpty(q)) { deQueue(q,e); printf("%c ",e); } DestroyQueue(q); }
原文:http://blog.csdn.net/u010286751/article/details/22764229