cpp手动实现顺序栈,要求实现数据结构中,所有栈的相关操作
main.cpp
#include <iostream>
using namespace std;
template<typename T>
class Stack{
private:
int maxSize=0; // 栈的最大容量
T* data;//数据域
public:
int top=-1;//栈顶
Stack(){ //无参构造
}
Stack(int size);//有参构造的声明
~Stack(){
delete []data;
}//析构函数
void show();//展示函数的申明
int push(T d);//入栈申明
int pop();//出栈申明
int getsize();//获取容量
int getlen();//获取长度
};
template<typename T>
Stack<T>::Stack(int size){
//有参
data=new T[size];//申请空间
maxSize=size;
top=-1;//栈顶设置为-1
}
template<typename T>
//遍历
void Stack<T>::show(){
cout<<"top="<<top<<endl;
for (int i = 0; i <= top; ++i) {
cout<<"data="<<data[i]<<"\ti="<<i<<endl;//遍历栈数据
}
}
template<typename T>
//入栈函数
int Stack<T>::push(T d){
//判满
if(maxSize-1==top){
cout<<"栈满"<<endl;
return -1;
}
//入栈,先加后压
data[++top]=d;
cout<<data[top]<<"已入栈"<<endl;
return 0;
}
//出栈函数
template<typename T>
int Stack<T>::pop(){
//判空
if(-1==top){
cout<<"栈空"<<endl;
return -1;
}
//出栈,先弹后减
cout<<data[top--]<<"已出栈"<<endl;
return 0;
}
//获取容量
template<typename T>
int Stack<T>::getsize(){
return maxSize;
}
//获取长度
template<typename T>
int Stack<T>::getlen(){
return top+1;
}
int main()
{
Stack<int> s1(3);//初始化,插入第一个值为10
s1.push(1);//入栈
s1.pop();//出栈
s1.pop();//出栈
s1.push(4);//入栈
s1.push(5);//入栈
s1.push(6);//入栈
s1.push(7);//入栈
s1.show();
cout<<"============================"<<endl;
cout<<"容量="<<s1.getlen()<<"长度="<<s1.getlen()<<endl;
Stack<double> s2(20);//初始化,插入第一个值为10
s2.push(1.2);//入栈
s2.push(2.9);//入栈
s2.pop();//出栈
s2.pop();//出栈
s2.push(4.3);//入栈
s2.push(5.8);//入栈
s2.show();
cout<<"============================"<<endl;
cout<<"容量="<<s2.getsize()<<"长度="<<s2.getlen()<<endl;
return 0;
}