模拟栈与队列


栈与队列均没有 begin,end等操作


模拟栈
栈(先进后出)

//栈
#include<iostream>
#include<stack>

using namespace std;

int main()
{
	stack<int> stk; 
	stk.push(9);
	stk.push(6);
	stk.push(3);//向栈中插入元素
	
	stk.pop(); //弹出栈顶元素,类似于删除
	cout<<stk.top()<<endl; //返回值为栈顶元素 
	cout<<stk.empty(); //判断是否为空
	return 0;
}
使用数组模拟栈
//通过数组模拟栈我们可以直接访问到栈中的元素
例题  https://www.acwing.com/problem/content/description/830/
#include<iostream>
#include<string>

using namespace std;

const int N=100010;
int stk[N];
int tt;//栈顶,数组的尾部

int main()
{
    int n;
    cin>>n;
    while(n--)
    {
        string ss;
        int x;
        cin>>ss;
        if(ss=="push")//插入
        {
            cin>>x;
            stk[++tt]=x;
        }else if(ss=="pop")//弹出
        {
            tt--;
        }else if(ss=="empty")//是否为空
        {
            if(tt>0) cout<<"NO"<<endl;
            else cout<<"YEs"<<endl;
        }else if(ss=="query")//栈顶
        {
            cout<<stk[tt]<<endl;
        }
    }
    return 0;
}
单调栈
https://www.acwing.com/problem/content/description/832/
#include<iostream>
#include<stack>

using namespace std;

const int N=100010;
int stk[N];
int tt;

int main()
{
    int n;
    int x;
   // stack<int> stk;
    cin>>n;
    for(int i=1;i<=n;i++)
    {
        cin>>x;
        while(tt&&stk[tt]>=x) tt--;//数据结构中的stack无法直接指向元素
        if(tt) cout<<stk[tt]<<" ";
        else cout<<-1<<" ";
        stk[++tt]=x; 
    }
    return 0;
}


队列模拟队列
队列(先进先出)

#include<iostream>
#include<queue>

using namespace std;

int main()
{
	queue<int> q;
	q.push(9);
	q.push(7);
	q.push(6);
	q.push(3);
	cout<<q.back()<<endl;//队尾 
	cout<<q.front()<<endl;//队头 
	q.emplace();//判断是否为空
	q.pop();//删除队头元素
	cout<<q.front()<<endl; 
	return 0;
}
模拟队列
 https://www.acwing.com/problem/content/831/
#include<iostream>
#include<string>

using namespace std;
const int N=100010;
int que[N];
int hh,tt;
//hh 表示队头
//tt 表示队尾
int main()
{
    int n;
    cin>>n;
    hh=1;
    while(n--)
    {
        string ss;
        int x;
        cin>>ss;
        if(ss=="push")//插入元素
        {
            cin>>x;
            que[++tt]=x;
        }else if(ss=="pop")//删除元素
        {
            if(que[hh]==0) continue;
            hh++;
        }else if(ss=="empty")//判断队列是否为空
        {
            if(tt>=hh) cout<<"NO"<<endl;
            else cout<<"YES"<<endl;
        }else 
        {
            cout<<que[hh]<<endl;
        }
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值