Calculate The Infix Expression With Stack

本篇概述下运用栈(stack),将中缀表达式(postfix expression)转换成后缀表达式(infix expression),并运算结果。

  1 // 对string数式的计算(基于中缀转后缀).cpp : 定义控制台应用程序的入口点。
  2 //
  3
  4 #include "stdafx.h"
  5 #include <string>
  6 #include <stack>
  7 #include <cctype>
  8 #include <iostream>
  9
 10 //计算后缀表达式。(int类型)
 11 int postfixExp(const std::string& exp)
 12 {
 13     std::stack<int> numSta;
 14     for (int i = 0; i != exp.size(); i++)
 15     {
 16         //将表达式中的数字压入栈中
 17         std::string num;
 18         while (isdigit(exp[i]))
 19         {
 20             num.push_back(exp[i]);
 21             i++;
 22         }
 23
 24         if (!num.empty())  numSta.push(atoi(num.c_str()));
 25
 26         //遇到空格继续迭代
 27         if (exp[i] == ‘ ‘) continue;
 28
 29         //遇到操作符将栈顶的两个元素弹出并将计算结果压入栈中
 30         if (exp[i] == ‘+‘ || exp[i] == ‘-‘ || exp[i] == ‘*‘ || exp[i] == ‘/‘)
 31         {
 32             int num1;
 33             int num2;
 34             if (!numSta.empty())
 35             {
 36                 num1 = numSta.top();
 37                 numSta.pop();
 38             }
 39             if (!numSta.empty())
 40             {
 41                 num2 = numSta.top();
 42                 numSta.pop();
 43             }
 44             //计算
 45             switch (exp[i])
 46             {
 47             case ‘+‘: numSta.push(num1 + num2);
 48                 break;
 49             case ‘-‘: numSta.push(num1 - num2);
 50                 break;
 51             case ‘*‘: numSta.push(num1 * num2);
 52                 break;
 53             case ‘/‘: numSta.push(num1 / num2);
 54                 break;
 55             default:
 56                 break;
 57             }
 58         }
 59
 60     }
 61     return numSta.top();
 62 }
 63
 64 //中缀转后缀 e.g. 2 + 3 * 5 + (7 * 8  + 9) * 10 ->  2 3 5 * + 7 8 * 9 + 10 * +
 65 std::string postfixToInfix(const std::string& exp)
 66 {
 67     std::string result;
 68     std::stack<char> operators;
 69     for (int i = 0; i < exp.size(); i++)
 70     {
 71         while (isdigit(exp[i]))
 72         {
 73             result.push_back(exp[i]);
 74             i++;
 75         }
 76         //若末尾数字非个位数,数组索引将越界,由于string不是真正意义上的字符数组,越界对结果没有影响
 77         //if (i >= exp.size()) break;
 78         //添加空格分隔符
 79         result.push_back(‘ ‘);
 80         //遇到空格继续迭代
 81         if (exp[i] == ‘ ‘) continue;
 82         //遇到操作符时,检查栈顶元素优先级,若为高优先级/等优先级操作符,弹出栈中操作符,完成后将表达式的操作符压入
 83         if (exp[i] == ‘+‘ || exp[i] == ‘-‘)
 84         {
 85             while (!operators.empty() && operators.top() != ‘(‘)
 86             {
 87                 //当栈顶元素为 + - * / 时 , ( 在栈中优先级最低,在表达式中优先级最高
 88                     result.push_back(operators.top());
 89                     operators.pop();
 90                     result.push_back(‘ ‘);
 91             }
 92             operators.push(exp[i]);
 93         }
 94         else if (exp[i] == ‘*‘ || exp[i] == ‘/‘)
 95         {
 96             while (!operators.empty() && (operators.top() == ‘*‘ || operators.top() == ‘/‘))
 97             {
 98                 //if (operators.top() == ‘*‘ || operators.top() == ‘/‘)
 99                     result.push_back(operators.top());
100                     operators.pop();
101                     result.push_back(‘ ‘);
102             }
103             operators.push(exp[i]);
104         }
105         else if (exp[i] == ‘(‘) operators.push(‘(‘);
106         else if (exp[i] == ‘)‘)
107         {
108             while (operators.top() != ‘(‘)
109             {
110                 result.push_back(operators.top());
111                 operators.pop();
112                 result.push_back(‘ ‘);
113             }
114             //弹出 (
115             operators.pop();
116         }
117
118     }
119     while (!operators.empty())
120     {
121         result.push_back(operators.top());
122         result.push_back(‘ ‘);
123         operators.pop();
124     }
125
126     return result;
127 }
128
129 int main()
130 {
131     std::cout << postfixExp(postfixToInfix("2 + 3 * 5 + (7 * 8  + 9) * 10")) << std::endl;
132      system("pause");
133     return 0;
134 }
时间: 2024-10-12 17:50:00

Calculate The Infix Expression With Stack的相关文章

Infix Expression Calculation

This program provides another two cases of the application of Stack besides what I have mentioned in a previous article: (1) Class InfixExpr converts an Infix Expression to a Suffix Expression by using an operator stack; (2) Class Suffix calculates t

1130. Infix Expression (25)

Given a syntax tree (binary), you are supposed to output the corresponding infix expression, with parentheses reflecting the precedences of the operators. Input Specification: Each input file contains one test case. For each case, the first line give

PAT甲题题解-1130. Infix Expression (25)-中序遍历

博主欢迎转载,但请给出本文链接,我尊重你,你尊重我,谢谢~http://www.cnblogs.com/chenxiwenruo/p/6789828.html特别不喜欢那些随便转载别人的原创文章又不给出链接的所以不准偷偷复制博主的博客噢~~ 水,中序遍历输出即可注意除根节点.叶子节点外,都需要有括号括起来 #include <iostream> #include <cstdio> #include <algorithm> #include <string>

1130 Infix Expression

题意:给出一个语法树(二叉树),输出相应的中缀表达式. 思路:很显然,通过中序遍历来做.通过观察,发现除了根结点之外的所有非叶结点的两侧都要输出括号,故在中序遍历时判断一下即可. 代码: #include <cstdio> #include <cstring> struct Node{ char data[15]; int left,right; }Tree[25]; int root=1;//根结点 void inOrderTraversal(int v) { if(v!=-1)

[算法专题] stack

1. Convert Expression to Reverse Polish Notation http://www.lintcode.com/en/problem/convert-expression-to-polish-notation/ Given an expression string array, return the Polish notation of this expression. (remove the parentheses) Example For the expre

Leetcode: Ternary Expression Parser

Given a string representing arbitrarily nested ternary expressions, calculate the result of the expression. You can always assume that the given expression is valid and only consists of digits 0-9, ?, :, T and F (T and F represent True and False resp

C++用后缀表达式(逆波兰)求四则表达式值,采用STL中的stack

简介: 20 世纪50 年代, 波兰逻辑学家JanLukasiewicz ,想到了一种不需要括号的后缀表达法,我们也把它称为逆波兰( Reverse Polish Notation, RPN) 表示,对于"如9 + (3 -1 ) X3 +10-/2 " ,如果要用后缀表示法应该是: "9 3 1-3*+10 2 / + " ,这样的表达式称为后缀表达式. 中缀表达式转后缀表达式规则: 从左到右遍历中缀表达式的每个数字和符号,若是数字就输出,即成为后缀表达式的一部分

数据接口复习 3 stack and queue

stack: 1.top and bottom.统一在top端增加和删除. Attention: 函数 delete(x) 是将top端的元素删除并且赋值给x 实现:通过linked list实现 . public class StackLi { public StackLi( ){ topOfStack = null; } public boolean isFull( ){ return false; } public boolean isEmpty( ){ return topOfStack

Basic Calculator - Stack(表达式计算器)

978. Basic Calculator https://www.lintcode.com/problem/basic-calculator/description public class Solution { /** * @param s: the given expression * @return: the result of expression */ public int calculate(String s) { // Write your code here Stack<Int