0%

【Algorithm#0x00】数据结构-逆波兰表示法

四则运算表达式求值 - 逆波兰表示法

逆波兰表示法是栈结构的典型应用。
在逆波兰表示法中,无论是“把中缀表达式转化成后缀表达式”,还是“计算后缀表达式”,都需要用栈作为工具。
所以我写了一个简单的表达式转换程序试了下……(仅支持个位数加减法)

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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
#include <iostream>
#include <string>
#include <stack>
#include <cctype>
using namespace std;

// 返回符号优先级,若非运算符则返回0
inline unsigned short prior(char c)
{
switch (c)
{
case '*':
case '/':
return 2;
case '+':
case '-':
return 1;
default:
return 0;
}
}

// 将中缀表达式a转化为后缀表达式,并存储在c中
void convert_expression(string& a, string& c)
{
stack<char> b;

for (int i = 0; i < a.length(); ++i)
{
// 数字直接输出
if (('0'<=a[i] && a[i]<='9'))
{
c.push_back(a[i]);
continue;
}
// 左括号直接压栈
else if (a[i] == '(')
{
b.push(a[i]);
}
// 右扩号则循环输出直到左括号
else if (a[i]==')')
{
while (b.top() != '(')
{
c.push_back(b.top());
b.pop();
}
b.pop();
continue;
}
// 处理符号优先级
else if (prior(a[i]))
{
// 当前符号优先级 <= 栈顶符号优先级:栈顶符号出栈
while (!b.empty() && prior(a[i]) <= prior(b.top()))
{
c.push_back(b.top());
b.pop();
}
b.push(a[i]);
}
// 处理非法字符
else
{
cout << "Please check your expression." << endl;
}
}
// 输出栈内剩余字符
while (!b.empty())
{
c.push_back(b.top());
b.pop();
}
}

int main(void)
{
string expression; cin >> expression;
string postfix_expression;
convert_expression(expression, postfix_expression);
cout << postfix_expression << endl;
}