看了紫书上的表达式树,上面讲用递归来建树,并给出了代码,稍加改造就可以用来求表达式的值。
这让我想起了以前看的一篇博客 http://blog.csdn.net/yzl_rex/article/details/7745341
讲的是如何利用栈来求四则运算表达式的值。但计算前需要将中缀表达式转为后缀表达式。
上面有基本的理论+详细的步骤,写的很不错。
以下是自己写的代码
#include<stdio.h>
#include<iostream>
#include<string>
#include<queue>
#include<stack>
#include<vector>
#include<string.h>
#define maxn 10010
using namespace std;
char str[maxn];
int cal(int a,int b,char ch)
{
switch(ch)
{
case '+':return a+b;
case '-':return a-b;
case '*':return a*b;
case '/':return a/b;
}
return 0;
}
struct Element
{
bool isnum;
int num;
char ch;
Element(bool a,int b,char c):isnum(a),num(b),ch(c){}
};
int main()
{
vector<Element>vec;
gets(str);
int l=strlen(str);
for(int i=0;i<l;i++)
{
if(str[i]==' ') continue;
if(str[i]>='0'&&str[i]<='9')
{
int num=str[i]-'0';
int r=i+1;
while(str[r]==' '||(str[r]>='0'&&str[r]<='9'))
{
if(str[r]==' ')
{
r++;
continue;
}
num*=10;
num+=str[r]-'0';
r++;
}
vec.push_back(Element(true,num,0));
i=r-1;
}
else vec.push_back(Element(false,0,str[i]));
}
queue<Element>q;
stack<Element>s;
/*
for(unsigned int i=0;i<vec.size();i++)
if(vec[i].isnum) printf("%d ",vec[i].num);
else printf("%c ",vec[i].ch);
puts("");
*/
for(unsigned int i=0;i<vec.size();i++)
if(vec[i].isnum) q.push(vec[i]);
else
{
if(vec[i].ch==')')
{
while(s.top().ch!='(')
{
q.push(s.top());
s.pop();
}
s.pop();
}
else if(vec[i].ch=='('||vec[i].ch=='*'||vec[i].ch=='/') s.push(vec[i]);
else
{
if(!s.empty()&&(s.top().ch=='*'||s.top().ch=='/'))
{
while(!s.empty()&&s.top().ch!='('&&s.top().ch!=')')
{
q.push(s.top());
s.pop();
}
}
s.push(vec[i]);
}
}
while(!s.empty())
{
q.push(s.top());
s.pop();
}
/*
while(!q.empty())
{
if(q.front().isnum) printf("%d ",q.front().num);
else printf("%c ",q.front().ch);
q.pop();
}
puts("");
*/
while(!q.empty())
{
if(q.front().isnum) {s.push(q.front());q.pop();}
else
{
Element e=q.front();
q.pop();
Element e1=s.top();
s.pop();
Element e2=s.top();
s.pop();
s.push(Element(true,cal(e2.num,e1.num,e.ch),0));
}
}
printf("%d\n",s.top().num);
return 0;
}
/*
9+(3-1)*3+10/2
( 9 + ( 3 - 1 ) * 3 + 1 0 / 2 )
((1 8 /(( 1+ 2)* 3)) +3) * 5
*/