forked from huangmingchuan/Cpp_Primer_Answers
-
Notifications
You must be signed in to change notification settings - Fork 0
/
exercise9_52.cpp
54 lines (49 loc) · 824 Bytes
/
exercise9_52.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include <iostream>
#include <string>
#include <stack>
#include <cctype>
using namespace std;
string calc(string l, string r, string op)
{
string s;
if (op == "-")
s = to_string(stoi(l) - stoi(r));
return s;
}
int main()
{
string s("1+2*(7-4)");
stack<string> stack;
for (auto iter = s.begin(); iter != s.end();)
{
if (*iter == '(')
{
stack.push(string(1, *iter));
++iter;
while (*iter != ')')
{
stack.push(string(1, *iter));
++iter;
}
}
else if (*iter == ')')
{
string r = stack.top(); stack.pop();
string op = stack.top(); stack.pop();
string l = stack.top(); stack.pop();
stack.pop(); // '(' 弹出
stack.push(calc(l, r, op));
++iter;
}
else
{
++iter;
}
}
while (!stack.empty())
{
cout << stack.top() << endl;
stack.pop();
}
return 0;
}