#include <iostream.h>
const int StackSize=50;
class Stack{
char *StackList;
int top;
public:
Stack(){
StackList=new char[StackSize];
top=-1;
}
bool IsEmpty();
bool IsFull();
void Push(char x);
char Pop();
char GetTop();
char EvalueExpression();
};
bool Stack:: IsEmpty(){
if(top==-1)
return true;
else return false;
}
bool Stack::IsFull(){
if(top==StackSize-1)
return true;
else return false;
}
void Stack:: Push(char x){
if(IsFull())
cout<<"栈满"<<endl;
else StackList[++top]=x;
}
char Stack::Pop(){
if(IsEmpty()) {
cout<<"栈空"<<endl; return' ' ;}
else return StackList[top--];
}
char Stack:: GetTop(){
if(IsEmpty()) {
cout<<"栈空"<<endl; return' ' ;}
else return StackList[top];
}
char Stack:: EvalueExpression( ){
char ch,ch3,ch4,op; int ch1,ch2,i,j; Stack s1,s2;
char ysf[7][7]={{'>','>','>','>','<','>','>'},
{'>','>','>','>','<','>','>'},
{'<','<','>','>','<','>','>'},
{'<','<','>','>','<','>','>'},
{'<','<','<','<','<','=','<'},
{'>','>','>','>','>','>','>'},
{'<','<','<','<','<','<','='}
};
cin>>ch;
s2.Push('#');
while((ch!='#')||(s2.GetTop()!='#')){
if(ch>='0'&& ch<='9') {
s1.Push(ch);
ch=cin.get();
}
else{ switch(s2.GetTop()){
case '*': ch1=0; break;
case '/': ch1=1; break;
case '+': ch1=2; break;
case '-': ch1=3; break;
case '(': ch1=4; break;
case ')': ch1=5; break;
case '#': ch1=6; break;
}
switch(ch){
case '*': ch2=0; break;
case '/': ch2=1; break;
case '+': ch2=2; break;
case '-': ch2=3; break;
case '(': ch2=4; break;
case ')': ch2=5; break;
case '#': ch2=6; break;
}
if(ysf[ch1][ch2]=='<'){
s2.Push(ch);
ch=cin.get();
}
else if(ysf[ch1][ch2]=='>') {
ch3=s1.Pop();
ch4=s1.Pop();
op=s2.Pop();
i=ch3-48; j=ch4-48;
switch(op){
case '+': s1.Push(i+j+48); break;
case '-': s1.Push(i-j+48); break;
case '*': s1.Push(i*j+48); break;
case '/': s1.Push(i/j+48); break;
}
}
else { s2.Pop();
ch=cin.get();
}
}//else
}//while
return s1.GetTop();
}
void main(){
Stack s;
cout<<"Input the expression"<<endl;
char ch=s.EvalueExpression();
cout<<"the value of expression: "<<ch<<endl;
}
改编多位运算