队列是只能向一端添加元素,从另一端删除元素的线性群体
循环队列
- 在想象中将数组弯曲成环形,元素出队时,后继元素不移动,每当队尾达到数组最后一个元素时,便再回到数组开头。
队列类模板
//Queue.h #ifndef QUEUE_H #define QUEUE_H #include <cassert> //类模板的定义 template <class T, int SIZE = 50> class Queue { private: int front, rear, count; T list[SIZE]; public: Queue(); void insert(const T &item); T remove(); void clear(); const T &getFront() const; int getLength() const; bool isEmpty() const; bool isFull() const; }; template <class T, int SIZE> Queue<T, SIZE>::Queue():front(0),rear(0),count(0){} template <class T, int SIZE> void Queue<T, SIZE>::insert(const T& item) { assert(count != SIZE); count++; list[rear] = item; rear = (rear + 1) % SIZE; } template <class T, int SIZE> T Queue<T, SIZE>::remove() { assert(count != 0); int temp = front; count--; front = (front + 1) % SIZE; return list[temp]; } template <class T, int SIZE> const T &Queue<T, SIZE>::getFront() const { return list[front]; } template <class T, int SIZE> int Queue<T, SIZE>::getLength() const { return count; } template <class T, int SIZE> bool Queue<T, SIZE>::isEmpty() const { return count == 0; } template <class T, int SIZE> bool Queue<T, SIZE>::isFull() const { return count == SIZE; } template <class T, int SIZE> bool Queue<T, SIZE>::clear() { count = 0; front = 0; rear = 0; } #endif //
怕什么真理无穷,进一寸有一寸的欢喜。---胡适