ZBLOG

c++代码实现栈--中缀转后缀表达式 表达式有三种表示方法,分别为: 前缀表示式:把运算符写在操作数之前,即运算符+操作数1+操作数2 中缀表示式:把运算符写在操作数之间,即操作数1+运算符+操作数2 后缀表示式:把运算符写在操作数之后,即操作数1+操作数2+运算符 例如:a+b*(c-d)-e/f 前缀表示式:-+a*b-cd/ef 中缀表示式:a+b*(c-d)-e/f 后缀表示式:abcd-*+ef/- 前缀表达式和后缀表达式与相应的中缀表达式的操作次序相同,但是没有...

以下是使用C++实现将中缀表达式转换为后缀表达式的代码:

  1. #include <iostream>
  2. #include <stack>
  3. #include <string>
  4. using namespace std;
  5. int getPriority(char op) {
  6. if (op == '+' || op == '-')
  7. return 1;
  8. else if (op == '*' || op == '/')
  9. return 2;
  10. return 0;
  11. }
  12. string infixToPostfix(string expression) {
  13. stack<char> operators;
  14. string postfix = "";
  15. for (int i = 0; i < expression.length(); i++) {
  16. char ch = expression[i];
  17. // 忽略空格
  18. if (ch == ' ')
  19. continue;
  20. // 操作数直接加入后缀表达式中
  21. if (isalnum(ch))
  22. postfix += ch;
  23. // 左括号直接入栈
  24. else if (ch == '(')
  25. operators.push(ch);
  26. // 右括号将栈内运算符弹出并加入到后缀表达式中,直到遇到左括号
  27. else if (ch == ')') {
  28. while (!operators.empty() && operators.top() != '(') {
  29. postfix += operators.top();
  30. operators.pop();
  31. }
  32. // 弹出左括号
  33. operators.pop();
  34. }
  35. // 运算符处理逻辑
  36. else {
  37. while (!operators.empty() && getPriority(ch) <= getPriority(operators.top())) {
  38. postfix += operators.top();
  39. operators.pop();
  40. }
  41. operators.push(ch);
  42. }
  43. }
  44. // 将栈内剩余运算符弹出并加入到后缀表达式中
  45. while (!operators.empty()) {
  46. postfix += operators.top();
  47. operators.pop();
  48. }
  49. return postfix;
  50. }
  51. float evaluatePostfix(string postfix) {
  52. stack<float> operands;
  53. for (int i = 0; i < postfix.length(); i++) {
  54. char ch = postfix[i];
  55. // 操作数入栈
  56. if (isdigit(ch)) {
  57. operands.push(ch - '0');
  58. }
  59. // 运算符处理逻辑
  60. else {
  61. float operand2 = operands.top();
  62. operands.pop();
  63. float operand1 = operands.top();
  64. operands.pop();
  65. switch (ch) {
  66. case '+':
  67. operands.push(operand1 + operand2);
  68. break;
  69. case '-':
  70. operands.push(operand1 - operand2);
  71. break;
  72. case '*':
  73. operands.push(operand1 * operand2);
  74. break;
  75. case '/':
  76. operands.push(operand1 / operand2);
  77. break;
  78. default:
  79. cout << "无效的运算符" << endl;
  80. return 0.0f;
  81. }
  82. }
  83. }
  84. // 返回最终结果
  85. return operands.top();
  86. }
  87. int main() {
  88. string expression;
  89. getline(cin, expression, '#');
  90. string postfix = infixToPostfix(expression);
  91. cout << "转换的后缀表达式为:" << postfix << endl;
  92. float result = evaluatePostfix(postfix);
  93. cout << "计算结果为:" << result << endl;
  94. return 0;
  95. }

注意,上述代码假定输入的中缀表达式是有效的,并且只包含加法、减法、乘法和除法运算符。对于其他类型的运算符或者更复杂的表达式,可能需要进行适当的修改。


内容由零声教学AI助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=10374

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?