用stl stack实现中缀转后缀及后缀运算。
转换之前将缺少的操作数补0。
Time limit: | 1sec. | Submitted: | 197 |
Memory limit: | 32M | Accepted: | 45 |
Write a program that can evaluate expressions from the following roughly BNF (Backus Naur Form) grammar:
expr ::= term | expr ‘+’ term | expr ‘-’ term unary_op ::= ‘+’ term | ‘-’ term term ::= ‘(’ expr ‘)’ | ‘(’ unary_op ‘)’ | literal literal ::= [0-9]
There will be no whitespace within an expression. All expressions will consist solely of the characters (, ), +, -, and the digits 0 through 9. You may assume that all input is well-formed.
Input
The input will consist of one expression per line followed by a newline. There will be no blank lines in the file.
Output
For each expression, output its integer value, followed by a single newline.
Sample Input
1 (-2)+3 (1-(2+3)) (1-2+3) (1-(+(2-3)))
Sample Output
1 1 -4 2 2
说明:
给出表达式。 由有符号一位数和运算符 + - 及 括号 组成。
计算结果。
为了将中缀表达为后缀。 将单操作数运算符前补零。
如 (-2)+3 先转换为 (0-2)+3。
然后中缀转后缀。 后缀运算。
stl stack 实现。
代码如下:
#include < stack >
using namespace std;
bool isd( char a) {
if (a >= ' 0 ' && a <= ' 9 ' ) return true ;
return false ;
}
int main() {
string ex;
while (cin >> ex) {
stack < char > a;
string tmp = "" ;
for ( int i = 0 ; i < ex.length(); i ++ ) {
if ((ex[i] == ' + ' || ex[i] == ' - ' ) && (i - 1 < 0 || ( ! isd(ex[i - 1 ]) && ex[i - 1 ] != ' ) ' ))) {
ex.insert(i, " 0 " );
i -- ;
} else if (isd(ex[i]))tmp += ex[i];
else if (ex[i] == ' ( ' ) a.push(ex[i]);
else if (ex[i] == ' ) ' ) {
while (a.top() != ' ( ' ) {
tmp += a.top();
a.pop();
}
a.pop();
} else {
if (a.empty() || a.top() == ' ( ' )a.push(ex[i]);
else {
tmp += a.top();
a.pop();
a.push(ex[i]);
}
}
}
while ( ! a.empty()) {
tmp += a.top();
a.pop();
}
stack < int > b;
for ( int i = 0 ; i < tmp.length(); i ++ ) {
if (isd(tmp[i]))b.push(tmp[i] - ' 0 ' );
else {
int tmp1, tmp2;
tmp2 = b.top();
b.pop();
tmp1 = b.top();
b.pop();
if (tmp[i] == ' + ' )b.push(tmp1 + tmp2);
else b.push(tmp1 - tmp2);
}
}
cout << b.top() << endl;
}
return 0 ;
}