1 #include <iostream>
2 #include <string>
3 #include <map>
4 #include <stack>
5 #include <queue>
6
7
8
9
10
11 using namespace std;
12
13 struct node
14 {
15 double num; // 也可以改成 int 具体情况具体分析
16 char op; // 存储符号
17 bool flag; // true代表数字 false代表符号
18 };
19
20 string str;
21 stack s;
22 queue q;
23 map<char,int> m;
24
25 void Change() // 中缀表达式转换为后缀表达式
26 {
27 double num;
28 node temp;
29 for(int i=0;i<str.length();) { if(str[i]>='0' && str[i]<='9')
30 {
31 temp.flag = 1;
32 temp.num = str[i++] - '0';
33 while(i<str.length() && str[i]>='0' && str[i]<='9')
34 {
35 temp.num = temp.num*10 + (str[i]-'0');
36 ++i;
37 }
38 q.push(temp);
39 }
40 else if(str[i]==' ')
41 {
42 ++i;
43 }
44 else
45 {
46 temp.flag = 0;
47 while(!s.empty() && m[str[i]]<=m[s.top().op])
48 {
49 q.push(s.top());
50 s.pop();
51 }
52 temp.op = str[i];
53 s.push(temp);
54 ++i;
55 }
56 }
57 while(!s.empty()) //转换结束后栈为空,队列保存的是一个完整的后缀表达式
58 {
59 q.push(s.top());
60 s.pop();
61 }
62 }
63
64 double cal()
65 {
66 double temp1,temp2;
67 while(!q.empty()) //将队列遍历,最终结果保存在栈里
68 {
69 node head = q.front();
70 q.pop();
71 if(head.flag == 1)
72 {
73 s.push(head);
74 }
75 else if(head.flag == 0)
76 {
77 node b = s.top(); //第一次弹出的是第二操作数
78 s.pop();
79 node a = s.top(); //第二次弹出的是第一操作数
80 s.pop();
81 node c;
82 c.flag = 1;
83 if(head.op == '+')
84 {
85 c.num = a.num + b.num;
86 }
87 else if(head.op == '-')
88 {
89 c.num = a.num - b.num;
90 }
91 else if(head.op == '*')
92 {
93 c.num = a.num * b.num;
94 }
95 else if(head.op == '/') //有可能出现除以零的非法,要特判,不过这里没写
96 {
97 c.num = a.num / b.num;
98 }
99 s.push(c);
100 }
101 }
102 return s.top().num;
103 }
104
105 int main()
106 {
107 m['+'] = m['-'] = 0; //设置优先级
108 m['*'] = m['/'] = 1;
109 getline(cin,str);
110 Change();
111 cout << cal() << endl;
112 return 0;
113 }