《算法》第一章——中缀表达式转前缀和后缀表达式

来源:互联网 发布:system.log windows 编辑:程序博客网 时间:2024/05/20 17:09

思路:

参考中的文章已经将思路讲的非常详细了。

中缀转前缀:
(1) 初始化两个栈:运算符栈S1和储存中间结果的栈S2;
(2) 从右至左扫描中缀表达式;
(3) 遇到操作数时,将其压入S2;
(4) 遇到运算符时,比较其与S1栈顶运算符的优先级:
(4-1) 如果S1为空,或栈顶运算符为右括号“)”,则直接将此运算符入栈;
(4-2) 否则,若优先级比栈顶运算符的较高或相等,也将运算符压入S1;
(4-3) 否则,将S1栈顶的运算符弹出并压入到S2中,再次转到(4-1)与S1中新的栈顶运算符相比较;
(5) 遇到括号时:
(5-1) 如果是右括号“)”,则直接压入S1;
(5-2) 如果是左括号“(”,则依次弹出S1栈顶的运算符,并压入S2,直到遇到右括号为止,此时将这一对括号丢弃;
(6) 重复步骤(2)至(5),直到表达式的最左边;
(7) 将S1中剩余的运算符依次弹出并压入S2;
(8) 依次弹出S2中的元素并输出,结果即为中缀表达式对应的前缀表达式。

代码:

#include<iostream>#include<string>#include<queue>#include<stack>using namespace std;stack<char> ops;//stack for store operatorstack<char> infixExps;//stack for store infix expression//queue<char> prefixExps;//stack for store prefix expression/*usage:priority comparereturn val:0 for equal,1 for higher*/int equal_or_higer(const char& lv, const char& rv){if ((lv == '+' || lv == '-') && (rv == '+' || rv == '-'))return 0;else if ((lv == '*' || lv == '/') && (rv == '*' || rv == '/'))return 0;else if ((lv == '*' || lv == '/') && (rv == '+' || rv == '-'))return 1;}void infixToSuffixExp(){string exp;while (cin >> exp, !cin.eof())//"ctrl+z" for console EOF{if (cin.bad()){cerr << "error:IO stream corrupt " << endl;}if (cin.fail()){cerr << "bad data!try again!" << endl;cin.clear();cin.sync();continue;}for (string::reverse_iterator rit = exp.rbegin(); rit != exp.rend(); ++rit){if (*rit >= '0' && *rit <= '9'|| *rit=='.'){infixExps.push(*rit);}else if (*rit == '+' || *rit == '-' || *rit == '*' || *rit == '/'){//注意:这个判断分支内之所以没有考虑操作数栈的栈顶是左括号的情况,因为左括号是不会入该栈的。do{if (ops.empty() || ops.top() == ')'){ops.push(*rit);break;//continue;}else if (equal_or_higer(*rit, ops.top()) >= 0){ops.push(*rit);break;}else{char ch = ops.top();ops.pop();infixExps.push(ch);}} while (1);}else if (*rit == '('){//这个判断分支中不需要考虑操作符栈为空的情况,因为括号是成对出现的,当前读到'(',所以必有')'在栈中。char ch;while ((ch=ops.top()) != ')'){infixExps.push(ch);ops.pop();}ops.pop();//pop ')'}else if (*rit == ')'){ops.push(*rit);}else{cout << "wrong expression" << endl;exit(-1);}}while (!ops.empty()){char ch;ch = ops.top();infixExps.push(ch);ops.pop();}while (!infixExps.empty()){cout << infixExps.top();infixExps.pop();}cout << endl;}}int main(void){infixToSuffixExp();system("pause");return 0;}



参考:前缀、中缀、后缀表达式


0 0