队列-满空及出入队

代码如下:

 1 #include <iostream>
 2 using namespace std;
 3 //队列 
 4 struct Queue
 5 {
 6     int a[100]; 
 7     int front;
 8     int rear;
 9 } q;
10 int n;//存实际占用空间为n+1,即0-n。 
11 //队满
12 bool isfull()
13 {
14     return (q.rear+1)%(n+1)==q.front;
15 }
16 //队空 
17 bool isempty()
18 {
19     return q.rear==q.front;
20 }
21 //入队
22 void inq(int x)
23 {
24     if(!isfull())
25     {
26         q.a[q.rear]=x;
27         q.rear= (q.rear+1)%(n+1);
28     }
29     else
30     {
31         cout<<"The queue is full.";
32     }
33 }
34 //出队
35 int outq()
36 {
37     int t;
38     if(isempty())
39     {
40         cout<<"The queue is empty.";
41         return -1;
42     }
43     else
44     {
45         t=q.a[q.front];
46         q.front=(q.front+1)%(n+1);
47         return t;
48     }
49 }
50 main()
51 {
52     q.front=0;
53     q.rear=0;
54     cin>>n;
55     for(int t,i=1;i<=n;i++)
56     {
57         cin>>t;
58         inq(t);
59     }
60     inq(100);//满队入队,报错 
61     for(int i=1;i<=n;i++)
62     {
63         cout<<outq()<<" ";
64     }
65     cout<<outq();//空队出队,报错 
66 }

猜你喜欢

转载自www.cnblogs.com/wanjinliu/p/11415614.html