队列是一种特殊的线性表,特殊之处在于它只允许在表的前端(front)进行删除操作,而在表的后端(rear)进行插入操作,和栈一样,队列是一种操作受限制的线性表。进行插入操作的端称为队尾,进行删除操作的端称为队头。
#include<iostream>
#include<deque>
#include<string>
template <typename T>
class Queue{
private:
int Front,Rear;
T *data;
std::string::size_type Size;
public:
Queue()
{
Size =20;
Front=0;
Rear=0;
data = new T[Size];
}
~Queue()
{
delete[] data;
}
void clear()
{
Front=0;
Rear=0;
Size=0;
}
bool empty()const
{
return (Front==Rear);
}
std::string::size_type size()
{
return (Rear-Front+Size)%Size;
}
std::string::size_type max_size()
{
return Size;
}
void resize(std::string::size_type RE)
{
Size=RE;
T* temp = data;
data = new T[RE];
for(auto i = 0,j=Front;i<Size||j<Rear;i++,j++)
data[i] = temp[j];
Rear = Size>Rear?size():Size;
Front = 0;
delete[]temp;
}
void push_front(const T& val)
{
if(size()!=Size)
{
data[Front] = val;
Front = (Front-1+Size)%Size;
}
else
std::cout<<"上溢"<<std::endl;
}
void push_back(const T& val)
{
if(size()!=Size)
{
data[Rear] = val;
Rear = (Rear+1)%Size;
}
else
std::cout<<"上溢"<<std::endl;
}
void pop_front()
{
if(!empty())
{
Front = (Front+1)%Size;
}
else
{
std::cout<<"下溢"<<std::endl;
}
}
void pop_back()
{
if(!empty())
{
Rear = (Rear-1+Size)%Size;
}
else
{
std::cout<<"下溢"<<std::endl;
}
}
T& top_front()
{
if(!empty()) return data[Front];
}
T& top_back()
{
if(!empty()) return data[Rear];
}
void show()
{
for(int i = Front;i<Rear;i++)
{
std::cout<<data[i]<<" ";
}
std::cout<<std::endl;
}
};