逆波兰表达式计算

题目:
Evaluate the value of an arithmetic expression in Reverse Polish Notation. Valid operators are+,-,*,/. Each operand may be an integer or another expression.
Some examples:

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

思路:
利用栈来模拟计算。遇到操作数直接压栈,碰到操作符直接取栈顶的2个操作数进行计算(注意取出来的第一个操作数是右操作数,第二个操作数是左操作数),然后再把计算结果压栈,如此循环下去。最后栈中剩下的唯一的一个元素便是整个表达式的值。

代码:

int evalRPN(vector<string> &tokens)
{
    int result = 0;
    stack<int> stack;
    for(int i = 0; i < tokens.size(); i++)
    {
        if(tokens[i] == "*")
        {
            int rdata = stack.top();
            stack.pop();
            int ldata = stack.top();
            stack.pop();
            result = ldata * rdata;
            stack.push(result);
        }
        else if(tokens[i] == "/")
        {
            int rdata = stack.top();
            stack.pop();
            int ldata = stack.top();
            stack.pop();
            result = ldata / rdata;
            stack.push(result);
        }
        else if(tokens[i] == "+")
        {
            int rdata = stack.top();
            stack.pop();
            int ldata = stack.top();
            stack.pop();
            result = ldata + rdata;
            stack.push(result);
        }
        else if(tokens[i] == "-")
        {
            int rdata = stack.top();
            stack.pop();
            int ldata = stack.top();
            stack.pop();
            result = ldata - rdata;
            stack.push(result);
        }
        else
        {
            //如果取出的是操作数,则将string类型转换char类型,再转换为int类型
            int data = 0;
            for(int j = 0; j < tokens[i].size(); j++)
            {
                data = data * 10 + (tokens[i][j] - '0');
            }
            stack.push(data);
        }
    }
    return stack.top();
}

你可能感兴趣的:(逆波兰表达式计算)