//数据结构//表达式求值//带注释#include #include using namespace std;const int MAXSIZE=100;template struct SqStack{ ElemType base[MAXSIZE]; int top;};template void initStack(SqStack& s){ s.top=0;}template void clearStack(SqStack& s){ s.top=0;}template bool isEmpty(SqStack& s){ return s.top==0;}template bool isFull(SqStack& s){ return s.top==MAXSIZE;}template ElemType peek(SqStack& s){ if(s.top==0){cerrvoid push(SqStack& s,const ElemType& e){ if(s.top==MAXSIZE){cerrElemType pop(SqStack& s){ if(s.top==0){cerr r; initStack(r);//初始化栈 push(r,'@');//给栈底放入'@'字符,它具有最低优先级 int i,j; i=0; j=0; char ch=s1; while(ch!='@'){if(ch==' ') ch=s1[++i];else if(ch=='('){ push(r,ch); ch=s1[++i];}else if(ch==')'){ while(peek(r)!='(')
s2[j++]=pop(r); pop(r); ch=s1[++i];}else if(ch=='+'||ch=='-'||ch=='*'||ch=='/'){ char w=peek(r); while(precede(w)>=precede(ch)){
s2[j++]=w;
pop(r);
w=peek(r); } push(r,ch); ch=s1[++i];}else{ while(isdigit(ch)||ch=='.'){
s2[j++]=ch;
ch=s1[++i]; } s2[j++]=' ';} } ch=pop(r); while(ch!='@'){if(ch=='('){ cerr s; initStack(s); istringstream ins(str); //把str定义为string流对象ins,P82 char ch; //用于输入字符 double x; //用于输入浮点数 ins>>ch; while(ch!='@') {switch(ch){case '+': x=pop(s)+pop(s); break;case '-': x=pop(s); //pop(s)弹出减数 x=pop(s)-x;//pop(s)弹出被减数 break;case '*': x=pop(s)*pop(s); break;case '/': x=pop(s); if(x!=0.0)
x=pop(s)/x; else {cerr>x; //从字符串输入流中读入一个浮点数}push(s,x); //把读入的数或进行相应运算的结果压入到s栈中ins>>ch; } if(!isEmpty(s)){x=pop(s);if(isEmpty(s)) return x;else{ cerr>ss; change(ss,s2); cout<<ss<<endl;
if(!checkString(ss)) cout<<"表达式错误!"; double r=compute(s2); cout<<r<<endl; }}这个要给钱才行
|