栈的基础应用之中缀转换后缀

算法详解:

1、在遇到操作数时,将其追加到输出字符串postfix中,在后缀表达式中,操作数的顺序与其在中缀表达式中的顺序相同,中缀表达式中操作符左边的操作数也出现在后缀表达式中的操作符的左边。

2、使各个左括号符入栈。

3、在遇到操作符时,若栈为空,则使操作符入栈。若栈非空,则使优先级更高(或相同)的操作符出栈,并追加到postfix中,在遇到左括号符,或优先级更低的操作符,或栈为空时停止。然后使新操作符入栈,这样,该步骤按优先级和从左到右的顺序给操作符排序。注意,使操作符持续出栈,直到遇到的操作符的优先级比中缀表达式的当前操作符的优先级低为止,在优先级相同时,不停,因为从左到右的关联规则认为:在优先级相同的情况下,先应用最左边的操作符,而该操作符已在栈上。

4、在遇到右括号时,使操作符出栈,并追加到postfix尾,知道遇到左括号为止,原因是:在一对小括号内,优先级和从左到右的关联顺序确定操作符的顺序,第三步已经按照这些规则确定了操作符的顺序。

5、在到达字符串尾时,将栈中的其他内容追加到postfix中。

关于操作符的优先级问题,我采用了一位网友的方法,制作一个优先级的表,然后根据表中值的大小(1或0或-1)来判断两个操作符的优先级别。

#include<iostream> #include<string> #include<map> #include<utility> #include<stack> using namespace std; void infix2postfix(const string &infix,string & postfix); bool isParenLeft(char ch); bool isParenRight(char ch); bool isOperand(char ch); bool isOperator(char ch); bool priority(char ch1,char ch2); typedef pair<char ,int> Pair; map<char,int>opeMap; int table[4][4]={{0,0,1,1},{0,0,1,1},{-1,-1,0,0},{0,0,-1,-1}}; int main() { opeMap.insert(Pair('+',0)); opeMap.insert(Pair('-',1)); opeMap.insert(Pair('*',2)); opeMap.insert(Pair('/',3)); cout<<"enter the right infix expression :"; string str1,str2; getline(cin,str1); cout<<" the infix expression is :"<<str1<<endl; cout<<"after converting ,the postfix expression is :"; infix2postfix(str1,str2); cout<<str2<<endl; return 0; } bool priority(char ch1,char ch2) { if(table[opeMap[ch1]][ch2]>=0) return true; else return false; } bool isParenLeft(char ch) { return (ch=='['||ch=='{'||ch=='('); } bool isParenRight(char ch) { return (ch==']'||ch=='}'||ch==')'); } bool isOperand(char ch) { return(ch>='a'&&ch<='z'); } bool isOperator(char ch) { return (ch=='+'||ch=='-'||ch=='/'||ch=='*'); } void infix2postfix(const string &infix,string & postfix) { int size=infix.size(); char ch; stack<char> s; for(int i=0;i<size;i++) { ch=infix[i]; if(isOperand(ch)) { postfix=postfix+ch; } else if(isParenLeft(ch)) { s.push(ch); } else if(isParenRight(ch)) { ch=s.top(); s.pop(); while(!isParenLeft(ch)) { postfix=postfix+ch; ch=s.top(); s.pop(); } } else if(isOperator(ch)) { while(!s.empty()&&!isParenLeft(s.top())&&!priority(ch,s.top())) { postfix=postfix+s.top(); s.pop(); } s.push(ch); } } while(!s.empty()) { postfix=postfix+s.top(); s.pop(); } }


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值