循环队列

循环队列

#pragma once
#include 
using namespace std;
template<class T>
class Queue
{
private:
	T* queue;
	int capcity;
	int front, rear;
public:
	Queue(int cap);
	~Queue();
	bool isEmpty();
	T Front();
	T Rear();
	void pop();
	void Push(T t);
};
template<class T>
Queue<T>::Queue(int cap)
{
	this->capcity = cap;
	queue = new T[capcity];
}
template<class T>
Queue<T>::~Queue()
{
	if (queue != nullptr)
	{
		delete[]queue;
		queue = nullptr;
		capcity = 0;
	}
}
template<class T>
inline bool Queue<T>::isEmpty()
{
	return rear == front;
}
template <class T>
T Queue<T>::Front()
{
	if (this->isEmpty())
	{
		return -1;
	}
	else
	{
		return queue[(front+1)%capcity];
	}
}
template <class T>
T Queue<T>::Rear()
{
	if (this->isEmpty())
	{
		return -1;
	}
	else
	{
		return queue[rear] ;
	}
}
template <class T>
void Queue<T>::Push(T t)
{
	if ((rear + 1) % capcity == front)
	{
		T* newQueue = new T[2 * capcity];
		if (rear < front)
		{
			//有一个循环
			copy(queue + front, queue + capcity, newQueue);
			copy(queue, queue + rear+1, newQueue + capcity - front);
		}
		else
		{
			//不够一个循环
			copy(queue, queue+capcity, newQueue);
		}
		front = 0;
		rear = capcity-1;
		capcity = capcity * 2;
		delete[]queue;
		queue = newQueue;

	}
	rear = (rear + 1) % this->capcity;
	queue[rear] = t;
}
template <class T>
void Queue<T>::pop()
{
	if (isEmpty())
	{
		cout << "队列为空" << endl;
	}
	else
	{
		front = (front + 1) % capcity;
	}
}

你可能感兴趣的:(循环队列)