Why do we have to reverse the string when converti

2019-06-04 06:09发布

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条回答
可以哭但决不认输i
2楼-- · 2019-06-04 07:00

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.

查看更多
登录 后发表回答