利用栈存储中缀表达式的各个元素
例如:
1 2 + 3 *
3 3 *
9
1 // 后缀表达式求解结果
2
3 #include <iostream>
4 #include <stack>
5 #include <string>
6 #include <sstream>
7 #include <algorithm>
8 using namespace std;
9
10 void printPost(const stack<string>& post)
11 {
12 stack<string> temp(post);
13 while (!temp.empty())
14 {
15 cout << temp.top() << ' ';
16 temp.pop();
17 }
18 cout << endl;
19 }
20
21 void clearPost(stack<string>& post)
22 {
23 while (!post.empty())
24 {
25 post.pop();
26 }
27 }
28
29 void getPost(stack<string>& post)
30 {
31 clearPost(post);
32 string t;
33 stack<string> temp;
34 while (cin >> t)
35 {
36 temp.push(t);
37 }
38 while (!temp.empty())
39 {
40 post.push(temp.top());
41 temp.pop();
42 }
43 }
44
45 double computePost(const stack<string>& rhs)
46 {
47 stack<string> post(rhs);
48 double d1, d2;
49 double dd;
50 string optor;
51 string temp;
52 while (post.size() >= 3)
53 {
54 d1 = atof(post.top().c_str());
55 post.pop();
56 d2 = atof(post.top().c_str());
57 post.pop();
58 optor = post.top();
59 post.pop();
60 switch (optor[0])
61 {
62 case '+':
63 dd = d1 + d2;
64 break;
65 case '-':
66 dd = d1 - d2;
67 break;
68 case '*':
69 dd = d1 * d2;
70 break;
71 case '/':
72 dd = d1 / d2;
73 break;
74 default:
75 break;
76 }
77 if (post.empty())
78 {
79 break;
80 }
81 stringstream ss;
82 ss << dd;
83 ss >> temp;
84 post.push(temp);
85 printPost(post);
86 }
87 return dd;
88 }
89
90 int main()
91 {
92 stack<string> post;
93 cout << "Input:" << endl;
94 getPost(post);
95 printPost(post);
96 cout << computePost(post) << endl;
97 return 0;
98 }
posted on 2011-06-25 19:10
unixfy 阅读(410)
评论(0) 编辑 收藏 引用