用栈实现两位数表达式的求值

来源:互联网 发布:php怎么写html 编辑:程序博客网 时间:2024/06/13 11:06
#include<iostream>
using namespace std;


//const char oper[7] = {'+','-','*','/','(',')','#'};
#define OK 1
#define ERROR 0
#define OVERFLOW -2
typedef char SElemType;
typedef int Status;
typedef struct SNode{
int data;
struct SNode *next;
}SNode,*LinkStack;




char Precede(char theta1,char theta2);




Status InitStack(LinkStack &S)
{
S = NULL;
return OK;
}
bool StackEmpty(LinkStack S)
{
if(!S)
return true;
return false;
}
Status Push(LinkStack &S,SElemType e)
{
SNode *p = new SNode;
if(!p)
{
return OVERFLOW;
}
p->data = e;
p->next = S;
S = p;
return OK;
}
Status Pop(LinkStack &S,SElemType &e)
{
SNode *p;
if(!S)
return ERROR;
e = S->data;
p = S;
S = S->next;
delete p;
return OK;
}
Status GetTop(LinkStack &S,SElemType &e)
{
if(!S)
return ERROR;
e = S->data;
return OK;
}


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;//OPTR ????·?  OPND êy?μ
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;
}


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 main()
{
char res=EvaluateExpression();
cout<<(int)(res-'0')<<endl;
}
0 0
原创粉丝点击