11.3号算法总结

模拟栈

模拟栈
push x :栈顶所在索引往后移动一格,然后放入x。st[++top] = x。
pop : top 往前移动一格。top–。
empty :top 大于等于 0 栈非空,小于 0 栈空。top == -1 ? “YES” : “NO”
实现初始化top=-1对栈进行初始化,表示空
实现压栈和出栈压栈 需要++top 然后读入即可 stk[++top]=x,出栈 只需 --top

#include <iostream>
using namespace std;
const int N = 100010;
int st[N];
int top = -1;
int n;
int main()
{
   
    cin >> n;
    while(n--)
    {
   
        string s;
        cin >> s;

        //栈顶所在索引往后移动一格,然后放入x。
        if(s == "push")
        {
   
            int a;
            cin >> a;
            st[++top] = a;
        }

        //往前移动一格
        if(s == "pop")
        {
   
            top --;
        }
        //返回栈顶元素
        if(s == "query")
        {
   
            cout << st[top] << endl;
        }
        //大于等于 0 栈非空,小于 0 栈空
        if(s == "empty")
        {
   
            cout << (top == -1 ? "YES" : "NO") << endl;
        }
    }
}

单调栈

在这里插入图片描述

#include <iostream>
using namespace std;
const int N = 100010;
int stk[N], tt;

int main()
{
   
    int n;
    cin >> n;
    while (n -- )
    {
   
        int x;
        scanf("%d", &x);
        while (tt && stk[tt] >= x) tt -- ;//如果栈顶元素大于当前待入栈元素,则出栈
        if (!tt) printf("-1 ");//如果栈空,则没有比该元素小的值。
        else printf("%d ", stk[tt]);//栈顶元素就是左侧第一个比它小的元素。
        stk[ ++ tt] = x;
    }
    return 0;
}

使用c++stl的代码,全程引用大佬

#include<iostream>
#include<vector>
using namespace std;
int main() {
   
    int n,x;
    cin >> n;
    vector<int> t;
    while (n--) {
   
        cin >> x;
        while (t.size() > 0 and t.back() >= x) {
   
            t.pop_back();
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一直爱莲子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值