0
点赞
收藏
分享

微信扫一扫

逆波兰式和波兰式


中缀表达式,前缀表达式(波兰式),后缀表达式(逆波兰式)

中缀表达式就是我们常用的形式:1+2*6+1
前缀表达式从右往左扫描,后缀表达式就是从左往右扫描
作用:实现逆波兰式的算法,难度并不大,但为什么要将看似简单的中缀表达式转换为复杂的逆波兰式?原因就在于这个简单是相对人类的思维结构来说的,对计算机而言中序表达式是非常复杂的结构。相对的,逆波兰式在计算机看来却是比较简单易懂的结构。因为计算机普遍采用的内存结构是栈式结构,它执行先进后出的顺序

此处简要说明一下中缀表达式(原式)转后缀表达式(逆波兰式)的方法。

构建一个栈,遵循如下规则:

  • 依次扫描,如果是数字,输出到序列;如果是运算符,入栈
  • 如果运算符优先级大于栈中优先级,出栈直到栈中优先级均小于运算符,再把运算符入栈,如果是括号,则找到反括号出栈为止

/*************************************************************************
> File Name: pp.cpp
> Author: liuhao
> Mail: 2226958871@qq.com
> Created Time: Sun 13 Jun 2021 08:55:41 PM CST
************************************************************************/

#include <iostream>
#include <stack>
#include <string>
#include <cctype>

std::string bolan();
int getdata(char);
int getnum(std::string);

int main() {
std::string str = bolan();
int n = getnum(str);
std::cout << n << std::endl;
return 0;
}

int getdata(char s) {
if (s == '*' || s == '/') {
return 1;
}
else if (s == '+' || s == '-') {
return 0;
}
return -1;
}

std::string bolan() {
using std::cout, std::endl, std::cin, std::string, \
std::stack;
string input_str;
cin >> input_str;
string output_str;
int n = 1;
stack<char> s_operator;
for (int i = 0; i < input_str.size(); ++i) {
if (isdigit(input_str[i])) {
output_str.push_back(input_str[i]);
}
else {
if (!s_operator.empty()) {
while (!s_operator.empty() && (getdata(s_operator.top()) >= getdata(input_str[i]))) {
output_str.push_back(s_operator.top());
s_operator.pop();
}
}
else {
n += 1;
}
s_operator.push(input_str[i]);
}
}
while (!s_operator.empty()) {
char a = s_operator.top();
s_operator.pop();
output_str.push_back(a);
}
return output_str;
}

int getnum(std::string str) {
std::stack<int> s_num;
for (int i = 0; i < str.size(); ++i) {
if (isdigit(str[i])) {
s_num.push(str[i] - '0');
}
else {
int f1 = s_num.top();
s_num.pop();
int f2 = s_num.top();
s_num.pop();
int num;
if (str[i] == '*') {
num = f1*f2;
}
else if (str[i] == '-') {
num = f1-f2;
}
else if (str[i] == '+') {
num = f1+f2;
}
else if (str[i] == '/') {
num = f1/f2;
}
s_num.push(num);
}
}
return s_num.top();
}

逆波兰式和波兰式_数据结构


举报

相关推荐

0 条评论