c/c++ 陣列實現迴圈queue
阿新 • • 發佈:2018-11-13
程式碼:
#include <iostream> #define MAX 5 using namespace std; class Queue{ private: int a[MAX]; int Front; int Rear; public: Queue(); bool IsEmpty(); bool IsFull(); bool EnQueue(int data); int DeQueue(); //返回出佇列的值 bool ergodic(); //遍歷 }; /******初始化******/ Queue::Queue(){ this->Front = 0; this->Rear = 0; } bool Queue::IsEmpty(){ if(this->Front==this->Rear) return true; else return false; } bool Queue::IsFull(){ if((this->Rear+1)%MAX==this->Front) return true; else return false; } bool Queue::EnQueue(int data){ if(IsFull()) return false; this->a[this->Rear] = data; this->Rear = (this->Rear+1)%MAX; return true; } int Queue::DeQueue(){ if(IsEmpty()) return false; int data = this->a[this->Front]; this->Front = (this->Front+1)%MAX; return data; } bool Queue::ergodic(){ if(IsEmpty()) return false; if(this->Rear>this->Front){ for(int i=this->Front;i<this->Rear;i++) cout<<this->a[i]<<" "; } if(this->Rear<this->Front){ for(int i=this->Front;i<MAX;i++) cout<<this->a[i]<<" "; for(int i=0;i<this->Rear;i++) cout<<this->a[i]<<" "; } return true; } int main() { Queue q; q.EnQueue(1); q.EnQueue(2); q.EnQueue(3); q.EnQueue(4); int a = q.DeQueue(); cout << a << endl; q.EnQueue(5); q.ergodic(); return 0; }
測試:
加上template後可實現對任意型別的操作
程式碼:
#include <iostream> #define MAX 5 using namespace std; template <typename T> class Queue{ private: T a[MAX]; int Front; int Rear; public: Queue(); bool IsEmpty(); bool IsFull(); bool EnQueue(T data); T DeQueue(); //返回出佇列的值 bool ergodic(); //遍歷 }; /******初始化******/ template <typename T> Queue<T>::Queue(){ this->Front = 0; this->Rear = 0; } template <typename T> bool Queue<T>::IsEmpty(){ if(this->Front==this->Rear) return true; else return false; } template <typename T> bool Queue<T>::IsFull(){ if((this->Rear+1)%MAX==this->Front) return true; else return false; } template <typename T> bool Queue<T>::EnQueue(T data){ if(IsFull()) return false; this->a[this->Rear] = data; this->Rear = (this->Rear+1)%MAX; return true; } template <typename T> T Queue<T>::DeQueue(){ if(IsEmpty()) return false; T data = this->a[this->Front]; this->Front = (this->Front+1)%MAX; return data; } template <typename T> bool Queue<T>::ergodic(){ if(IsEmpty()) return false; if(this->Rear>this->Front){ for(int i=this->Front;i<this->Rear;i++) cout<<this->a[i]<<" "; } if(this->Rear<this->Front){ for(int i=this->Front;i<MAX;i++) cout<<this->a[i]<<" "; for(int i=0;i<this->Rear;i++) cout<<this->a[i]<<" "; } return true; } int main() { Queue<float> q; q.EnQueue(1); q.EnQueue(2.3); q.EnQueue(3); q.EnQueue(4.55); float a = q.DeQueue(); cout << a << endl; q.EnQueue(5); q.ergodic(); return 0; }