队列顺序结构C/C++实现(数据结构严蔚敏版)
生活随笔
收集整理的這篇文章主要介紹了
队列顺序结构C/C++实现(数据结构严蔚敏版)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1、頭文件Queue.h
#include<iostream> using namespace std;//定義4個空間,留出一個作為標志位,當Q.rear+1 / MAXQSIZE = Q.front時,說明隊列已滿#define MAXQSIZE 4 #define ok 1 #define error 0 #define flow 0typedef int ElemType; typedef int Status;//定義數據類型 typedef struct{ElemType *base;int front;int rear;}SqQueue;//初始化隊列 Status InitQueue(SqQueue& Q) {Q.base = new ElemType[MAXQSIZE];if(!Q.base) exit(flow);Q.front = Q.rear = 0;return ok; }//獲取隊列長度 int QueueLength(const SqQueue& Q){return ( Q.rear - Q.front+MAXQSIZE ) % MAXQSIZE; }//刪除隊列的頭,并返回刪除的數據 Status DeQueue(SqQueue& Q, ElemType& e){if(Q.front == Q.rear)return error;Q.front = (Q.front + 1) % MAXQSIZE;return ok; }//在隊尾進行插入 Status EnQueue(SqQueue& Q, ElemType e) {//插入到隊尾if((Q.rear + 1) % MAXQSIZE == Q.front){cout<<"隊列已滿\n\n"<<endl;return error;}Q.base[Q.rear] = e;Q.rear = (Q.rear+1) % MAXQSIZE;return ok; }//打印隊列 Status Print(const SqQueue& Q){int a = Q.front;if(Q.front == Q.rear){cout<<"這是個空隊列\n\n"<<endl;return error;}else{while(Q.rear != a){cout<<Q.base[a]<<" ";a++;}cout<<endl;return ok;}} //判斷隊列是否已滿 Status IsFull(SqQueue& Q){if(Q.front == (Q.rear+1) % MAXQSIZE){cout<<"隊列已滿,請先刪除再添加\n\n"<<endl;return error;} else{return ok;}}2、測試文件test.cpp:
#include "Queue.h"int main(void) {SqQueue Q;ElemType e;int n;InitQueue(Q);cout<<" 0------退出"<<endl;cout<<" 1------插入隊列"<<endl;cout<<" 2------刪除隊列的首部"<<endl;cout<<" 3------隊列的長度"<<endl; cout<<" 4------隊列的數據如下"<<endl; cout<<"請輸入你的操作"<<endl;cin>>n;while(1){switch(n){case 0:delete(Q.base); exit(flow);case 1:cout<<"輸入一個數據"<<endl;if(IsFull(Q)){cin>>e;EnQueue(Q, e);cout<<endl;}break;case 2:DeQueue(Q, e);cout<<"刪除的隊首數據是:"<<e<<endl;cout<<endl;break;case 3:cout<<"隊列的長度是:"<<QueueLength(Q);cout<<endl<<endl;break;case 4:cout<<"隊列如下:"<<endl;Print(Q);break;}cout<<" 0------退出"<<endl;cout<<" 1------插入隊列"<<endl;cout<<" 2------刪除隊列的首部"<<endl;cout<<" 3------隊列的長度"<<endl; cout<<" 4------隊列的數據如下"<<endl; cout<<"請輸入你的操作"<<endl;cin>>n;cout<<"\n\n";}}《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀
總結
以上是生活随笔為你收集整理的队列顺序结构C/C++实现(数据结构严蔚敏版)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 栈C/C++实现(数据结构严蔚敏版)
- 下一篇: 队列链式结构C/C++实现(数据结构严蔚