前缀,后缀表达式求值

前缀表达式

从右至左扫描表达式,遇到数字时,将数字压入堆栈,遇到运算符时,弹出栈顶的两个数,用运算符对它们做相应的计算(栈顶元素 op 次顶元素),并将结果入栈;重复上述过程直到表达式最左端,最后运算得出的值即为表达式的结果

从右至左,遇数压1,遇符弹2,再来计算。

后缀表达式

从左至右扫描表达式,遇到数字时,将数字压入堆栈,遇到运算符时,弹出栈顶的两个数,用运算符对它们做相应的计算(栈顶元素 op 次顶元素),并将结果入栈;重复上述过程直到表达式最左端,最后运算得出的值即为表达式的结果

从左至右,遇数压1,遇符弹2,再来计算。

例题

https://www.luogu.org/problem/P1449

#include <iostream>
#include <algorithm>
#include <cstdio>
using namespace std;
int a[1005],p,top,t;
char c;

int main()
{
    while(c=getchar())
    {
        if(c=='@')
            break;
        if(isdigit(c)) t=t*10+c-'0';
        if(c=='.')
        {
            a[++top]=t;
            t=0;
        }
        if(c=='+')
        {
            a[top-1]=a[top]+a[top-1];
            top--;
        }
        if(c=='-')
        {
            a[top-1]=a[top-1]-a[top];
            top--;
        }
        if(c=='*')
        {
            a[top-1]=a[top]*a[top-1];
            top--;
        }
        if(c=='/')
        {
            a[top-1]=a[top-1]/a[top];
            top--;
        }
    }
    cout<<a[top];
    return 0;
}

注意事项:

1.有除法,并且就按c++里的整除运算

2.getchar()在cstdio里面

猜你喜欢

转载自www.cnblogs.com/huaruoji/p/11702800.html