首页 > 代码库 > 队列的实现

队列的实现

完整代码如下:

  1 #include <cstdio>  2 #include <cstdlib>  3 #include <iostream>  4 using namespace std;  5 typedef int datatype;  6 const int maxsize = 100;  7 struct seqQueue  8 {  9     datatype queue[maxsize]; 10     int front;    //指向队头的前一个数据,若和rear相等则说明队空 11     int rear;    //队尾,下标 12 }; 13  14 //初始化队 15 void init(seqQueue &q) 16 { 17     q.front = q.rear = maxsize - 1; 18 } 19  20 //入队 21 void enQueue(seqQueue &q, datatype e) 22 { 23     if ((q.rear + 1) % maxsize == q.front) 24         cout << "溢出" << endl; 25     else 26     { 27         q.rear = (q.rear + 1) % maxsize; 28         q.queue[q.rear] = e; 29     } 30 } 31  32 //出队 33 datatype delQueue(seqQueue &q) 34 { 35     if (q.rear == q.front) 36     { 37         cout << "下溢出" << endl; 38         return 0; 39     } 40     else 41     { 42         q.front = (q.front + 1) % maxsize; 43         return q.queue[q.front];    //front是队头的前一个数据的下标 44     } 45 } 46  47 //判断是否队空 48 bool isEmpty(seqQueue &q) 49 { 50     return q.rear == q.front ? true : false; 51 } 52  53 //打印队 54 void print(seqQueue &q) 55 { 56     int f = q.front, r = q.rear; 57     while (f != r) 58     { 59         f = (f + 1) % maxsize; 60         cout << q.queue[f] << ", "; 61     } 62     cout << endl; 63 } 64  65 //打印说明 66 void showHelp(void) 67 { 68     cout << "\n\n\n\n"; 69     cout << "\t\t\t 队列子系统\n"; 70     cout << "\t\t*******************************\n"; 71     cout << "\t\t*        1----进 队 列     *\n"; 72     cout << "\t\t*        2----出 队 列    *\n"; 73     cout << "\t\t*        3----队列空否    *\n"; 74     cout << "\t\t*        4----显示队列    *\n"; 75     cout << "\t\t*        0----返  回    *\n"; 76     cout << "\t\t*******************************\n"; 77     cout << "\t\t 请选择菜单项0-4:"; 78 } 79  80 int main() 81 { 82     seqQueue q; 83     init(q); 84     datatype e; 85     int k = 0; 86     bool flag = true; 87     do 88     { 89         showHelp(); 90         cin >> k; 91         switch (k) 92         { 93         case 1:    //入队 94             cout << endl << "请输入要进队的数据 "; 95             cin >> e; 96             enQueue(q, e); 97             break; 98         case 2:    //出队 99             cout << delQueue(q);100             break;101         case 3:    //判断队空与否102             flag = isEmpty(q);103             if (flag == true)104                 cout << "队空";105             else106                 cout << "队不空";107         case 4:    //打印队列108             cout << "队中元素如下" << endl;109             print(q);110             break;111         default:112             break;113         }114     } while (k != 0);115     return 0;116 }
View Code

 

队列的实现