/****************************
* Date : 2015-07-23
* Description: queue.h
*****************************/
#ifndef _QUEUE_H
#define _QUEUE_H
// class queue
template<class T>
class Queue{
public:
Queue(int MaxQueueSize = 10);
~Queue() {delete [] queue;}
bool IsEmpty() const {return front == rear;}
bool IsFull() const {return (((rear+1)%MaxSize == front) ? 1 : 0);}
T Front() const; // 返回队首元素
T Rear() const; // 返回队尾元素
Queue<T>& Push(const T &x); //队尾添加元素
Queue<T>& Pop(); //删除队首元素,但不返回其值
int size() const; // 返回队列中元素的个数
private:
int front;
int rear;
int MaxSize;
T *queue;
};
//
template<class T>
Queue<T>::Queue(int MaxQueueSize /* = 10 */)
{
MaxSize = MaxQueueSize + 1;
front = rear = 0;
queue = new T[MaxSize];
}
//
template<class T>
T Queue<T>::Front() const
{
if(IsEmpty())
throw out_of_range("队列为空!");
return queue[(front+1)%MaxSize];
}
//
template<class T>
T Queue<T>::Rear() const
{
if(IsEmpty())
throw out_of_range("队列为空!");
return queue[rear];
}
//
template<class T>
Queue<T>& Queue<T>::Push(const T &x)
{
if(IsFull())
throw out_of_range("队列已满!");
rear = (rear + 1) % MaxSize;
queue[rear] = x;
//queue[(rear+1)%MaxSize] = x; // 注意此错误!!!
return *this;
}
//
template<class T>
Queue<T>& Queue<T>::Pop()
{
if(IsEmpty())
throw out_of_range("队列为空!");
front = (front + 1) % MaxSize;
return *this;
}
//
template<class T>
int Queue<T>::size() const
{
if(front < rear)
return (rear - front);
else
return (front - rear);
}
#endif // _QUEUE_H