Why this program giving ambiguous output?

Sample Input: ((A+B)*C-D)*E

Program Link : link

Problem : Infix to Postfix Expression

Please give me a few minutes to take a look at your code and I will get back to you.

Hey @raghav6 your code is throwing segmentation fault. Please make this change in line 37

if(!st.empty()&&precedence(infix[i])<=precedence(st.top())){

You were trying to access st.top() even when stack was empty.

but I’ve already applied a check before, if(!st.empty()&&precedence(infix[i])<=precedence(st.top())){

And it isn’t the case which I was talking about, I was getting (( after the answer, I can’t figure it out where it is coming from.

You still need to make this check irrespective of previous one here because this is in the else part.

Ok, but why am I getting ambiguous output?

You are getting (( because you aren’t popping it from the stack in the first place and simply adding it to your postfix string , so in that loop after line 33 add another st.pop().
Also in your line 37 it has to be be a while loop instead of a simple ‘if’, along with the check that stack is not empty.

Can you modify my code and share the link? :sweat_smile:

I know I should’ve done, it but adding that giving me segmentation fault

Here’s https://ide.codingblocks.com/s/184609 what I tried.

Sure ,here you go https://ide.codingblocks.com/s/184610, this is your initial code that i have modified.
I hope i have cleared all your doubts ,so please mark the doubt as resolved.

Why did you check if if(st.size()) st.pop(); you could’ve used if(st.top()=='(') st.pop();

It might fail if there’s no opening bracket in the beginning

It’s the same situation anyway. The only time we are getting out of the loop is when we encounter the opening bracket,otherwise we simply keep popping the elements. Yeah to be on a safer side you can use the condition you just mentioned but just looking at the logic one can deduce that remaining element has to be ‘(’ in the stack.

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.

1 Like