迴圈佇列的插入與刪除操作(C++)
阿新 • • 發佈:2019-02-19
記錄一下C++實現迴圈佇列;
#include<iostream> using namespace std; class queue { public: queue(int max) { front = 0; rear = 0; maxlen = max; myqueue = new int[maxlen]; num = 0; } ~queue() { delete[]myqueue; } bool que_empty(); //判斷隊空; bool que_full(); //判斷隊滿; void in(int x); //入隊; void out(); //出隊; int length() const; //佇列長度; void print_que(); //列印佇列; private: int front; int rear; int maxlen; int *myqueue; int num; }; bool queue::que_empty() { return num == 0 ? true : false; } bool queue::que_full() { return num == maxlen ? true : false; } void queue::in(int x) { if (que_full()) cout << "插入失敗,已滿" << endl; else { myqueue[rear%maxlen] = x; rear = (rear + 1) % maxlen; num++; } } void queue::out() { if (que_empty()) cout << "刪除失敗,已空" << endl; else { front = (front + 1) % maxlen; num--; } } int queue::length() const { return num; } void queue::print_que() { for (int i = front; i < num + front; i++) { cout << myqueue[i%maxlen] << endl; } } int main() { queue *p = new queue(5); p->in(2); p->in(5); p->in(10); p->in(15); p->in(20); //p->in(25); p->out(); p->out(); cout<<"佇列長度是: "<<p->length()<<endl; p->print_que(); system("pause"); return 0; }