Yale class

Today we learned about the stack. The stack is a kind of first-in, last-out, and the last-in-first-out diagram is as follows:

The teacher gave an example, the suffix expression:

Postfix notation is also called reverse Polish notation (the prefix is ​​Polish notation), and it is called postfix notation because all operators are after the operands.

The operator of infix notation is between the operands, which is also the most logical. The operator of the prefix notation is before the operand. Like the suffix notation, it is for the convenience of computer calculation, because there is no parenthesis in the suffix or prefix, and there is no problem of priority processing, and the stack is directly used for calculation.

Idea: Now perform the operation of the symbols behind the 2 numbers input at the beginning, and then perform the operation of the symbols behind the constants with the constants behind. . . . . . Finally output the last item of the array

The code is as follows (with comments):

#include <bits/stdc++.h>
using namespace std;
char c[1005];
int a[1005];
int main()
{
    int m;
    gets(c);//input
    int top=0;// top means The current highest value
    for(int i=0;i<strlen(c);i++){
        switch(c[i]){
            case ' ':break;//If there is no number, jump out of
            case '+':m=a[ top-1]+a[top];top--;a[top]=m;break;//If it is a plus sign, add the two numbers, top returns to the previous layer, and update the value of a[top] For a+b
            case '-':m=a[top-1]-a[top];top--;a[top]=m;break;//as above
            case '*':m=a[top- 1]*a[top];top--;a[top]=m;break;//as above
            case '/':m=a[top-1]/a[top];top--;a[top ]=m;break;//as above
            default a[++top]=c[i]-48;//If it is a constant item, add a layer to top, and a[top] is updated to the int value of c[i]
        }
    }
    cout<<a[top];//output
    return 0;
}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324956351&siteId=291194637