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. **输出结果**:栈中最后剩下的数字即为结果。

相关推荐
积极向上的向日葵6 分钟前
有效的括号题解
数据结构·算法·
GIS小天12 分钟前
AI+预测3D新模型百十个定位预测+胆码预测+去和尾2025年6月7日第101弹
人工智能·算法·机器学习·彩票
_Itachi__33 分钟前
LeetCode 热题 100 74. 搜索二维矩阵
算法·leetcode·矩阵
不忘不弃33 分钟前
计算矩阵A和B的乘积
线性代数·算法·矩阵
不爱写代码的玉子37 分钟前
HALCON透视矩阵
人工智能·深度学习·线性代数·算法·计算机视觉·矩阵·c#
Java 技术轻分享43 分钟前
《树数据结构解析:核心概念、类型特性、应用场景及选择策略》
数据结构·算法·二叉树··都差速
虚拟之1 小时前
36、stringstream
c++
我很好我还能学1 小时前
【面试篇 9】c++生成可执行文件的四个步骤、悬挂指针、define和const区别、c++定义和声明、将引用作为返回值的好处、类的四个缺省函数
开发语言·c++
芜湖xin1 小时前
【题解-洛谷】P1706 全排列问题
算法·dfs
chao_7892 小时前
链表题解——两两交换链表中的节点【LeetCode】
数据结构·python·leetcode·链表