100行以内C++代码实现逆波兰式

逆波兰式(Reverse Polish notation,RPN,或逆波兰记法),也叫后缀表达式(将运算符写在操作数之后)。

算术表达式转逆波兰式例子:

逆波兰式整体的算法流程图如下:

下面给出我基于C++ 语言对逆波兰式算法的实现代码,值得注意的是:

1、算法中对操作数,仅支持一个字符的字母或数字的操作数,如:x,y,j,k,3,7等;如果要支持多个字符的操作数,如:var1,等。需要读者自己扩展对算术表达式操作数的分词部分的代码。

2、为了为了增加转换后的逆波兰表达式的可读性,我在每个操作数和操作符输出时后面追加了一个空格。

代码如下:


/// file:
#include <string>
#include <stack>class ReversePolishNotation {
private:std::string _expr;unsigned _idx;std::stack<std::string> _stk;
public:ReversePolishNotation(const std::string &expr);std::string nextWord();std::string operator()();static int getOpPriority(const std::string &word);bool isWord(const std::string &word);bool isOperator(const std::string &word);
};


/// file: ReversePolishNotation.cpp
#include <iostream>
#include <cassert>
#include ""
#include <cctype>
#include <sstream>using std::cout;
using std::endl;ReversePolishNotation::ReversePolishNotation(const std::string &expr) : _idx(0), _expr(expr) {}std::string ReversePolishNotation::nextWord() {if (_idx >= ()) {return "";}return _expr.substr(_idx++, 1);
}std::string ReversePolishNotation::operator()() {std::stringstream outExpr;std::string word;std::string topElem;while (true) {word = nextWord();if (isWord(word)) {outExpr << word << " ";} else if (isOperator(word)) {if (() || () == "(") {(word);continue;}topElem = ();while (getOpPriority(topElem) > getOpPriority(word)) {outExpr << topElem << " ";();if (()) {break;}topElem = ();}(word);} else if (word == "(") {(word);} else if (word == ")") {while (true) {topElem = ();();if (topElem == "(") {break;}assert(!() && "[E]Expr error. Missing '('.");outExpr << topElem << " ";}} else if (word == "") {while (!()) {topElem = ();assert (topElem != "(" && "[E]Expr error. Redundant '('.");outExpr << topElem << " ";();}break;} else {assert(false && "[W]>>>Can not recognize this word");}}return outExpr.str();
}int ReversePolishNotation::getOpPriority(const std::string &word) {if (word == "+") { return 1; }if (word == "-") { return 1; }if (word == "*") { return 2; }if (word == "/") { return 2; }return 0;
}bool ReversePolishNotation::isWord(const std::string &word) {return isalpha(()[0]) || isdigit(()[0]);
}bool ReversePolishNotation::isOperator(const std::string &word) {return word == "+" ||word == "-" ||word == "*" ||word == "/";
}/// ---测试代码---
int main() {assert(ReversePolishNotation("a+b*c")() == "a b c * + ");assert(ReversePolishNotation("(a+b)*c-(a+b)/e")() == "a b + c * a b + e / - ");assert(ReversePolishNotation("3*(2-(5+1))")() == "3 2 5 1 + - * ");
// assert(ReversePolishNotation("3*((2-(5+1))")() == "3 2 5 1 + - * "); // Failed Case: Redundant '('
// assert(ReversePolishNotation("3*(?2-(5+1))")() == "3 2 5 1 + - * "); // Failed Case: Can not recognize '?'return 0;
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

c语言int 转bool_C++代码实现逆波兰式_C 语言相关推荐

  1. 《编译原理》一道关于逆波兰式的作业题(学委推导出了逆波兰式的数学公式表示)

    考虑下面的上下文无关文法:考虑下面的上下文无关文法:考虑下面的上下文无关文法: S→SS∗∣SS+∣aS → SS* \; | \; SS+ \; | \; aS→SS∗∣SS+∣a (1).表明通过 ...

  2. C语言编程对一个逆波兰式进行求值,算式与逆波兰式

    致憨憨的从前 当年,老师布置一道作业:编写一个计算器,要求输入算式,给出结果.算式中只包含+-*/^这几个运算符,算式中不含负数.由于是Python课程,我很快给出了解题方式,如下: while Tr ...

  3. 【C语言】算法学习·逆波兰式

    目录 逆波兰式 算法定义 算法作用 算法实现 计算方法 算法举例 算法图示 程序实现 二叉树法 逆波兰式 算法定义 一个表达式E的后缀形式可以如下定义: (1)如果E是一个变量或常量,则E的后缀式是E ...

  4. c语言数据结构逆波兰算法,[分享]表达式二叉树逆波兰式的转换程序源代码(C++)...

    [分享]表达式二叉树逆波兰式的转换程序源代码(C++) RT,这是我两年前学数据结构时的作品. 拿出来给大家分享. ps:当时才学C++,代码写的不好,见笑了./*将中缀式转换为表达式树,并打印逆波兰 ...

  5. c语言逆波兰式算法,c语言 逆波兰式输入 计算器程序

    #include #include #include #define MAXOP 100 #define NUMBER '0' int getop(char []) ; void push(doubl ...

  6. 使用栈解决的一类经典问题:表达式转换及求值;中缀表达式;前缀表达式,后缀表达式,中缀转前缀;中缀转后缀;后缀表达式求值;波兰式,逆波兰式

    文章目录 背景知识 表达式转换问题(考研经典) 一:手工转换 (1)中缀转前缀和中缀转后缀 (2)前缀转中缀和后缀转中缀 二:用栈实现表达式转换 (1)中缀转后缀 (2)中缀转前缀 表达式计算问题(使 ...

  7. 编译原理实验二-逆波兰式生成程序

    一.实验目的和要求: 1. 掌握语法分析的基本思想,并用高级语言编写逆波兰式生成程序 2. 要求利用逆波兰式生成算法编写程序,将从键盘上输入的算术表达式 (中缀表达式)转化成逆波兰式 二.实验平台: ...

  8. 中缀表达式转换成逆波兰式

    栈的应用:中缀表达式转换成逆波兰式 小白前来报道!懒癌患者的第一篇博客,实属不易,先为自己鼓个掌. 编写程序,将任意一个合法的中缀表达式转换成逆波兰式. [问题描述]表达式计算是实现程序设计语言的基本 ...

  9. php逆波兰表达式,PHP根据数字的字符表达式计算出结果(转换成逆波兰式再求解)[转]...

    这个简单的计算器采用的是逆波兰式来做的,仅支持加减乘除四种运算,纯粹个人练习记录一下,还望多多支持. 用法 require 'Calc.php'; $calc = new Calc('(1+9)/2' ...

最新文章

  1. 关于android.view.WindowLeaked(窗体泄露)的解决方案
  2. 第十六周程序阅读(8)
  3. android开发之当设置textview多少字后以省略号显示。限制TextView的字数
  4. 二、linux最小驱动
  5. node n 切换node版本失败_记一次 node-sass@4.x 安装失败
  6. mysql用户数据导入_mysql创建数据库、用户及导入数据_mysql数据库教程
  7. 小哥送一单外卖应该拿多少钱?
  8. [LintCode] Reverse Pairs 翻转对
  9. 测试自动化金字塔在软件开发中是如何使用的?
  10. std::thread的常用参数传递总结
  11. 最小倍约数c语言,求助C语言求最大公约数和最小公倍数
  12. 生鲜配送小程序源码_ThinkPHP社区水果生鲜蔬菜同城配送服务平台 社区团购商城小程序源码...
  13. Windows10桌面美化合集(壁纸+任务栏+资源管理器)
  14. 信息学奥赛一本通(c++):1336:【例3-1】找树根和孩子
  15. 云计算及其支撑技术简介
  16. Python爬虫入门教程 19-100 51CTO学院IT技术课程抓取
  17. hexo 利用 Markdown 语法画 mermaid 流程图
  18. 为什么正态分布如此常见?
  19. SpringCould整合oauth2
  20. linux打开共享文件

热门文章

  1. b站在线解析_这款游戏被全B站所唾弃,每个月却依然有5000万玩家坚持在线?!...
  2. Pytorch RNN(详解RNN+torch.nn.RNN()实现)
  3. Endnote生成的中英文混排参考文献中“等”与“et al”的处理
  4. asp获取mysql数据报错_ASP.NET在删除掉数据库文件后报错处理
  5. 产品经理思维模型:产品生命周期
  6. 伪命题:我们来谈谈校招生起薪的问题,它对你来说重要吗?
  7. 滑动窗口限流 java_Spring Boot 的接口限流算法优缺点深度分析
  8. byte数组转为string_String类
  9. java 获取oracle mysql sqlserver 链接 connection
  10. 解决关于 ionic3 启动白屏 控制台错误提示:Uncaught SyntaxError Use of const in strict mode.