简体   繁体   English

了解后缀表达式评估代码

[英]Understanding postfix expression evaluation code

I am trying to understand this piece of code. 我正在尝试理解这段代码。 What it does it postfix expression evaluation. 后缀表达式评估的作用。 I am having problems understanding the code. 我在理解代码时遇到问题。 I will be very thankful if anyone can help me out. 如果有人可以帮助我,我将非常感激。

#include <iostream>
#include <cstring>
#include <stack>
using namespace std;
int main()
{


    //suppose a contains the string..
    //n is the length of string...
    char a[10]="A+B/C";
    int n = strlen(a)
    stack<int>s;
    for (int i=0;i<n;i++)
    {
        if (a[i]=='+')
        {
            s.push(s.pop()+s.pop());
            int temp1 = s.top();
            s.pop();
            int temp2 = s.top();
            s.pop();
            s.push(temp1 * temp2);
        }
        if (a[i]=='*')
            s.push(s.pop() * s.pop());

        if ((a[i]>='0') && (a[i]<='9'))
            s.push(0);
        while ((a[i]>='0') && (a[i]<='9'))
            s.push(10*s.pop()+(a[i++]-'0'));
    }

    cout<<s.pop()<<endl;

    return 0;
}

Thanks in advance. 提前致谢。

This site looks to be a good resource on what's happening here, but the expression should use numbers, not letters. 该站点似乎是此处发生情况的良好资源,但该表达式应使用数字,而不是字母。

Say you have the infix expression 1+2*3-4*5. 假设您有中缀表达式1 + 2 * 3-4 * 5。 The corresponding postfix would be 123*+45*-. 相应的后缀为123 * + 45 *-。 First, you start by scanning the string from left to right. 首先,首先从左到右扫描字符串。 The first three numbers are operands so they will be stored on the stack in the order 1 (bottom), 2 (middle), 3 (top). 前三个数字是操作数,因此它们将以顺序1(底部),2(中间),3(顶部)存储在堆栈中。 Next, there is a * operator. 接下来,有一个*运算符。 To deal with this, pop the first two operands off of the stack and multiply them (the first one popped is the right operand and the second is the left). 要解决此问题,请从堆栈中弹出前两个操作数,然后将它们相乘(弹出的第一个是右侧的操作数,第二个是左侧的操作数)。 This will evaluate to 2*3=6, and 6 will be stored on the stack, making it 1, 6. 这将得出2 * 3 = 6,并且6将存储在堆栈中,从而使其成为1、6。

Next, there is a + operator. 接下来,有一个+运算符。 1 and 6 are popped and added and 7 is stored on the stack. 弹出并添加1和6,将7存储在堆栈中。 After this, 4 and 5 are pushed on the stack as well (7, 4, 5). 之后,将4和5也推入堆栈(7、4、5)。 The next character is another * operator, so it evaluates 4*5=20 and pushes 20 onto the stack (7, 20). 下一个字符是另一个*运算符,因此它求值4 * 5 = 20并将20压入堆栈(7,20)。

Finally, there is a - operator. 最后,有一个-运算符。 7 and 20 are popped and evaluated as 7-20=(-13). 弹出7和20,并将其评估为7-20 =(-13)。 This is pushed onto the stack and is ready to be popped as your final answer. 它被压入堆栈,可以作为最终答案弹出。

Hope that helps clear up any confusion (assuming I read your question correctly). 希望这有助于消除任何混乱(假设我正确阅读了您的问题)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM