1. 使用数组模拟(摘自OI Wiki):
int st[N];
// 这里使用 st[0] (即 *st) 代表栈中元素数量,同时也是栈顶下标
// 压栈 :
st[++*st] = var1;
// 取栈顶 :
int u = st[*st];
// 弹栈 :注意越界问题, *st == 0 时不能继续弹出
if (*st) --*st;
// 清空栈
*st = 0;封装
template<typename T>
struct Stack{
int tp;
T st[maxn];
inline T &operator [](const int x){
return st[x];
}
inline bool empty()const{
return !tp;
}
inline void clear(){
tp=0;
}
inline int size(){
return tp;
}
inline void push(const T x){
st[++tp]=x;
}
inline bool pop(){
if(!tp) return 0;
tp--;
return 1;
}
inline T top(){
return st[tp];
}
};2.STL中的栈
- 头文件:<stack>
- 定义:stack<类型> 栈名;
- 函数:
top()返回栈顶,
push(x):推入 x ,
pop()弹出栈顶,
empty()返回是否为空,
size()返回元素数量
思路
如题目描述。
代码
#include<iostream>
#define int unsigned long long //不开 ull 见祖宗
using namespace std;
const int N=1e6+010;
int st[N],tot;
int n;
signed main(){
ios::sync_with_stdio(false);
cin.tie(0),cout.tie(0);
int t;
cin>>t;
while(t--){
tot=0; //多测清空
cin>>n;
string str;
while(n--){
cin>>str;
if(str=="push"){
int x;
cin>>x;
st[++tot]=x;
}
else if(str=="pop"){
if(!tot) cout<<"Empty\n";
else tot--;
}
else if(str=="query"){
if(!tot) cout<<"Anguei!\n";
else cout<<st[tot]<<'\n';
}
else cout<<tot<<'\n';
}
}
return 0;
}思路
定义两个栈,输入数则存入数栈,输入符号则去除数栈最上方两个元素运算后再存回去。
代码
#include<iostream>
#include<cstdio>
#include<stack>
#define int long long
using namespace std;
const int maxn=5e5+010;
stack<int> st;
int n,ans;
signed main(){
int x=0;
char ch=getchar();
while(ch!='@'){
if(isdigit(ch)) x=(x<<1)+(x<<3)+(ch^48);
else if(ch=='.'){
st.push(x);
x=0;
}
else if(ch=='+'){
int a,b;
a=st.top();
st.pop();
b=st.top();
st.pop();
st.push(a+b);
}
else if(ch=='-'){
int a,b;
a=st.top();
st.pop();
b=st.top();
st.pop();
st.push(b-a);
}
else if(ch=='*'){
int a,b;
a=st.top();
st.pop();
b=st.top();
st.pop();
st.push(b*a);
}
else if(ch=='/'){
int a,b;
a=st.top();
st.pop();
b=st.top();
st.pop();
st.push(b/a);
}
ch=getchar();
}
cout<<st.top();
return 0;
}插入元素
- 过程:对于将插入的元素 ,判断其与栈顶元素的大小关系,若满足条件则插入,否则弹出栈顶再判断直至满足。
- 代码:
while(!st.empty()&&st.top()<x)
st.pop();
st.push(x);思路
对于每个在插入第 个元素时弹出的元素,记录其结果为 。
代码
#include<iostream>
#include<cstdio>
#include<stack>
using namespace std;
const int maxn=3e6+010;
int n,ans[maxn];
stack<pair<int,int> > st;
int main(){
cin>>n;
for(int i=1;i<=n;i++){
int x;
cin>>x;
while(st.size()&&st.top().first<x){
ans[st.top().second]=i;
st.pop();
}
st.push(make_pair(x,i));
}
for(int i=1;i<=n;i++) cout<<ans[i]<<" ";
return 0;
}