c++ 用栈stack实现表达式求值

问题说明

请编写程序,用栈实现简化的表达式求值。表达式是从键盘输入一个字符串。
比如:

输入((1+2+4)3-6)/5 。输出 3。
输入(11-10+100)/5。输出20。(注意整数的除法)
输入(10+10
2)/5。输出6。

要求:

支持操作: + - * /
支持小括号。
不支持负数的表达式。
只支持整数的表达式。

分析与步骤:
表达式求解问题需要用到栈(stack)的思想(先进后出),参考讲义及教材。
表达式字符串先处理为一个个的元素,放入队列中。这部分的代码已经给出。
用两个栈:数字栈和算符栈;遇到数字就将其放入数字栈中,遇到运算符就要分开考虑:

是‘(’就直接入栈,方便遇到’)‘时,就将’('以后所有的算符栈带入数字栈运算,结果保存于数字栈
如果算符栈为空栈直接入栈
如果算符栈的栈顶元素优先级小于当前字符的优先级,直接入栈
其他情况就是要将数字栈与算符栈结合,算出结果保存在数字栈中

数字栈中的最后一个元素即为题解。

算法说明

An algorithm of evaluating infix-expressions using stacks.

[Input]: A string of infix expression.
[Computation steps]:

  1. Parse the input string into a sequence of tokens, ordered from left to right.

  2. Create two stacks, called D-stack (operand-stack, numstack ) and the R-stack (operator-stack, oprstack)

// 你的代码开始
3. Repeat:

Read the next token T from the token sequence (left to right)
Do one of the following actions according to the current condition.
f) If reach the end of the token sequence, which means nothing is left in the token sequence, repeatedly do the process (p)
	as much as possible (until no more number can be popped out from the D-stack, or no more
	operator can be popped out from the R-stack). 
	Finally, the number appears on the top of the Dstack is the value of the expression.
	Quit the loop, and end the algorithm
a) If T is a number (operand), push T to the D-stack.
b) If T an operator, and the R-stack is empty, or the top of the R-stack is "(", then push T onto the R-stack.
c) If T is an operator and the top of R-stack is an operator K, and T has higher priority than K, it means pre(T) < pre(K), then push T onto the R-stack.
d) If T is "(", then push it onto the R-stack.
		Note: parenthesises, "(" and ")", are not operators, although "(" can appear on the operator stack.
e) If T is ")", then do the following "process" (p) described below, until the corresponding "(" is popped out from the R-stack
g) If the above conditions do not apply, which means T is an operator, and the top of the R-stack
	is some operator X, and T has lower priority than X, i.e. pre(T)>=pre(X), do the process (p)
	repeatedly as much as possible. Then, push T onto the R-stack.

§ Process
(1) pop operator stack once ( operator ). Do one of the following two actions.
(2.1) If (1) is successful, do (h) (i) (j) (k).
- (h) pop operand stack once ( value1 )
- (i) pop operand - stack again ( value2 )
- (j) compute value2 operator value1 and obtain a value N
- (k) push N onto the operand stack.
(2.2) Otherwise when (1) failes, do (h) and push value1 onto the D-stack.

后记

不得不感叹,国外的计算机系的教材就是比国内的好。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值