为调车场算法处理一元减号 [英] handling unary minus for shunting-yard algorithm

查看:120
本文介绍了为调车场算法处理一元减号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在将中缀表达式转换为后缀表达式时,是否有更好的方法来处理一元-?

Is there a better way to handle unary "-" in converting a infix expression to a postfix one?

显而易见的是在每个一元-之前加上前缀0。有人知道更好的实现吗?谢谢!

The obvious one would be prefix every unary "-" with a 0. Does anyone know better implementation? Thanks!

推荐答案

我几年前的方式是为我的后缀表达式发明了一个新的运算符。因此,当我在前缀中遇到一元减号时,我会将其转换为。所以我的 a + -b 的后缀变成了 ab#+

The way I did this years ago was invent a new operator for my postfix expression. So when I encountered a unary minus in the infix, I'd convert it to #. So my postfix for a + -b became ab#+.

当然,我的评估者必须知道仅弹出一个操作数。

And, of course, my evaluator had to know that # only popped one operand.

种类的大小取决于构建后缀表达式的方式。如果要显示它,则特殊的运算符可能会使人们感到困惑。但是,如果您只是在内部使用(我曾经使用过),那么它会很好用。

Kind of depends on how you're using the postfix expression once it's built. If you want to display it then your special # operator would probably confuse people. But if you're just using it internally (which I was), then it works great.

这篇关于为调车场算法处理一元减号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆