<p style="margin-top:16px;color:rgb(34,34,34);font-family:'PingFang SC','Hiragino Sans GB','Microsoft YaHei','WenQuanYi Micro Hei','Helvetica Neue',Arial,sans-serif;line-height:28px;background-color:rgb(255,255,255);">前几天有个面试题目:计算字符串"1 + (5 - 2) 3",结果为10,不能用eval()。今天介绍一下用压栈的方法解一解这个题目,事实上我们的计算器原理也是如此。
<p style="margin-top:16px;color:rgb(34,255);">

<p style="margin-top:16px;color:rgb(34,255);">

<p style="margin-top:16px;color:rgb(34,255);">

<p style="margin-top:16px;color:rgb(34,255);">

<p style="margin-top:16px;color:rgb(34,255);"><span style="font-weight:700;">2 总结算法<p style="margin-top:16px;color:rgb(34,255);">通过1中的分析我们大致可以整理出如下算法:<p style="margin-top:16px;color:rgb(34,255);">

<p style="margin-top:16px;color:rgb(34,255);">以上分析我们抽象出几个
函数:<p style="margin-top:16px;color:rgb(34,255);">(1)弹栈时计算‘两个数字和运算符组成的算式’结果的
函数。<p style="margin-top:16px;color:rgb(34,255);">(2)判断元素是数字还是运算符的
函数。<p style="margin-top:16px;color:rgb(34,255);">(3)把算式处理成列表形式的
函数。如:'-1-2((-2+3)+(-2/2))' 应该处理成:['-1','-','2','*','(','-2','+','3',')','/',')'] 。<p style="margin-top:16px;color:rgb(34,255);">(4)决策
函数,决定应该是入栈,弹栈运算,还是弹栈丢弃。<p style="margin-top:16px;color:rgb(34,255);">(5)主
函数,遍历算式列表,计算最终结果。<p style="margin-top:16px;color:rgb(34,255);"><span style="font-weight:700;">3 两数运算
函数<p style="margin-top:16px;color:rgb(34,255);">传入两个数字,一个运算符,根据运算符不同返回相应结果。即计算加减乘除:<p style="margin-top:16px;color:rgb(34,255);">

<p style="margin-top:16px;color:rgb(34,255);"><span style="font-weight:700;">4 判断是运算符还是数字<p style="margin-top:16px;color:rgb(34,255);">这里可能会想到isdigit()判断数字,但这个
函数不能判断小数和负数。所以,我们自己写一个
函数判断是否是运算符:<p style="margin-top:16px;color:rgb(34,255);">

<p style="margin-top:16px;color:rgb(34,255);">

<p style="margin-top:16px;color:rgb(34,255);"><span style="font-weight:700;">5 格式化算式为列表<p style="margin-top:16px;color:rgb(34,255);">这个步骤需要处理的是区分横杠‘-’是代表负数还是减号。详细参见下例,注释已经十分明了:<p style="margin-top:16px;color:rgb(34,255);">

<p style="margin-top:16px;color:rgb(34,255);"><span style="font-weight:700;">6 决策弹栈还是入栈<p style="margin-top:16px;color:rgb(34,255);">这个
函数比较难,也比较抽象。比较连续两个运算符来判断是入栈还是弹栈:<p style="margin-top:16px;color:rgb(34,255);">

<p style="margin-top:16px;color:rgb(34,255);"><span style="font-weight:700;">7 主
函数<p style="margin-top:16px;color:rgb(34,255);">主
函数负责遍历算式列表中的字符,决定入数字栈或运算符栈或弹栈运算。<p style="margin-top:16px;color:rgb(34,255);">

<p style="margin-top:16px;color:rgb(34,255);"><span style="font-weight:700;">8 终极
代码与测试<p style="margin-top:16px;color:rgb(34,255);">

<p style="margin-top:16px;color:rgb(34,255);">我们看一下谷歌运算的结果:<p style="margin-top:16px;color:rgb(34,255);">

<p style="margin-top:16px;color:rgb(34,255);">说明咱们算对了,不妨多测试一些算式看看。<p style="margin-top:16px;color:rgb(34,255);">本篇完。<p style="margin-top:16px;color:rgb(34,255);">装逼如风,常伴吾身!那么你学会了吗?<p style="margin-top:16px;color:rgb(34,255);">
