您的位置:首页 > 其它

中缀式转化为前缀式,中缀式转化为后缀式

2015-06-05 20:56 176 查看
1

中缀式转化为前缀式:

从左向右读取中缀式,

当读取到(";直接压栈;

当读取的(”将"(前的全部取出,存到结果字符串中;

当读取的‘为’操作符时,将其与栈顶元素比较,

当栈顶元素小于或等于当前操作符时,将其压栈,

与中缀式转后缀式不同。//后缀式中,栈顶元素小于操作符时才可将其压栈;

string  fun(string a,string b)//中缀转前缀
{
int len=a.length();
stacks;
s.push('#');
for(int i=len-2; i>=0; )
{
if(a[i]==')')
{
s.push(a[i]);
i--;
}
else if(a[i]=='(')
{
while(s.top()!=')')
{
b+=s.top();
s.pop();
b+=' ';
}
s.pop();
i--;
}
else if(a[i]=='*'||a[i]=='-'||a[i]=='/'||a[i]=='+')
{
while(cmp(s.top())>cmp(a[i]))
{
b+=s.top();
s.pop();
b+=' ';
}
s.push(a[i]);
i--;
}
else
{
while( (a[i]<='9'&&a[i]>='0')||a[i]=='.')
{
b+=a[i];
i--;
}
b+=' ';
}
}
while(s.top()!='#')
{
b+=s.top();
s.pop();
if(s.top()!='#')
b+=' ';
} //
reverse(b.begin(),b.end());
b+=' ';
b+='=';
return  b;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: