板子
模拟栈
828. 模拟栈
#include <iostream>
using namespace std;
const int N = 1e5 + 10;
int n;
int stk[N], tt;
int main()
{
tt = -1;
cin >> n;
while(n -- )
{
string op;
int x;
cin >> op;
if(op == "push")
{
cin >> x;
stk[++ tt] = x;
} else if(op == "pop"){
tt --;
} else if(op == "query")
{
cout << stk[tt] << endl;
} else {
if(tt == -1) puts("YES");
else puts("NO");
}
}
return 0;
}
常见操作
tt = -1 || tt = 0
stk[++ tt] = x;
tt --;
stk[tt]
tt == -1
注意
- 模拟栈的时候,初始化不同,指针tt代表含义不同
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/735ded089fe73be0cf919337fa46188e.png)
应用
单调栈
830. 单调栈
#include <iostream>
using namespace std;
const int N = 1e5 + 10;
int n;
int a[N];
int stk[N], tt;
int main()
{
scanf("%d", &n);
for(int i = 0; i < n; i ++) scanf("%d", &a[i]);
tt = -1;
for(int i = 0; i < n; i ++)
{
while(stk[tt] >= a[i] && tt != -1) tt --;
if(tt == -1) printf("-1 ");
else printf("%d ", stk[tt]);
stk[ ++ tt] = a[i];
}
return 0;
}