由于博主比较懒,所以呢循环队列的原理图如下:
代码如下:
1 #include "stdafx.h" 2 #include<iostream> 3 using namespace std; 4 #define OK 1 5 #define ERROR 0 6 #define OVERFLOW -2 7 #define MAXSIZE 100 8 typedef int Status; 9 typedef int QElemType; 10 typedef struct 11 { 12 QElemType *base; 13 int front; 14 int rear; 15 }SqQueue; 16 17 Status InitQueue(SqQueue &Q) //初始化队列 18 { 19 Q.base = new QElemType[MAXSIZE]; 20 if (!Q.base) 21 exit(OVERFLOW); 22 Q.front = Q.rear = 0; 23 return OK; 24 } 25 26 Status QueueLength(SqQueue Q) //求队列的长度 27 { 28 return (Q.rear - Q.front + MAXSIZE) % MAXSIZE; 29 } 30 31 Status EnQueue(SqQueue &Q, QElemType e) //进队 32 { 33 if ((Q.rear + 1) % MAXSIZE == Q.front) 34 return ERROR; 35 Q.base[Q.rear] = e; 36 Q.rear = (Q.rear + 1) % MAXSIZE; 37 return OK; 38 } 39 40 Status DeQueue(SqQueue &Q, QElemType &e)//出队 41 { 42 if (Q.front == Q.rear) 43 return ERROR; 44 e = Q.base[Q.front]; 45 Q.front = (Q.front + 1) % MAXSIZE; 46 return OK; 47 } 48 49 QElemType GetHead(SqQueue Q) //取队头元素 50 { 51 if (Q.front != Q.rear) 52 return Q.base[Q.front]; 53 } 54 55 Status Visit(SqQueue Q) //相当于输出 56 { 57 if (Q.rear == Q.front) 58 { 59 cout << "空队列" << endl; 60 return ERROR; 61 } 62 while (Q.front != Q.rear) 63 { 64 cout << Q.base[Q.front] << " "; 65 Q.front = (Q.front + 1) % MAXSIZE; 66 } 67 cout << endl; 68 return OK; 69 } 70 int main() 71 { 72 SqQueue Q; 73 int e; 74 InitQueue(Q); 75 EnQueue(Q, 1); 76 EnQueue(Q, 3); 77 EnQueue(Q, 5); 78 EnQueue(Q, 7); 79 EnQueue(Q, 9); 80 Visit(Q); 81 cout << "队列的长度为:"; 82 cout << QueueLength(Q) << endl; 83 cout << "循环队列的队头元素为:"; 84 cout << GetHead(Q) << endl; 85 DeQueue(Q, e); 86 EnQueue(Q, 11); 87 Visit(Q); 88 cout << "现在队列的长度为:"; 89 cout << QueueLength(Q) << endl; 90 cout << "现在循环队列的队头元素为:"; 91 cout << GetHead(Q) << endl; 92 return 0; 93 94 }
输出结果: