#include<iostream>
using namespace std;
const int MaxSize=100;
template<typename T>
class SqStackClass
{
T *data;
int top;
public:
SqStackClass();
~SqStackClass();
bool StackEmpty();
bool Push(T e);
bool Pop(T &e);
bool GetTop(T &e);
void Display();
};
template<typename T>
SqStackClass<T>::SqStackClass()
{
data=new T[MaxSize];
top=-1;
}
template<typename T>
SqStackClass<T>::~SqStackClass()
{
delete[]data;
}
template<typename T>
bool SqStackClass<T>::StackEmpty()
{
if(top==-1)
return true;
else
return false;
}
template<typename T>
bool SqStackClass<T>::Push(T e)
{
if(top==MaxSize-1)
return false;
top++;
data[top]=e;
return true;
}
template<typename T>
bool SqStackClass<T>::Pop(T &e)
{
if(StackEmpty())
return false;
e=data[top];
top--;
return true;
}
template<typename T>
bool SqStackClass<T>::GetTop(T &e)
{
if(StackEmpty())
return false;
e=data[top];
return true;
}
template<typename T>
void SqStackClass<T>::Display()
{
while(!StackEmpty())
{
cout<<data[top]<<" ";
top--;
}
cout<<endl;
}
class ExpressClass
{
char *exp;//存放中缀表达式
char postexp[MaxSize];//存放后缀表达式
int pnum;//后缀中的字符个数
public:
//获取中缀表达式
void Setexp(char *str);
//转换
void Trans();
//输出后缀表达式
void Displayexp();
//计算值
bool GetValue(double &v);
};
void ExpressClass::Setexp(char *str)
{
exp=str;
}
void ExpressClass::Trans()
{
//建立运算符栈
SqStackClass<char> op;
//i为exp下标,j为postexp下标
int i=0,j=0;
char ch,e;
while(exp[i])
{
ch=exp[i];
if(ch=='(')
op.Push(ch);
else if(ch==')')
{
while(!op.StackEmpty()&&op.GetTop(e)&&e!='(')
{
op.Pop(e);
postexp[j++]=e;
}
op.Pop(e);
}
else if(ch=='+'||ch=='-')
{
while(!op.StackEmpty()&&op.GetTop(e)&&e!='(')
{
op.Pop(e);
postexp[j++]=e;
}
op.Push(ch);
}
else if(ch=='*'||ch=='/')
{
while(!op.StackEmpty()||op.GetTop(e)&&e!='('&&(e=='*'||e=='/'))
{
op.Pop(e);
postexp[j++]=e;
}
op.Push(ch);
}
else
{
while(ch>='0'&&ch<='9')
{
postexp[j++]=ch;
i++;
if(exp[i])
ch=exp[i];
else
break;
}
i--;
postexp[j++]='#';
}
i++;
}
while(!op.StackEmpty())
{
op.Pop(e);
postexp[j++]=e;
}
pnum=j;
}
bool ExpressClass::GetValue(double &v)
{
SqStackClass<double> st;
double a,b,c,d;
int i=0;
char ch;
while(i<pnum)
{
ch=postexp[i];
switch(ch)
{
case'+':
st.Pop(a);
st.Pop(b);
c=b+a;
st.Push(c);
break;
case'-':
st.Pop(a);
st.Pop(b);
c=b-a;
st.Push(c);
break;
case'*':
st.Pop(a);
st.Pop(b);
c=b*a;
st.Push(c);
break;
case'/':
st.Pop(a);
st.Pop(b);
if(a!=0)
{
c=b/a;
st.Push(c);
}
else
return false;
break;
default:
d=0;
while(ch>='0'&&ch<='9')
{
d=10*d+(ch-'0');
i++;
ch=postexp[i];
}
st.Push(d);
break;
}
i++;
}
st.GetTop(v);
return true;
}
void ExpressClass::Displayexp()
{
int i;
for(i=0;i<pnum;i++)
cout<<postexp[i];
cout<<endl;
}
int main()
{
SqStackClass <char> st1;
st1.Push('a');
st1.Push('b');
st1.Push('c');
st1.Display();
double v;
ExpressClass obj;
char str[MaxSize];
cin>>str;
obj.Setexp(str);
cout<<"中缀表达式:"<<str<<endl;
obj.Trans();
cout<<"后缀表达式:";
obj.Displayexp();
obj.GetValue(v);
cout<<"值为:"<<v<<endl;
int x;
cin>>x;
return 0;
}