说来惭愧,和上一篇文章几乎相同,几个区别: 本来是头删,改为了尾删,类的名字改了一下,其余部分可以说完全相同。
using namespace std;
template <typename T>
class My_shed //队列
{
private:
T *front;
T *last;
int num;
public:
//构造函数
My_shed(int size = 1)
{
front = new T[size];
last = front;
num = 0; //成员数初始化为0;
}
//析构函数
~My_shed()
{
delete []front;
front = last = NULL;
}
//拷贝构造函数
My_shed(const My_shed &other)
{
//原空间大小为num+1,申请空间
this->front = new T[other.num+1];
//存入
memcpy(this->front, other.front, (other.num+1)*sizeof (T));
this->num = other.num;
//指针调整指向
this->last = this->front + this->num;
}
//拷贝赋值
My_shed(My_shed R, const My_shed &other)
{
//释放原空间
delete []R.front;
R.last = NULL;
//原空间大小为num+1,申请空间
R.front = new T[other.num +1];
//存入
memcpy(R.front, other.front, (other.num+1)*sizeof (T));
R.num = other.num;
//指针调整指向
R.last = R.front + R.num;
}
//判空
bool empty()
{
if(num != 0)
return 0;
else
return 1;
}
//队尾入队
void push(const T val)
{
T *temp = new T[this->num+2]; //一个塞数据,一个空
memcpy(temp, this->front, (this->num+2)*sizeof(T));
//释放原本空间
delete []front;
//更新指针指向
this->front = temp;
this->last = this->front + num;
//存值
*(this->last) = val;
this->last++;
num++;
}
//出队
void pop()
{
//判空
if(this->empty())
{
cout<< "队列为空" <<endl;
return;
}
T *temp = last;
last = last-1; //头指针往后移一位
//释放原本位置的空间
delete temp;
//置空
temp = NULL;
num--;
}
int size() //求容量
{
return num;
}
//展示队列
T &at(int index)
{
return front[index]; //暂时不进行越界判断
}
};