#ifndef _顺序队列_H
#define _顺序队列_H
template<class T> // 模板类,T是用来创建动态数组,
class Queue
{
public:
Queue(int queueCapacity = 10); // 队列的数量存储10个
bool IsEmpty() const; // 这是判断队列是不是空的,
T& Front() const; // 这个是读取队首的数据,
T& Rear() const; // 这个是读取或查看队尾的数据,中间的数据是不能查看或读取的,
void Push(const T& item); // 这是将一个数据从队尾压入的队列中,
void Pop(); // Pop是删除数据,从队首删除,
private:
T *queue; // T是用来创建一个动态的数组,
int front; // front 是用来记录队首的下标,
int rear; // rear 是用来记录队尾的下标,
int capacity; // 是记录数据中数目,
};
template<class T> // 类模板,
Queue<T>::Queue(int queueCapacity):capacity(queueCapacity)
{
if(capacity<1) throw "Queue capacity must be > 0";
queue = new T[capacity];
front = rear = 0;
}
template<class T> // 类模板,
inline bool Queue<T>::IsEmpty() const
{
return front == rear;
}
template<class T> // 类模板,
void Queue<T>::Push(const T &item) // 在给队列增加数据的时候,第一个位置是空着的,是为了push和pop的速度快,
{
//if(rear == capacity - 1) // 这表示如果队尾到(最后)它的容量了,就将队尾从0开始,否则继续进行加加,
// rear = 0;
//else
// rear++;
if((rear + 1)%capacity == front) // 队列满了,
{
//加倍
T* newQueue = new T[2*capacity];
int start = (front + 1) % capacity;
if(start < 2) // 没有回转,
copy(queue + start, queue + start + capacity - 1, newQueue);
else // 有回转,
{
copy(queue + start, queue + capacity, newQueue);
copy(queue, queue + rear + 1, newQueue + capacity - start);
}
front = 2 * capacity - 1;
rear = capacity - 2;
capacity *= 2;
delete[] queue;
queue = newQueue;
}
rear = (rear + 1) % capacity;
queue[rear] = item; // 这是将加入的数据放到队尾,
}
template<class T> // 类模板
inline T& Queue<T>::Front() const // 这是读队首的位置,
{
if(IsEmpty()) throw "Queue is empty , no front element";
return queue[(front + 1) % capacity]; // 第一个数据是空的,将加1 读取队首的位置,
}
template<class T> // 类模板
inline T& Queue<T>::Rear() const // 读队尾的位置,
{
if(IsEmpty()) throw "Queue is empty, No rear element";
return queue[rear];
}
template<class T> // 类模板
void Queue<T>::Pop()
{
if(IsEmpty()) throw "Queue is empty, Canot delete";
front = (front + 1) % capacity;
queue[front].~T();
}
#endif
#include <iostream>
#include "顺序队列.h"
using namespace std;
int main()
{
Queue<char> q(4);
q.Push('x');
q.Push('i');
cout << q.Front() << ", " << q.Rear() << endl;
q.Push('a');
q.Push('o');
q.Push('c');
cout << q.Front() << ", " << q.Rear() << endl;
/*q.Pop();
cout << q.Front() << ", " << q.Rear() << endl;*/
q.Push('u');
q.Push('i');
cout << q.Front() << ", " << q.Rear() << endl;
q.Push('l');
q.Push('o');
q.Push('v');
q.Push('e');
cout << q.Front() << ", " << q.Rear() << endl;
return 0;
}