本节,我们实现用数组模拟实现栈和队列,接下来,我们以题带知识点。
1.用数组模拟栈
实现一个栈,栈初始为空,支持四种操作:
push x
– 向栈顶插入一个数 x;
pop
– 从栈顶弹出一个数;
empty
– 判断栈是否为空;
query
– 查询栈顶元素。
现在要对栈进行 M 个操作,其中的每个操作 3 和操作 4 都要输出相应的结果。
输入格式
第一行包含整数 M,表示操作次数。
接下来 M 行,每行包含一个操作命令,操作命令为 push x,pop,empty,query 中的一种。
输出格式
对于每个 empty 和 query 操作都要输出一个查询结果,每个结果占一行。
其中,empty 操作的查询结果为 YES 或 NO,query 操作的查询结果为一个整数,表示栈顶元素的值。
数据范围
1≤M≤100000,
1≤x≤109
所有操作保证合法。
思路
下面我们定义一个数组arr,并且定义tt作为栈顶下标
- 插入操作 :
arr[++t]=x;
- 弹出操作 :
tt--;
- 判空操作 :
if(tt>0) not empty; else empty;
- 取栈顶元素:
arr[tt];
代码实现:
#include<iostream>
#include<string>
using namespace std;
const int N=100010;
int arr[N];
int tt;//栈顶下标
int m;//操作次数
int main()
{
cin>>m;
while(m--)
{
int x;//要插入的数
string op;//操作类型
cin>>op;
if(op=="push")
{
cin>>x;
arr[++tt]=x;
}
else if(op=="pop") tt--;
else if(op=="empty") cout<<(tt?"NO":"YES")<<endl;
else cout<<arr[tt]<<endl;;
}
return 0;
}
2.用数组模拟队列
实现一个队列,队列初始为空,支持四种操作:
push x
– 向队尾插入一个数 x;
pop
– 从队头弹出一个数;
empty
– 判断队列是否为空;
query
– 查询队头元素。
现在要对队列进行 M 个操作,其中的每个操作 3 和操作 4 都要输出相应的结果。
输入格式
第一行包含整数 M,表示操作次数。
接下来 M 行,每行包含一个操作命令,操作命令为 push x,pop,empty,query 中的一种。
输出格式
对于每个 empty 和 query 操作都要输出一个查询结果,每个结果占一行。
其中,empty 操作的查询结果为 YES 或 NO,query 操作的查询结果为一个整数,表示队头元素的值。
数据范围
1≤M≤100000,
1≤x≤109,
所有操作保证合法。
思路
下面我们定义一个数组arr,并且定义hh作为队头下标,tt作为队尾下标。
- 在队尾插入数据,在队头弹出元素
- 插入操作:
arr[++tt]=x;
- 弹出操作:hh++;
- 判空操作:
if(hh<=tt)not empty; else empty;
- 取队头元素:
arr[hh];
代码实现:
#include<iostream>
using namespace std;
const int N=100010;
int arr[N],hh,tt=-1;
int m;
int main()
{
cin>>m;
while(m--)
{
int x;
string op;
cin>>op;
if(op=="push")
{
cin>>x;
arr[++tt]=x;
}
else if(op=="pop") hh++;
else if(op=="empty") cout<<((hh<=tt)?"NO":"YES")<<endl;
else cout<<arr[hh]<<endl;
}
return 0;
}