Why do we have to reverse the string when converting from infix to prefix

梦想的初衷 提交于 2019-12-08 08:12:39

问题


In the first step itself of converting an infix to prefix can someone explain in simple terms why should we reverse the string? Is there any alternative method to convert?


回答1:


Yes, you are absolutely right that if you have to convert infix to prefix then you have to scan the string from right to left.

Why not from left to right?

If you scan from left to right then you will require future knowledge of operators in the string.

Example 1 :

Infix  : 2+3
Prefix : +23

Now, when you convert it from left to right then you should have the knowledge of + that is yet to appear in the string. This looks simple in this particular example, now consider another example given below.

Example 2:

Infix  : 2+3*4/5-6*7
Prefix : -+2/*345*67

Now, if you scan from left to right then when you scan 0th index of string then the program should have knowledge of - which is going to appear in 7th index of string which could be a hectic job.

So the safest way to do is to scan the string from right to left.



来源:https://stackoverflow.com/questions/23942225/why-do-we-have-to-reverse-the-string-when-converting-from-infix-to-prefix

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!