栈的特点是先进后出,编程时通常直接使用STL stack,或者自己手写栈。
STL stack:
- stack< Type > s
- push(item) 压栈
- top() 栈顶元素
- pop() 出栈
- size() 元素个数
- empty() 判断栈是否为空
手写栈:
struct mystack{
char a[N];
int t = 0; //指向栈顶位置
void push(char x){ a[++t] = x; }
char top() { return a[t]; }
void pop() { t--; }
int empty() { return t==0?1:0; }
}
单调栈:
单调栈是栈的一种经典应用,使用时保证了栈内元素的单调性,接下来以洛谷p2947(题目链接)为例来说明单调栈的简单应用。
#include<bits/stdc++.h>
#define N 3000000
using namespace std;
int n,h[N],ans[N];
stack<int> s;
int main()
{
scanf("%d",&n);
for(int i = 1; i <= n; i++) scanf("%d",&h[i]);
for(int i = n; i >= 1; i--)
{
while(!s.empty() && h[s.top()] <= h[i]) s.pop();
if(s.empty()) ans[i] = 0;
else ans[i] = s.top();
s.push(i);
}
for(int i = 1; i <= n; i++) printf("%d\n",ans[i]);
return 0;
}