#include<iostream>
#include<stack>
#include<queue>
#include<string>
using namespace std;
stack<char>opt;
stack<char>subexp;
string InfixToPrefix(string exp,int len)
{
for(int i=len-1;i>=0;i--)
{
if(exp[i]>='0'&&exp[i]<='9')
{
subexp.push(exp[i]);
}else
{
if(exp[i]==')')
{
opt.push(exp[i]);
}else
{
if(exp[i]=='(')
{
while(opt.top()!=')')
{
char tmp=opt.top();
subexp.push(tmp);
opt.pop();
}
opt.pop();
}else
{
if(exp[i]=='*')
{
if(opt.empty())
{
opt.push(exp[i]);
}else
{
if(opt.top()=='+'||opt.top()=='-'||opt.top()=='/')
{
opt.push(exp[i]);
}else
{
while((opt.size()!=0)&&opt.top()!='*'&&opt.top()!='/'&&opt.top()!=')')
{
char tmp=opt.top();
subexp.push(tmp);
opt.pop();
}
opt.push(exp[i]);
}
}
}
if(exp[i]=='/')
{
if(opt.empty())
{
opt.push(exp[i]);
}else
{
if(opt.top()=='+'||opt.top()=='-'||opt.top()=='*')
{
opt.push(exp[i]);
}else
{
while((opt.size()!=0)&&opt.top()!='/'&&opt.top()!='*'&&opt.top()!=')')
{
char tmp=opt.top();
subexp.push(tmp);
opt.pop();
}
opt.push(exp[i]);
}
}
}
if(exp[i]=='+')
{
if(opt.empty())
{
opt.push(exp[i]);
}else
{
if(opt.top()=='-')
{
opt.push(exp[i]);
}else
{
while((opt.size()!=0)&&opt.top()!='+'&&opt.top()!='-'&&opt.top()!=')')
{
char tmp=opt.top();
subexp.push(tmp);
opt.pop();
}
opt.push(exp[i]);
}
}
}
if(exp[i]=='-')
{
if(opt.empty())
{
opt.push(exp[i]);
}else
{
if(opt.top()=='+')
{
opt.push(exp[i]);
}else
{
while((opt.size()!=0)&&opt.top()!='+'&&opt.top()!='-'&&opt.top()!=')')
{
char tmp=opt.top();
subexp.push(tmp);
opt.pop();
}
opt.push(exp[i]);
}
}
}
}
}
}
}
while(!opt.empty())
{
char tmp=opt.top();
subexp.push(tmp);
opt.pop();
}
string prefix="";
while(!subexp.empty())
{
prefix+=subexp.top();
subexp.pop();
}
return prefix;
}
int main()
{
string infix="8-(3+5)*(5-6/2)";
string prefix=InfixToPrefix(infix,infix.length());
cout<<prefix<<endl;
char ch;
cin>>ch;
exit(ch);
return 0;
}
中缀表达式转换为前缀表达式
最新推荐文章于 2024-01-02 01:02:36 发布