1 #include "stdafx.h" 2 #include <iostream> 3 #include <exception> 4 using namespace std; 5 6 //循环队列的顺序存储结构 7 typedef int QElemType; 8 typedef int Status; 9 const int ok = 1; 10 const int error = 0; 11 const int maxSize = 5; 12 13 typedef struct 14 { 15 QElemType data[maxSize]; 16 int front; 17 int rear; 18 }SqQueue,*pSqQueue; 19 20 //初始化队列 21 Status InitQueue(SqQueue *Q) 22 { 23 Q->front = 0; 24 Q->rear = 0; 25 for(int i = 0;i!=maxSize;++i) 26 Q->data[i]=0; 27 return ok; 28 } 29 30 //获取队列长度 31 int QueueLenght(const SqQueue *Q) 32 { 33 return (maxSize-Q->front+Q->rear)%maxSize; 34 } 35 36 //入队操作,如果队列未满,则插入元素e为Q新的队尾元素 37 Status EnQueue(SqQueue *Q,const int &e) 38 { 39 if((Q->rear+1)%maxSize==Q->front) 40 { 41 cout<<"队列已满,入队失败!"<<endl; 42 return error; 43 } 44 Q->data[Q->rear]=e; 45 Q->rear=(Q->rear+1)%maxSize; 46 return ok; 47 } 48 Status DeQueue(SqQueue *Q) 49 { 50 if(Q->rear==Q->front) 51 return error; 52 cout<<"出队列:"<<Q->data[Q->front]<<endl;; 53 Q->front=(Q->front+1)%maxSize; 54 return ok; 55 } 56 void outputQueue(const SqQueue *Q) 57 { 58 if(Q->rear == Q->front) 59 { 60 cout<<"队列空了!"<<endl; 61 return ; 62 } 63 64 if(Q->rear>Q->front) 65 { 66 for(int i = Q->front ;i != Q->rear;i++) 67 cout<<Q->data[i]<<" "; 68 } 69 else 70 { 71 for(int i = Q->front;i!=maxSize;++i) 72 { 73 cout<<Q->data[i]<<" "; 74 } 75 for(int j = 0;j!=Q->rear;++j) 76 { 77 cout<<Q->data[j]<<" "; 78 } 79 } 80 } 81 int _tmain(int argc, _TCHAR* argv[]) 82 { 83 SqQueue *qQueue = new SqQueue; 84 InitQueue(qQueue); 85 EnQueue(qQueue,1); 86 EnQueue(qQueue,2); 87 EnQueue(qQueue,3); 88 EnQueue(qQueue,4); 89 DeQueue(qQueue); 90 DeQueue(qQueue); 91 DeQueue(qQueue); 92 DeQueue(qQueue); 93 EnQueue(qQueue,5); 94 DeQueue(qQueue); 95 cout<<"队列长度为:"<<QueueLenght(qQueue)<<endl; 96 outputQueue(qQueue); 97 return 0 ; 98 }