中缀表达式和后缀表达式
中缀表达式就是我们平常写的算式,符合人的阅读和理解习惯。
后缀表达式也叫逆波兰表达式,符合计算机的处理习惯。
后缀表达式的计算
给出一个后缀表达式,我们应该如何计算呢?
主要利用了栈这个数据结构来计算后缀表达式,具体思路:从左往右遍历表达式,遇到数字就直接压栈,遇到运算符就从栈里弹出两个数,假设先弹出a,再弹出b,把a放到运算符右侧,b放到运算符左侧,计算结果,并把结果压栈。重复上述过程,直到遍历完整个后缀表达式。
下面看一道例题:
若a=10,b=4,c=6,d=4,e=15,计算后缀表达式ab*cd+-e+的结果
遍历表达式,往栈中压入ab,遇到*号,从栈中取出ab计算得40并将40压入栈中。按照上述思路计算结果得45。
中缀表达式转后缀表达式
从左到右遍历中缀表达式,按照以下规则进行转换:
- 如果取出的是数字,直接追加到后缀表达式中
- 如果取出的是左括号,将其压栈,此时左括号优先级最低
- 如果取出的是右括号,从栈中弹出元素追加到后缀表达式,直到弹出左括号(左括号弹出但不追加到结果中)
- 如果取出的是运算符
- 若栈为空,直接入栈
- 若栈不为空,比较栈顶运算符和该运算符的优先级
- 若前者小于后者,后者入栈
- 若前者大于后者,不断出栈并追加到后缀表达式中,直到前者小于后者,或栈为空,此时后者入栈
按照上述规则进行转换,直到遍历完整个中缀表达式,同时检查栈是否为空,若栈不为空,将栈中所有元素弹出到后缀表达式中,返回。
#include <iostream>
#include <string>
#include <vector>
#include <stack>
#include <cctype>
int compare(std::string op)
{
if (op == "+" || op == "-") return 1;
if (op == "*" || op == "/") return 2;
return 0;
}
std::vector<std::string> midToPost(const std::vector<std::string>& infix)
{
std::vector<std::string> ans;
std::stack<std::string> st;
for (std::string key : infix)
{
if (isalnum(key[0])) ans.push_back(key);
else if (key == "(") st.push(key);
else if (key == ")")
{
while (!st.empty() && st.top() != "(")
{
ans.push_back(st.top());
st.pop();
}
if (!st.empty() && st.top() == "(") st.pop();
}
else //运算符处理
{
while (!st.empty() && compare(st.top()) >= compare(key))
{
ans.push_back(st.top());
st.pop();
}
st.push(key);
}
}
while (!st.empty())
{
ans.push_back(st.top());
st.pop();
}
return ans;
}
12万+

被折叠的 条评论
为什么被折叠?



