当前位置: 代码迷 >> 综合 >> 栈和队列:计算表达式
  详细解决方案

栈和队列:计算表达式

热度:99   发布时间:2024-01-20 03:05:39.0

计算表达式

题目:计算(4+5)*(7-2)

思路:本文只介绍简单处理后的表达式,来简单的阐明栈在计算表达式中的应用,例如上面的表达式,要用栈的话,需要对表达式做转换,转成4 5 + 7 2 - *,然后利用栈做计算。

int express(string input)
{stack<int>  st;int op1,op2;int i=0;while(i < input.size()){if(input[i] == ' ') continue;if(isdigit(input[i])){st.push(input[i]-'0');}else{op1 = st.top();st.pop();op2 = st.top();st.pop();switch(input[i]){case '+':st.push(op1+op2);break;case '-':st.push(op2-op1);//注意顺序break;case '*':st.push(op1*op2);break;case '/':st.push(op2/op1);break;default:break;     }}i++;}return st.top();
}

本文没有把中缀表达式转为后缀表达式的代码,后续的文章会有介绍。

  相关解决方案