功能:输入表达式,求出其值。输入中不含有括号和空格。
思想:扫描表达式,用两个栈分别保存数字和操作符,扫描的时候遇到乘除法,就先计算,然后压栈。这样保证扫描结束后,操作符栈中仅有加号和减号。然后可以放入队列中求值。
#include <cassert> /* assert () */
#include <stack>
#include <iostream>
#include <cstdlib> /* atoi () */
#include <cstdio> /* getchar () */
using namespace std;
int main (int argc, char * argv[]){
assert (1 < argc);
stack<int> st1, st1_t;
stack<char> st2, st2_t;
char * p, * q;
char op;
int left, right, result;
p = q = argv[1];
while (* p){
if (* p > '9' || * p < '0'){
right = atoi (q);
/* compute result when scanning '*' or '/' operators firstly. */
if (!st2.empty () && (st2.top () == '*' || st2.top () == '/')){
op = st2.top ();
st2.pop ();
left = st1.top ();
st1.pop ();
switch (op){
case '*': right = left * right; break;
case '/': right = left / right; break;
}
}
st1.push (right);
st2.push (* p);
q = p + 1;
}
p ++;
}
/* append the last integers. */
right = atoi (q);
st1.push (right);
/* if the last operator of the input expression is '*' or '/', it has not been addressed yet.
Get the result of '*' or '/' and put it into the number stack.*/
if ('*' == st2.top () || '/' == st2.top ()){
op = st2.top ();
st2.pop ();
right = st1.top ();
st1.pop ();
left = st1.top ();
st1.pop ();
switch (op){
case '*': result = left * right; break;
case '/': result = left / right; break;
}
st1.push (result);
}
/* reverse the two stacks to ensure calculating is performed from leftside to rightside. */
while (!st2.empty ()){
st2_t.push (st2.top ());
st2.pop ();
}
while (!st1.empty ()){
st1_t.push (st1.top ());
st1.pop ();
}
/* take the first number out from the number stack. */
left = st1_t.top ();
st1_t.pop ();
/* now the two stacks has the same number of elements, and the operator stack
* contains only '+' and '-' operators. */
while (!st2_t.empty ()){
op = st2_t.top ();
st2_t.pop ();
right = st1_t.top ();
st1_t.pop ();
switch (op){
case '+': left += right; break;
case '-': left -= right; break;
default : cout << op << endl;
}
}
/* reslut is stored in the variable 'left' */
result = left;
cout << result << endl;
return 0;
}