//头文件Prefix2Postfix.h
#include <iostream>
using namespace std;
void Check(char*str);
void postfix(char * infix);
int isp(char x);
int icp(char x);
bool isdigit(char c);
bool isoperator(char op) ;
//源文件Prefix2Postfix.cpp
#include "Prefix2Postfix.h"
#include <iostream>
#include "seqStack.h"
#include <math.h>
using namespace std;
/*
把中缀表达式e转换成后缀表示,并输出之。
设定e中最后一个符号是“#”,而且“#”一开始先放在栈s的栈底
*/
void postfix(char * infix)
{
char ch,y;
seqStack s;
s.InitseqStack();
s.Push('#'); //栈底放了一个‘#’
int i=0;
while (infix[i]!='#')
{
ch=infix[i];
if(!isoperator(ch)) cout<<ch<<" "; //是操作数,输出之
else if (ch==')') //遇到')',需持续退栈,直到遇到'('
{
for (y=s.Pop(); y!='('; y=s.Pop())
{
cout<<y<<" ";
}
}
else{ //是一个操作符
for (y=s.Pop(); isp(y)>=icp(ch) ;y=s.Pop())//isp是栈内优先数,icp是栈外优先数
{
cout<<y<<" ";
}
s.Push(y);
s.Push(ch);
}
i++;
}
while (!s.isEmpty())
{
y=s.Pop();
cout<<y<<" ";
}
}
int isp(char x)//设置栈内优先级
{
switch(x)
{
case '#':
{
return 0;
break;
}
case '(':
{
return 1;break;
}
case '*':
case '/':
case '%':
{
return 5; break;
}
case '+':
case '-':
{
return 3; break;
}
case ')':
{
return 6;break;
}
default:
return -1;
}
}
int icp(char x) //设置栈外优先级
{
switch(x)
{
case '#':
{ return 0;break;}
case '(':
{return 6; break;}
case '*':
case '/':
case '%':
{ return 4; break;}
case '+':
case '-':
{return 2;break;}
case ')':
{return 1;break;}
default:
return -1;
}
}
bool isoperator(char op)
{
switch(op)
{
case '+':
case '-':
case '*':
case '/':
case '%':
case '(':
case ')':
return true;
default :
return false;
}
}
/*bool isdigit(char c)
{
switch(c)
{
case '+':
case '-':
case '*':
case '/':
case '%':
case '(':
case ')':
return false;
default:
return true;
}
}
*/
void main()
{
char exp[100];
cout << "输入表达式(中缀,以#结束):";
cin>>exp;
postfix(exp);
}