数据结构算法练习1-循环双端队列
//double_queue.h template <typename T> class DoubleQueue { public: DoubleQueue(int size=10); ~DoubleQueue(); void EnQueue(T item, int end); void DeQueue(int end); bool IsEmpty(); bool IsFull(); void List(int end); private: T* data_; int end1_; int end2_; int size_; }; template <typename T> DoubleQueue<T>::DoubleQueue(int size/* =10 */) : size_(size) , end1_(0) , end2_(0) { data_ = new T[size]; } template <typename T> DoubleQueue<T>::~DoubleQueue() { delete [] data_; } template <typename T> void DoubleQueue<T>::EnQueue(T item, int end) { if (end == 1) { end1_ = (end1_ + 1) % size_; data_[end1_] = item; } else { data_[end2_] = item; end2_ = (end2_-1+size_)%size_; } } template <typename T> void DoubleQueue<T>::DeQueue(int end) { assert(!IsEmpty()); if (end == 1) { end1_ = (end1_ - 1) % size_; } else { end2_ = (end2_ + 1 +size_) % size_; } } template <typename T> bool DoubleQueue<T>::IsEmpty() { return end1_ == end2_; } template <typename T> bool DoubleQueue<T>::IsFull() { return (end1_+1)%size_ == end2_; } template <typename T> void DoubleQueue<T>::List(int end) { if (end == 1) { for (int i=(end2_+1)%size_; i!=(end1_+1)%size_; i=(i+1)%size_) { cout<<data_[i]<<setw(3); } } else { for (int i=end1_; i!=(end2_+1)%size_; i=(i-1+size_)%size_) { cout<<data_[i]<<setw(3); } } }
测试
int main() { DoubleQueue<int> queue(5); queue.EnQueue(1, 1); queue.EnQueue(2, 1); queue.EnQueue(3, 1); queue.EnQueue(4, 1); queue.List(1); system("pause"); return 0; }