首页 > 代码库 > C++数组实现的循环队列

C++数组实现的循环队列

#include<iostream>#include <string>/*功能:数组实现的循环队列,C++实现,学习参考*/using namespace std;template <typename T>class Myloopqueue{private:T *queue;//存储用的数组int capacity;//存放个数int head;//指向队首int tail;//指向队尾public:Myloopqueue(int a);//无参构造Myloopqueue();//有参构造~Myloopqueue();//析构bool isEmpty();//判断空int getSize();//返回个数bool push(T a);//入队bool pop();//出队T top();//显示队首};template<typename T>Myloopqueue<T>::Myloopqueue(int a) :head(0), tail(0), capacity(a), queue(nullptr){queue = new T[capacity];}template<typename T>Myloopqueue<T>::Myloopqueue() : Myloopqueue(10){};template<typename T>Myloopqueue<T>::~Myloopqueue(){delete[] queue;}template<typename T>bool Myloopqueue<T>::isEmpty(){if (head == tail)return true;elsereturn false;}template<typename T>int Myloopqueue<T>::getSize(){return (tail - head + capacity) % capacity;}template<typename T>bool Myloopqueue<T>::push(T a){if ((tail - head + capacity) % capacity == capacity)return false;queue[tail] = a;tail = (tail + 1) % capacity;return true;}template<typename T>bool Myloopqueue<T>::pop(){if ((tail - head + capacity) % capacity == 0)return false;head = (head + 1) % capacity;return true;}template<typename T>T Myloopqueue<T>::top(){return queue[head%capacity];}int main(){Myloopqueue<string> queue(6);queue.push("one");queue.push("two");queue.push("three");queue.push("four");queue.push("five");cout << "队列长度" << queue.getSize() << endl;while (!queue.isEmpty()){cout << queue.top() << endl;queue.pop();}getchar();return 0;}

 

C++数组实现的循环队列