数据结构表达式求值问题 求代码
就是数据结构课本(严蔚敏)中栈中的一个问题,算法想的挺简单,不过实现起来着实困难,
例:计算 (3 + 2 * 2(1 + 3))
就是建立两个栈一个字符一个数字 判断读入的是符号还是数据时要用ASCII码吗??? 希望高手能给个C的源代码!!!!
[解决办法]
in++;//指针移到右括号的后一位。
}
else if(priority(*in)>=priority(s.top()))
{//如果大于栈顶的优先权,入栈。
s.push(*in++);
}
else
{//否则栈顶元素出栈,赋予后辍式。
*out++=s.top();
s.pop();
}
}
}
while(priority('\0')<priority(s.top()))
{//元素全部出栈,给后辍式。
*out++=s.top();
s.pop();
}
*out='\0';//使后辍式成为字符串。
}
int compute(char *chb)
{
stack<int>num;
int a,b;
while(*chb!='\0')
{
if(isdigit(*chb))
{//数字入栈。
num.push(*chb++-'0');
}
else
{//出两个元素出来计算,压入栈。
a=num.top();num.pop();
b=num.top();num.pop();
num.push(reback(*chb,a,b));
chb++;
}
}
return num.top();
}
int reback(char ch,int a,int b)
{
switch(ch)
{
case '+':return b+a;
case '-':return b-a;
case '/':return b/a;
case '*':return b*a;
case '%':return b%a;
default:return 0;
}
}