#include <iostream>
using namespace std;
#define MaxSize 50
typedef char ElemType;
typedef struct
{
ElemType data[MaxSize];
int top;
} SqStack;
void initStack(SqStack &S)
{
S.top = -1;
}
bool stackEmpty(SqStack S)
{
if(S.top == -1)
return true;
else
return false;
}
bool push(SqStack &S,ElemType x)
{
if(S.top == MaxSize-1)
return false;
S.top++;
S.data[S.top] = x;
return true;
}
bool pop(SqStack &S,ElemType &x)
{
if(S.top == -1)
return false;
x = S.data[S.top--];
return true;
}
bool getTop(SqStack S,ElemType &x)
{
if(S.top == -1)
return false;
x = S.data[S.top];
return true;
}
bool reversePolish(ElemType str[],int length)
{
SqStack S;
initStack(S);
string polish;
int i;
for(i=0; i<length; i++)
{
switch(str[i])
{
case '(':
push(S,str[i]);
break;
case ')':
ElemType topElem,x;
getTop(S,topElem);
while(topElem != '(')
{
pop(S,x);
polish+=x;
if(stackEmpty(S))
{
break;
}
else
getTop(S,topElem);
}
pop(S,x);
break;
case '+':
case '-':
if(!stackEmpty(S))
{
ElemType topElem;
getTop(S,topElem);
while(topElem == '+' || topElem == '-' || topElem == '*' || topElem == '/')
{
ElemType x;
pop(S,x);
polish+=x;
if(stackEmpty(S))
{
break;
}
else
getTop(S,topElem);
}
}
push(S,str[i]);
break;
case '*':
case '/':
if(!stackEmpty(S))
{
ElemType topElem;
getTop(S,topElem);
while(topElem == '*' || topElem == '/')
{
ElemType x;
pop(S,x);
polish+=x;
if(stackEmpty(S))
{
break;
}
else
getTop(S,topElem);
}
}
push(S,str[i]);
break;
default:
polish+=str[i];
}
}
while(!stackEmpty(S))
{
ElemType x;
pop(S,x);
polish+=x;
}
cout<<"后缀表达式为:"<<endl;
cout<<polish;
return true;
}
int main()
{
ElemType str[MaxSize];
int length;
cout<<"请输入中缀字符串长度:";
cin>>length;
cout<<"请输入中缀表达式:"<<endl;
cin>>str;
cout<<"您输入的中缀表达式为:";
cout<<str<<endl;
reversePolish(str,length);
return 0;
}
代码有个缺点,输入的时候必须输入要测试的中缀字符串长度,我懒得改了~~其他应该还是没问题的
|