数组模拟栈和队列
https://www.acwing.com/problem/content/830/
https://www.acwing.com/problem/content/831/
相比数组模拟链表要简单的多,要注意的是tt的初始值,看个人习惯设置,栈一般为0,队列一般为1
//栈
#include<iostream>
using namespace std;
const int N = 100010;
int stk[N],tt;//栈值和栈顶指针,栈顶指针时刻指向栈顶元素下表
int m;
//插入
//stk[++t]=x
//删除
//tt--即可
//判空
//tt从1开始有值,tt<1时即空
//栈顶元素
//stk[tt]
void add(int x)
{
stk[++tt]=x;//下标从1开始数
}
void remove()
{
tt--;
}
void empty()
{
if(tt>0)cout << "NO" << endl;
else cout << "YES" << endl;
}
void query()
{
cout << stk[tt] << endl;
}
int main()
{
cin >> m;
while(m--)
{
string op;
cin >> op;
if(op == "push")
{
int x;
cin >> x;
add(x);
}
else if(op == "pop")
{
remove();
}
else if(op == "empty")
{
empty();
}
else//qeury
{
query();
}
}
}
//队列
#include<iostream>
using namespace std;
const int N = 100010;
//在队尾插入元素,在队头弹出元素
int q[N],hh,tt=-1;//q表示队值,hh对头,tt队尾
int m;
//插入
//q[++tt]=x;
//弹出
//hh++;
//判空
//if(hh<=tt)not empty
//else empty
//队头队尾元素
//q[hh];
//q[tt];
void add(int x)
{
q[++tt]=x;//下标从0开始数
}
void remove()
{
hh++;
}
void empty()
{
if(hh<=tt)cout << "NO" << endl;
else cout << "YES" << endl;
}
void query()
{
cout << q[hh] << endl;
}
int main()
{
cin >> m;
while(m--)
{
string op;
cin >> op;
if(op == "push")
{
int x;
cin >> x;
add(x);
}
else if(op == "pop")
{
remove();
}
else if(op == "empty")
{
empty();
}
else//qeury
{
query();
}
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!