PTA波兰表达式
一、题目描述

二、解题思路
弄个string的栈,把这些全部存进栈,然后从栈顶一直往下走,碰到两个数字和一个操作符就进行一次操作,再入栈就行。(注意除号和减号不要写反了,不然跟我一样调一个小时)
三、代码实现
1 #include "bits/stdc++.h" 2 #define PII pair<int,int> 3 #define rep(i,z,n) for(int i = z;i <= n; i++) 4 #define per(i,n,z) for(int i = n;i >= z; i--) 5 #define ll long long 6 #define db double 7 #define vi vector<int> 8 #define debug(x) cerr << "!!!" << x << endl; 9 using namespace std; 10 inline ll read() 11 { 12 ll s,r; 13 r = 1; 14 s = 0; 15 char ch = getchar(); 16 while(ch < '0' || ch > '9'){ 17 if(ch == '-') 18 r = -1; 19 ch = getchar(); 20 } 21 while(ch >= '0' && ch <= '9'){ 22 s = (s << 1) + (s << 3) + (ch ^ 48); 23 ch = getchar(); 24 } 25 return s * r; 26 } 27 inline void write(ll x) 28 { 29 if(x < 0) putchar('-'),x = -x; 30 if(x > 9) write(x / 10); 31 putchar(x % 10 + '0'); 32 } 33 stack <string> que; 34 stack <double> num; 35 stack <string> c; 36 int main() 37 { 38 string s; 39 string temp = ""; 40 getline(cin,s); 41 // reverse(s.begin(),s.end()); 42 // cout << s << endl 43 for(auto &u:s){ 44 if(u == ' '){ 45 que.push(temp); 46 temp = ""; 47 continue; 48 } 49 temp += u; 50 } 51 if(temp.size() != 0) 52 que.push(temp); 53 string code; 54 while(!que.empty()){ 55 string temp = que.top(); 56 que.pop(); 57 if(temp.size() == 1) 58 c.push(temp); 59 if(temp.size() > 1){ 60 double k = stod(temp); 61 num.push(k); 62 } 63 if(num.size() >= 2 && !c.empty()){ 64 double k; 65 code = c.top(); 66 c.pop(); 67 double val1 = num.top(); 68 num.pop(); 69 double val2 = num.top(); 70 num.pop(); 71 if(code == "+") 72 k = val1 + val2; 73 else if(code == "-") 74 k = val1 - val2; 75 else if(code == "*") 76 k = val1 * val2; 77 else 78 k = val1 / val2; 79 // cout << k << endl; 80 num.push(k); 81 } 82 } 83 cout << fixed << setprecision(6) << num.top() << endl; 84 return 0; 85 }
本文来自博客园,作者:{scanner},转载请注明原文链接:{https://home.cnblogs.com/u/scannerkk/}

浙公网安备 33010602011771号