19009 后缀表达式

思路

  1. **输入处理**:读取输入的后缀表达式,去掉末尾的`@`符号。

  2. **使用栈计算后缀表达式**:

  • 遍历表达式中的每个字符。

  • 如果是数字,压入栈中。

  • 如果是运算符,从栈中弹出两个数字进行运算,并将结果压入栈中。

  1. **输出结果**:栈中最后剩下的数字即为表达式的结果。

伪代码

```

function evaluate_postfix(expression):

stack = []

for token in expression.split():

if token is a digit:

stack.push(int(token))

else if token is an operator:

b = stack.pop()

a = stack.pop()

result = perform_operation(a, b, token)

stack.push(result)

return stack.pop()

function perform_operation(a, b, operator):

if operator == '+':

return a + b

if operator == '-':

return a - b

if operator == '*':

return a * b

if operator == '/':

return a / b

function main():

while input is not EOF:

expression = read_input().strip('@')

result = evaluate_postfix(expression)

print(result)

```

C++代码

cpp 复制代码
#include <iostream>
#include <stack>
#include <sstream>
#include <string>

int main() {
    std::string input;
    std::getline(std::cin, input);

    std::stack<int> s;
    std::istringstream iss(input);
    std::string token;

    while (iss >> token) {
        if (token == "@") {
            break;
        } else if (isdigit(token[0])) {
            s.push(std::stoi(token));
        } else {
            for (char op : token) {
                if (op == '@') {
                    break;
                }
                int b = s.top(); s.pop();
                int a = s.top(); s.pop();
                if (op == '+') {
                    s.push(a + b);
                } else if (op == '-') {
                    s.push(a - b);
                } else if (op == '*') {
                    s.push(a * b);
                } else if (op == '/') {
                    s.push(a / b);
                }
            }
        }
    }

    std::cout << s.top() << std::endl;
    return 0;
}

总结

  1. **输入处理**:读取并去掉末尾的`@`符号。

  2. **使用栈计算后缀表达式**:遍历表达式,数字压栈,运算符弹出两个数字计算并压栈。

  3. **输出结果**:栈中最后剩下的数字即为结果。

相关推荐
千里马-horse几秒前
Async++ 源码分析8--partitioner.h
开发语言·c++·async++·partitioner
格林威29 分钟前
常规线扫描镜头有哪些类型?能做什么?
人工智能·深度学习·数码相机·算法·计算机视觉·视觉检测·工业镜头
Lucis__1 小时前
再探类&对象——C++入门进阶
开发语言·c++
北京不会遇到西雅图2 小时前
【SLAM】【后端优化】不同优化方法对比
c++·机器人
jndingxin2 小时前
c++多线程(6)------ 条件变量
开发语言·c++
程序员莫小特2 小时前
老题新解|大整数加法
数据结构·c++·算法
小刘max3 小时前
深入理解队列(Queue):从原理到实践的完整指南
数据结构
过往入尘土4 小时前
服务端与客户端的简单链接
人工智能·python·算法·pycharm·大模型
zycoder.4 小时前
力扣面试经典150题day1第一题(lc88),第二题(lc27)
算法·leetcode·面试
蒙奇D索大4 小时前
【数据结构】考研数据结构核心考点:二叉排序树(BST)全方位详解与代码实现
数据结构·笔记·学习·考研·算法·改行学it