#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<conio.h>
#include<iostream.h>
#define MAXSIZE 100
#define OK 1
#define ERROR 0
#define OVERFLOW -2
#define INFEASIBLE -1
typedef int SElemType;
typedef int Status;
typedef struct
{
SElemType *base;
SElemType *top;
int stacksize;
}SqStack;
//顺序栈的初始化
Status InitStack(SqStack &S)
{
S.base=new SElemType[MAXSIZE];
if(!S.base) exit(OVERFLOW);
S.top=S.base;
S.stacksize=MAXSIZE;
return OK;
}
//入栈
Status Push(SqStack &S,SElemType e)
{
if(S.top-S.base==S.stacksize) return ERROR;
*S.top++=e;
return OK;
}
//出栈
Status Pop(SqStack &S,SElemType &e)
{
if(S.top==S.base) return ERROR;
e=*--S.top;
return OK;
}
//取栈顶元素
SElemType GetTop(SqStack S)
{
if(S.top!=S.base)
return *(S.top-1);
}
//P78页 表3.1
char Precede(char a1,char a2)
{
char r;
switch(a2)
{
case'+':
case'-':
if(a1=='(' || a1=='#')
r='<';
else
r='>';
break;
case'*':
case'/':
if(a1=='*' || a1=='/' || a1==')')
r='>';
else
r='<';
break;
case '(':
if(a1 == ')')
{
cout<<"括号匹配错误"<<endl;
exit(-1);
}
else
r = '<';
break;
case ')':
if(a1 == '(')
r = '=';
else if(a1 == '#')
{
cout<<"error,没有左括号"<<endl;
}
else
r = '>';
break;
case '#':
switch(a1)
{
case'#':
r='=';
break;
case'(':
cout<<"error!没有右括号"<<endl;
exit(-1);
default:
r='>';
}//switch
break;
}
return r;
}
//判断是否为操作符
char In(char d)
{
switch(d)
{
case '+':
case '-':
case '*':
case '/':
case '(':
case ')':
case '#':
return true;
default:
return false;
}
}
//运算函数
int Operate(int a, int Opera, int b)
{
char n = (char)Opera;
switch(n)
{
case '+':
return a+b;
case '-':
return a-b;
case '*':
return a*b;
case '/':
if(b!=0)
return a/b;
else
{
cout<<"除数不能为0"<<endl;
exit(-1);
}
}
}
//
char EvaluateExpression()
{
SqStack OPTR;
SqStack OPND;
char ch;
int theta,a,b,x;
InitStack(OPND);
InitStack(OPTR);
Push(OPTR,'#');
cin>>ch;
while(ch!='#' || GetTop(OPTR)!='#')
{
if(!In(ch)) {Push(OPND,ch);cin>>ch;}
else
switch(Precede(GetTop(OPTR),ch))
{
case'<':
Push(OPTR,ch); cin>>ch;
break;
case'>':
Pop(OPTR,theta);
Pop(OPND,b);Pop(OPND,a);
Push(OPND,Operate(a,theta,b));
break;
case'=':
Pop(OPTR,x);cin>>ch;
break;
}
}
return GetTop(OPND);
}
int main()
{
int Result;
cout<<"Please Input Num with # to end"<<endl;
Result = EvaluateExpression();
cout<<"The result="<<Result<<endl;
system("pause");
return 0;
}