前綴表達式
從右至左掃描表達式,遇到數字時,將數字壓入堆棧,遇到運算符時,彈出棧頂的兩個數,用運算符對它們做相應的計算(棧頂元素 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里面