表达式计算

波兰式,操作符放在操作数前。

逆波兰式,操作符放在操作数后。

中序的话,用两个栈,一个存操作符, 一个存操作数,根据操作符优先级来操作。为了处理边界情况,在操作符的栈底和栈顶都放了一个"#"。

伪代码如下:

 1 stack<char> ops;
 2 stack<int> nums;
 3 ops.push('#');
 4 
 5 for (; ops.top() != '#' || (current != '#'); current = readNext()) {
 6     if (!isOperator(current)) {
 7         nums.push(current);
 8     } else if (current > ops.top()) {
 9         ops.push(current);
10     } else if (current == ops.top()) { // if "()"
11         ops.pop();
12     } else {
13         int n1 = nums.top(); nums.pop();
14         int n2 = nums.top(); nums.pop();
15         nums.push(operate(n1, n2, ops.top());
16         ops.pop();
17     }
18 }
19 
20 return nums.top();

 

posted @ 2014-10-05 15:38  linyx  阅读(151)  评论(0编辑  收藏  举报