循环队列实现及基本操作
C++源码如下:
1 #include<iostream> 2 #define MAXQUEUESIZE 100 3 using namespace std; 4 typedef struct CircularQueue//循环队列结构 5 { 6 int *base; 7 int front; 8 int rear; 9 }CQ; 10 11 CQ CreateCircularQueue()//创建空队列 12 { 13 CQ Q; 14 Q.base=new int[MAXQUEUESIZE]; 15 if(!Q.base) 16 cout<<"内存分配失败!"<<endl; 17 Q.front=Q.rear=0; 18 return Q; 19 } 20 CQ InitQueue(CQ Q) 21 { 22 int num,i; 23 cout<<"输入要初始化元素个数:"; 24 cin>>num; 25 for(i=0;i<num;i++) 26 { 27 cout<<"输入元素:"; 28 cin>>Q.base[Q.rear]; 29 Q.rear=(Q.rear+1)%MAXQUEUESIZE; 30 } 31 return Q; 32 } 33 34 35 CQ EnterQueue(CQ Q,int n)//插入n为新的队尾元素 36 { 37 if(((Q.rear+1)%MAXQUEUESIZE)==Q.front) 38 { 39 cout<<"队列已满,无法入队列"<<endl; 40 } 41 else 42 { 43 Q.base[Q.rear]=n; 44 Q.rear=(Q.rear+1)%MAXQUEUESIZE; 45 } 46 return Q; 47 } 48 CQ OutQueue(CQ Q)//队头元素出队列 49 { 50 if(Q.front==Q.rear) 51 cout<<"队列为空"<<endl; 52 else 53 Q.front=(Q.front+1)%MAXQUEUESIZE; 54 return Q; 55 } 56 int QueueLength(CQ Q) 57 { 58 return (Q.rear-Q.front+MAXQUEUESIZE)%MAXQUEUESIZE;//注意要加上MAXQUEUESIZE,否则可能出现长度为负数 59 } 60 void PrintQueue(CQ Q) 61 { 62 int i; 63 i=Q.front; 64 while(((i+1)%MAXQUEUESIZE)!=Q.rear) 65 { 66 cout<<Q.base[i]<<"-->"; 67 i=(i+1)%MAXQUEUESIZE; 68 } 69 cout<<Q.base[i]<<endl; 70 } 71 72 CQ EmptyQueue(CQ Q) 73 { 74 Q.front=Q.rear=0; 75 return Q; 76 } 77 void DestroyQueue(CQ Q) 78 { 79 delete[] Q.base; 80 } 81 82 int main() 83 { 84 CQ Q; 85 int choice,n; 86 Q=CreateCircularQueue(); 87 Q=InitQueue(Q); 88 while(1) 89 { 90 system("pause"); 91 system("cls"); 92 cout<<"1.元素入队列"<<endl; 93 cout<<"2.队头元素出队列"<<endl; 94 cout<<"3.打印队列元素"<<endl; 95 cout<<"4.队列长度"<<endl; 96 cout<<"5.清空队列"<<endl; 97 cout<<"0.退出程序"<<endl; 98 cout<<"选择操作:"; 99 cin>>choice; 100 switch(choice) 101 { 102 case 1:cout<<"输入入队元素:";cin>>n;Q=EnterQueue(Q,n);break; 103 case 2:Q=OutQueue(Q);break; 104 case 3:cout<<"循环队列为:";PrintQueue(Q);break; 105 case 4:cout<<"队列长度为:"<<QueueLength(Q)<<endl;break; 106 case 5:Q=EmptyQueue(Q);break; 107 case 0:DestroyQueue(Q);exit(0); 108 } 109 } 110 return 0; 111 }