#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;
}中缀表达式转换为前缀表达式
最新推荐文章于 2022-05-08 15:07:05 发布
本文介绍了一种将C++表达式从后缀形式转换为前缀形式的算法实现,包括栈和子表达式的使用,详细解释了括号、运算符的优先级和操作流程。
1184

被折叠的 条评论
为什么被折叠?



