【LeetCode】Evaluate Reverse Polish Notation(逆波兰表达式求值) -(Linkedin) Medium ++

本文介绍了一种计算逆波兰表达式的方法,通过使用栈来处理运算符和操作数,实现对表达式的有效解析。提供了Java和C++两种语言的具体实现案例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Evaluate Reverse Polish Notation

Evaluate the value of an arithmetic expression in Reverse Polish Notation.

Valid operators are +, -, *, /. Each operand may be an integer or another expression.

Example
[“2”, “1”, “+”, “3”, ““] -> ((2 + 1) 3) -> 9
[“4”, “13”, “5”, “/”, “+”] -> (4 + (13 / 5)) -> 6

【分析】
计算逆波兰表达式:
如第2例:凡不是运算符者——压栈,遇到运算符,如“/”,将从栈顶起2个元素弹栈,计算13/5 = 2,再将结果2压栈。又碰到“+”,将栈顶2个元素(2,4)弹出,计算2+4=6,再将6压栈。此时走到底了,最后,返回栈中唯一的栈顶元素6,即为运算结果。
注意!!!是 b/ab-a!!!!
(1)Java

import java.util.Stack;

public class Solution {
    public static int ReversePolishNation(String[] tokens) {
        Stack<Integer> s = new Stack<Integer>();
        String operators = "+-*/";
        for(String token : tokens){
            if(!operators.contains(token)){//若非运算符,则压栈
                s.push(Integer.valueOf(token));
                continue;
            }
            int a = s.pop();
            int b = s.pop();
            if(token.equals("+") )
                s.push(a+b);
            else if(token.equals("-"))
                s.push(b-a);
            else if(token.equals("*"))
                s.push(a*b);
            else // if(token.equals("/"))
                s.push(b/a);
        }
        return s.pop();
    }
    public static void main(String[] args){
        String tokens[] = {"2", "1", "+", "3", "*"};
        int answer = ReversePolishNation(tokens);
        System.out.println(answer);
    }
}

(2)C++

#include "stdafx.h"
#include <iostream>
#include <stack>

using namespace std;

bool IsOperator(const char* token) {
    if (token[0] == '+' || token[0] == '-' || token[0] == '*' || token[0] == '/') {
        return true;
    }
    return false;
}
int ReversePolishNation(const char* str[],int size) {
    stack<int> s;
    const char* token;
    int a, b;
    for (int i = 0; i < size; i++) {
        token = str[i];
        if (!IsOperator(token)) {//若不是运算符,则压入栈中
            s.push(atoi(token));//atoi:array to integer
        }
        else {//若是运算符,则将栈中弹出2元素,将运算结果再压栈
            a = s.top();
            s.pop();
            b = s.top();
            s.pop();

            if (token[0] == '+')
                s.push(a + b);
            else if (token[0] == '-')
                s.push(b - a);
            else if (token[0] == '*')
                s.push(a * b);
            else    // if (token[0] == '/')
                s.push(b / a);

        }
    }

    return s.top();
}

int main()
{
    const char* str[] = {"2","1","+","3","*"};
    int size = sizeof(str) / sizeof(const char*);//size的求值 不可以放在函数中!(见上一篇:数组指针)
    cout << size << endl;
    int value = ReversePolishNation(str, size);
    cout << value << endl;

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值