概念:
“先进后出”,只有一个出入口
编程中的递归就是用栈来实现的
通常使用STL中的stack或者手写栈
成员函数:
empty() //堆栈为空则返回真
pop() //移除栈顶元素
push() //在栈顶增加元素
size() //返回栈中元素数目
top() //返回栈顶元素
clear() //清空栈内元素
先上模板
模板:
struct Stack{
int data[N]={0},len=0;
void pop(){
len--;
}
void push(int e){
data[++len]=e;
}
int top(){
return data[len];
}
bool empty(){
return len==0;
}
int size(){
return len;
}
void clear(){
len=0;
}
};
这里就不用vector写了
毕竟STL库中有stack,几乎不用手写
这里就是供初学者学习
模板题:
洛谷:B3614 【模板】栈 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)
代码:
/*---code---*/
const int N = 1e6 + 5;
using ull=unsigned long long;
struct Stack{
ull data[N]={0},len=0;
void pop(){
len--;
}
void push(ull e){
data[++len]=e;
}
ull top(){
return data[len];
}
bool empty(){
return len==0;
}
ull size(){
return len;
}
void clear(){
len=0;
}
};
Stack st;
int q;
void solve(){
st.clear();
cin>>q;
while(q--){
string op;ull x;
cin>>op;
if(op=="push")cin>>x,st.push(x);
if(op=="query"){
if(st.empty())cout<<"Anguei!\n";
else cout<<st.top()<<"\n";
}
if(op=="pop"){
if(st.empty())cout<<"Empty\n";
else st.pop();
}
if(op=="size")cout<<st.size()<<"\n";
}
}
/*---main---*/
int main() {
ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
// freopen("a.txt","r",stdin);
// freopen("cout.txt","w",stdout);
int T = 1;
cin >> T;
while(T--)
solve();
return 0;
}
PAT:这里非常注意的是给的数据范围是0<x<2^64 这里就要使用unsigned long long