栈与队列
什么是栈(Stack)
栈其实就是一种数据结构 - 先进后出(先入栈的数据后出来,最先入栈的数据会被压入栈底)
什么是队列(Queue)
只允许在一端进行插入数据操作,在另一端进行删除数据操作的特殊线性表,队列具有 - 先进先出。
数组模拟栈
用top表示栈顶所在的索引。初始时,top = -1。表示没有元素。
push x :栈顶所在索引往后移动一格,然后放入x。st[++top] = x。
pop : top 往前移动一格。top–。
empty :top 大于等于 0 栈非空,小于 0 栈空。top == -1 ? “YES” : “NO”
query : 返回栈顶元素。st[top]
#include <iostream>
#include <string.h>
using namespace std;
const int N=1e5+10;
int st[N];
int top=-1;
int n;
int main(){
scanf("%d",&n);
while(n--){
string s;
cin>>s;
if(s=="push"){
int a;
cin>>a;
st[++top]=a;
}
else if(s=="pop"){
top--;
}
else if(s=="empty"){
cout<<(top==-1?"YES":"NO")<<endl;
}
else if(s=="query") cout<<st[top]<<endl;
}
}
数组模拟数列
#include <iostream>
#include <string.h>
using namespace std;
const int N=1e5+10;
int qu[N];
int hh=0,tt=-1;
int m;
int main(){
scanf("%d",&m);
while(m--){
string s;
cin>>s;
if(s=="push"){
int a;
cin>>a;
qu[++tt]=a;
}
else if(s=="pop"){
hh++;
}
else if(s=="empty"){
if(tt>=hh) cout<<"NO"<<endl;
else cout<<"YES"<<endl;
}
else if(s=="query") cout<<qu[hh]<<endl;
}
单调栈
#include <iostream>
#include <stdio.h>
using namespace std;
const int N=1e5+10;
int st[N];
int tt=0;
int n;
int main(){
scanf("%d",&n);
while(n--){
int x;
scanf("%d",&x);
while(tt&&st[tt]>=x) tt--;
if(!tt) printf("-1 ");
else printf("%d ",st[tt]);
st[++tt]=x;
}
return 0;
}
单调队列
#include <iostream>
using namespace std;
const int N=1e6+10;
int a[N],q[N];
int main()
{
int n,k;
scanf("%d%d",&n,&k);
for(int i=0;i<n;i++)
scanf("%d",&a[i]);
int hh = 0, tt = -1;
for(int i=0;i<n;i++)
{
if(hh<=tt&&i-k+1>q[hh])hh++;
while(hh<=tt&&a[q[tt]]>=a[i])tt--;
q[++tt]=i;
if(i>=k-1)printf("%d ",a[q[hh]]);
}
puts("");
hh = 0, tt = -1;
for(int i=0;i<n;i++)
{
if(hh<=tt&&i-k+1>q[hh])hh++;
while(hh<=tt&&a[q[tt]]<=a[i])tt--;
q[++tt]=i;
if(i>=k-1)printf("%d ",a[q[hh]]);
}
puts("");
}