微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c – 如何为“(1 3 *(5/4))”等字符串编写求值器,并获得数字结果

这是一个面试问题
我对它的解决方案感到困惑,我想我需要堆栈来推送和弹出这些操作符和操作数,
但是我需要两个堆栈,一个用于运算符,一个用于操作数?或者只是一个堆栈?我认为我们需要两个堆栈,但是有什么办法可以解决使用一个堆栈?

我也有点困惑,这将如何工作,每次我得到一个运算符,我会弹出两个我最高的操作数,并推动结果在操作数堆栈

首选的是括号,然后是分,多,最后的减法,然后加法

但是如何检查何时弹出两个操作数并进行必要的操作操作?

解决方法

看看 shunting yard algorithm.

The shunting yard algorithm is a method for parsing mathematical equations specified in infix notation. It can be used to produce output in Reverse Polish notation (rpn) or as an abstract Syntax tree (AST). The algorithm was invented by Edsger Dijkstra and named the “shunting yard” algorithm because its operation resembles that of a railroad shunting yard.

原文地址:https://www.jb51.cc/c/113388.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐