Why do we have to reverse the string when converti

2019-06-04 06: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.