数据结构与算法学习笔记----栈

数据结构与算法学习笔记----栈

@@ author: 明月清了个风

@@ last edited: 2024.11.21

挖坑待填

  • 后缀表达式求值过程

Acwing 828. 模拟栈

实现一个栈,栈初始为空,支持四种操作:

  1. push x向栈顶插入一个数x
  2. pop从栈顶弹出一个数;
  3. empty判断栈是否为空
  4. query查询栈顶元素

现在要对该链表进行MMM次操作,其中的每个操作3和操作4都要输出相应的结果

输入格式

第一行包含整数MMM,表示操作次数。

接下来MMM行,每行包含一个操作指令。

输出格式

对于每个queryempty操作都要输出一个查询结果,每个结果占一行。

其中,empty操作的查询结果为YESNOquery操作的查询结果为一个整数,表示栈顶元素。

数据范围

1≤M≤1051 \leq M \leq 10^{5}1M105,

1≤x≤1091 \leq x \leq 10^{9}1x109

代码

#include <iostream>

using namespace std;

const int N = 100010;

int stk[N], tt;

int main()
{
    int n;
    cin >> n;
    
    while(n --)
    {
        string op;
        int x;
        cin >> op;
        if(op == "push")
        {
            cin >> x;
            stk[++ tt] = x;
        }
        else if(op == "pop") tt --;
        else if(op == "empty") cout << (tt ? "NO" : "YES") <<endl;
        else cout << stk[tt] << endl;
    }
    
    return 0;
}

Acwing 3302. 表达式求值

给定一个表达式,其中运算符仅包含+,-,*,/,可能包含括号,请你求出表达式的最终值。

注意

  • 数据保证给定的表达式合法
  • 题目保证符号-只作为减号出现,不会作为负号出现。
  • 题目保证表达式中所有数字均为正整数。
  • 题目保证表达式在中间计算过程以及结果中,均不超过231−12^{31} - 12311
  • 题目中的整除是指向0取整,也就是对于大于0的啥结果向下取整,如5/3=15/3 = 15/3=1,对于小于0的结果向上取整,例如5/(1−4)=−15/(1-4)=-15/(14)=1

输入格式

共一行,为给定表达式。

输出格式

共一行,为表达式的结果。

数据范围

表达式的长度不超过10510^{5}105

代码

#include <iostream>
#include <cstring>
#include <stack>
#include <unordered_map>
#include <algorithm>

using namespace std;

stack<int> num;
stack<char> op;

void eval()
{
    int a = num.top(); num.pop();
    int b = num.top(); num.pop();
    char c = op.top(); op.pop();
    
    int x;
    if(c == '+') x = a + b;
    else if(c == '-') x = b - a;
    else if(c == '*') x = b * a;
    else x = b / a;
    
    num.push(x);
}

int main()
{
    unordered_map<char, int> pr{{'+', 1}, {'-', 1}, {'*', 2}, {'/', 2}};
    string str;
    cin >> str;
    
    for(int i = 0; i < str.size(); i ++)
    {
        auto t = str[i];
        if(isdigit(t))
        {
            int x = 0, j = i;
            while(j < str.size() && isdigit(str[j]))
                x = x * 10 + str[j ++] - '0';
            i = j - 1;
            num.push(x);
        }
        else if(t == '(') op.push(t);
        else if(t == ')')
        {
            while(op.top() != '(') eval();
            op.pop();
        }
        else 
        {
            while(op.size() && op.top() != '(' && pr[op.top()] >= pr[t]) eval();
            op.push(t);
        }
    }
    
    while(op.size()) eval();
    cout << num.top() << endl;
    
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值