版权声明:原创文章,转载请注明出处 https://blog.csdn.net/hza419763578/article/details/88416578
1.自己实现栈的clear,size,empty,pop,top
TOP本质上为·最大元素的下标,栈空时为-1
#include<iostream>
#include<stack>
using namespace std;
const int MAXSIZE=1000;
struct Stack{
int st[MAXSIZE];
int TOP;
Stack(){//初始栈空
TOP=-1;
}
void clear(){
TOP=-1;
}
int size(){
return TOP+1;
}
bool empty(){
if(TOP==-1) return true;
else return false;
}
void push(int x){
st[++TOP]=x;
}
void pop(){
TOP--;
}
int top(){
return st[TOP];
}
};
void empty(Stack s){
if(s.empty()){
cout<<"空\n";
}else{
cout<<"非空\n";
}
}
int main(){
Stack s;//默认int 不想写什么模板了
empty(s);
for(int i=1;i<=5;i++){
s.push(i*i);
}
empty(s);
cout<<"栈顶:"<<s.top()<<endl;
cout<<"长度:"<<s.size()<<endl;
s.pop();
cout<<"栈顶:"<<s.top()<<endl;
cout<<"长度:"<<s.size()<<endl;
s.clear();
empty(s);
cout<<"长度:"<<s.size()<<endl;
return 0;
}