博客
关于我
150. 逆波兰表达式求值 (栈)
阅读量:376 次
发布时间:2019-03-05

本文共 986 字,大约阅读时间需要 3 分钟。

分析

本题与计算器那道题的区别在于表达式的形式。

本题是后缀表达式,不需要额外的处理,可以直接让两个数字出栈进行运算。
而计算器那道题是中缀表达式,需要对符号的优先级进行判断。

C++ 代码

class Solution {public:    stack
stk1; // 只需一个数字栈即可 bool dg(char c) { // 判断是否为合法数字 return (c >= '0' && c <= '9'); } int getc(string c) { // 判断符号类型 if (c == "+") return 1; if (c == "-") return 2; if (c == "*") return 3; return 4; } int evalRPN(vector
&s) { int n = s.size(); for (int i = 0; i < n; ++i) { if (dg(s[i][0]) || (s[i].size() > 1 && s[i][0] == '-')) { // 数字或负数 stk1.push(stoi(s[i])); } else { // 运算符 int a = stk1.top(); stk1.pop(); int b = stk1.top(); stk1.pop(); int c = getc(s[i]); if (c == 1) b += a; if (c == 2) b -= a; if (c == 3) b *= a; if (c == 4) b /= a; stk1.push(b); } } return stk1.top(); // 结果在栈顶 }};

转载地址:http://poag.baihongyu.com/

你可能感兴趣的文章
node~ http缓存
查看>>
node不是内部命令时配置node环境变量
查看>>
node中fs模块之文件操作
查看>>
Node中同步与异步的方式读取文件
查看>>
Node中的Http模块和Url模块的使用
查看>>
Node中自启动工具supervisor的使用
查看>>
Node入门之创建第一个HelloNode
查看>>
node全局对象 文件系统
查看>>
Node出错导致运行崩溃的解决方案
查看>>
Node响应中文时解决乱码问题
查看>>
node基础(二)_模块以及处理乱码问题
查看>>
node安装卸载linux,Linux运维知识之linux 卸载安装node npm
查看>>
node安装及配置之windows版
查看>>
Node实现小爬虫
查看>>
Node提示:error code Z_BUF_ERROR,error error -5,error zlib:unexpected end of file
查看>>
Node提示:npm does not support Node.js v12.16.3
查看>>
Node搭建静态资源服务器时后缀名与响应头映射关系的Json文件
查看>>
Node服务在断开SSH后停止运行解决方案(创建守护进程)
查看>>
node模块化
查看>>
node模块的本质
查看>>