欢迎加qq群:453398542 学习讨论,会定期分享资料课程,解答问题。
表达式求值问题
【问题描述】
给定一个算术表达式,对该表达式进行四则运算。
(1)以栈作为存储结构,一个栈存放操作符,一个栈存放操作数;
(2)按字符串形式输入表达式;
(3)最终结果放在操作数栈中并输出。
给定的表达式中,必须有包含两位数的数值。例如,给定的表达式为:(10+2)*6-12/3
#include<iostream>
using namespace std;
typedef struct SNode{
int data;
struct SNode *next;
}SNode,*LinkStack;
char Precede(char theta1,char theta2){
//比较优先级
if( (theta1=='(' && theta2==')' ) || (theta1=='#' && theta2=='#') )
return '=';
else if( theta1=='(' || theta1=='#' || theta2=='('|| ( theta1=='+'||theta1=='-' )&&(theta2=='*'||theta2=='/') )
return '<';
else return '>';
}
int InitStack(LinkStack &S){
S=NULL;
return 1;
}
int StackEmpty(LinkStack S){
if(!S)
return 1;
return 0;
}
int Push(LinkStack &S,char e){
SNode *p=new SNode;
if(!p){
return -1;
}
p->data=e;
p->next=S;
S=p;
return 1;
}
int Pop(LinkStack &S,char &e){
SNode *p;
if(!S)
return 0;
e=S->data;
p=S;
S=S->next;
delete p;
return 1;
}
int GetTop(LinkStack &S,char &e){
if(!S)
return 0;
e=S->data;
return 1;
}
char Operate(char first,char theta,char second){
//运算
switch(theta){
case '+':
return (first-'0')+(second -'0')+48;
case '-':
return (first-'0')-(second -'0')+48;
case '*':
return (first-'0')*(second -'0')+48;
case '/':
return (first-'0')/(second -'0')+48;
}
}
char EvaluateExpression(){
//结果
LinkStack OPTR,OPND;
char ch,theta,a,b,x,top,k=0,count;
InitStack(OPTR);//运算符
InitStack(OPND);//数和结果
Push(OPTR,'#');
cin>>ch;
while(ch!='#'||(GetTop(OPTR,top),top!='#')){
if(isdigit(ch)){
//判断字符是否为阿拉伯数字
if(k>0){
Pop(OPND,count);
count=(count-'0')*10+(ch-'0')+48;
Push(OPND,count);
}
else{
Push(OPND,ch);
}
cin>>ch;
k++;
}
else{
k=0;
GetTop(OPTR,top);
switch(Precede(top,ch)){
case '<':
Push(OPTR,ch);
cin>>ch;
break;
case '>':
Pop(OPTR,theta);
Pop(OPND,a);
Pop(OPND,b);
Push(OPND,Operate(b,theta,a));
break;
case'=':
Pop(OPTR,x);
cin>>ch;
break;
}
}
}
GetTop(OPND,ch);
return ch;
}
int main(){
cout<<"输入表达式(以#结尾):"<<endl;
char res=EvaluateExpression();
cout<<(int)(res-'0')<<endl;
}