第八章:单调栈与单调队列
一、数组模拟栈
1、逻辑结构:
2、物理结构:
3、接口函数:
(1)提前准备:
const int N=100010;
int stk[N],top;
(2)初始化:
void init()
{
top=0;
}
(3)插入:
void insert(int k)
{
stk[++top]=k;
}
我们这里默认stk[0]处不存储数据,这样当top等于0的时候,说明栈为空,而0恰好是假的意思,所以这样写便于判断栈是否为空。
(4)删除:
void remove()
{
top--;
}
(5)访问栈顶:
int top()
{
return stk[top];
}
(6)判断是否为空:
bool empty()
{
if(top)return false;
else return true;
}
4、例题:
#include<iostream>
using namespace std;
const int N=100010;
int stk[N],top=0;
int main()
{
int n;
scanf("%d",&n);
while(n--)
{
string op;
cin>>op;
if(op=="push")
{
int x;
scanf("%d",&x);
stk[++top]=x;
}
else if(op=="pop")
{
top--;
}
else if(op=="empty")
{
cout<<(top?"NO":"YES")<<endl;
}
else
{
cout<<stk[top]<<endl;
}
}
return 0;
}
二、数组模拟队列
1、逻辑结构:
2、物理结构:
3、接口函数:
(1)前期准备
const int N=100010;
int q[N],hh,tt;
(2)初始化
void init()
{
tt=-1;
hh=0;
}
(3)插入
void insert(int x)
{
q[++tt]=x;
}
(4)删除
void remove()
{
hh++;
}
(5)查看队尾
int back()
{
return q[tt];
}
(6)查看队头
int front()
{
return q[hh];
}
(7)判断是否为空
bool empty()
{
if(hh<=tt)return false;
else true;
}
4、例题:
#include<iostream>
using namespace std;
const int N=100010;
int m;
int q[N],head,tail=-1;
int main()
{
cin>>m;
while(m--)
{
string op;
int x;
cin>>op;
if(op=="push")
{
cin>>x;
q[++tail]=x;
}
else if(op=="pop")head++;
else if(op=="empty")
{
cout<<(head<=tail?"NO":"YES")<<endl;
}
else
{
cout<<q[head]<<endl;
}
}
return 0;
}