自己封装栈和队列的模板类
#include <iostream>
using namespace std;
template <typename T>
class mystack
{
private:
T *data;
int size;
int top;
public:
//无参构造
mystack():size(10)
{
data = new T[size];
top = -1;
size =10;
}
//有参构造
mystack(int s)
{
data = new T[s];
top = -1;
size = s;
}
//赋值
mystack &operator=(mystack &R)
{
delete []this;
data = new T[R.size];
size = R.size;
top = R.top;
return *this;
}
//访问栈顶元素
T gettop()
{
return data[top];
}
//判空
bool empty()
{
return top==-1;
}
//求最大容量
int getsize()
{
return size;
}
//向栈顶插入元素
void push(int a)
{
if(top==size-1)
{
expend(); //二倍扩容
}
data[top+1] = a;
top++;
}
//删除栈顶元素
void pop()
{
data[top] = 0;
top--;
}
//输出栈中元素
void show()
{
for(int i=0;i<=top;i++)
{
cout<<data[i]<<" ";
}
cout<<endl;
}
//二倍扩容
void expend()
{
T *temp = new T[size*2];
for(int i=0;i<size;i++)
{
temp[i] = data[i];
}
delete []data;
data = temp;
size = size*2;
}
};
int main()
{
mystack<double> s(3);
s.push(99);
s.push(77);
s.push(88);
//s.pop();
s.show();
cout<<"size="<<s.getsize()<<endl;
s.push(66);
s.show();
cout<<"size="<<s.getsize()<<endl;
mystack<double> s1 = s;
s1.show();
return 0;
}
#include <iostream>
using namespace std;
template <typename T>
class myqueue
{
private:
T *data;
int size;
int front;
int tail;
public:
//无参构造
myqueue():size(10)
{
data = new T[size];
size =10;
front = 0;
tail = 0;
}
//有参构造
myqueue(int s)
{
data = new T[s];
size = s;
front = 0;
tail = 0;
}
//赋值
myqueue &operator=(myqueue &R)
{
delete []this;
data = new T[R.size];
size = R.size;
front = R.front;
tail = R.tail;
return *this;
}
//访问第一个元素
T getfront()
{
if(empty())
{
cout<<"队列中没有元素"<<endl;
return -1;
}
return data[front];
}
//访问最后一个元素
T back()
{
if(empty())
{
cout<<"队列中没有元素"<<endl;
return -1;
}
return data[tail];
}
//判空
bool empty()
{
return front==tail;
}
//判满
bool full()
{
return (tail+1)%size == front;
}
//求最大容量
int getsize()
{
return size;
}
//向队列尾部插入元素
void push(T a)
{
if(full())
{
cout<<"队列满了"<<endl;
}
else
{
data[tail] = a;
tail = (tail+1)%size;
}
}
//删除首个元素
void pop()
{
if(empty())
{
cout<<"队列为空"<<endl;
return ;
}
data[front] = 0;
front = (front+1)%size;
}
//输出队列中元素
void show()
{
if(empty())
{
cout<<"队列为空"<<endl;
return ;
}
for(int i=front;i!=tail;i=(i+1)%size)
{
cout<<data[i]<<" ";
}
cout<<endl;
}
};
int main()
{
myqueue<double> q1(4);
q1.push(66);
q1.push(77);
q1.push(88);
q1.show();
q1.pop();
q1.push(99);
q1.show();
return 0;
}
思维导图
![](https://i-blog.csdnimg.cn/direct/ba0d7a2d81a541e494359940dd8edd14.png)