前缀、中缀和后缀算式

.转换方法

 

 

中缀算式(3+4X)-2Y/3对应的后缀算式  3 4 X * + 2 Y * 3 / -  乘号也应算进去

转载于:https://www.cnblogs.com/fthjane/p/4745532.html

### C++ 中前缀中缀后缀表达式的定义及使用方法 #### 1. 中缀表达式 (Infix Expression) 中缀表达式是最常见的算术表示法,在这种形式下,操作符位于两个操作数之间。例如: \[ a + b \] 这是人类最直观理解的方式,但在计算机处理时较为复杂。 对于复杂的表达式,如 \( 1 + ((2 + 3) * 4) - 5 \),可以直接按照常规书写习惯来理解计算[^1]。 #### 2. 前缀表达式 (Prefix Expression 或 Polish Notation) 在前缀表达式里,操作符总是放在其对应的操作数之前。这使得解析变得简单,因为不需要考虑优先级或括号的影响。上述例子转换为前缀表达式如下所示: \[- (+ 1 (* (+ 2 3) 4)) 5\] 简化后的版本则会去除不必要的括号: \- + 1 * + 2 3 4 5 这种方式可以更方便地通过栈结构实现求值算法[^2]。 #### 3. 后缀表达式 (Postfix Expression 或 Reverse Polish Notation) 相反于前缀表达式,后缀表达式中的操作符紧跟在其相应的操作数之后。同样以上述为例,该表达式的后缀形式将是这样的: \[1 2 3 + 4 * + 5 -\] 此格式也易于利用堆栈来进行高效的评估过程[^3]。 #### 实现示例 下面给出一段简单的C++代码用于展示如何将一个给定的字符串形式的中缀表达式转换成后缀表达式并打印出来: ```cpp #include <iostream> #include <stack> #include <string> using namespace std; bool isOperator(char c){ return (!isdigit(c) && !isalpha(c)); } int getPrecedence(char op){ if(op == '+' || op == '-') return 1; else if(op == '*' || op == '/') return 2; else return 0; // '(' or ')' } void infixToPostfix(string s){ stack<char> st; string result = ""; for(int i=0;i<s.length();i++){ char c=s[i]; // If the scanned character is an operand, add it to output. if(isalnum(c)) result += c; // Else if the scanned character is an ‘(‘, push it to the stack. else if(c=='(') st.push('('); // If the scanned character is an ‘)’, pop and append from the stack // until an ‘(‘ is encountered. else if(c==')'){ while(st.top()!='('){ result+=st.top(); st.pop(); } st.pop(); } // An operator is encountered else{ while(!st.empty() && getPrecedence(s[i]) <= getPrecedence(st.top())){ result += st.top(); st.pop(); } st.push(c); } } // Pop all remaining elements in the stack while(!st.empty()){ result += st.top(); st.pop(); } cout << "The Postfix expression is : "<<result<<endl; } ``` 这段程序实现了基本的功能,能够处理包含加减乘除以及括号在内的标准四则运算表达式,并将其转换为对应的后缀表达式输出。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值