Search code examples
javastackpostfix-notation

ArrayStack: getting wrong output on implementation


The program in java is to evaluate the post-fix arithmetic expression. I am not getting any error in my program but I am getting the wrong output.

I am trying to evaluate the expression (1*(((2+3)*(4-5))+6)) where its result is 1. But I am getting the output as 11. Its post-fix expression is 1 2 3 + 4 5 - * 6 + *

Looking forward for your help. Thank you!!

public static void evaluatePostfix(String sol)
{

    ArrayStack<Double> nlist = new ArrayStack<Double> ();
    double op1, op2, result;
    char ch;



    for (int i = 0; i < sol.length(); i++)
    {    

         if ('0' <= sol.charAt(i) && sol.charAt(i) <= '9')
            nlist.push((double)(sol.charAt(i) - '0'));
        else

          if (sol.charAt(i)=='+'||sol.charAt(i)=='-'||sol.charAt(i)=='*'||sol.charAt(i)=='/') 
        {

            op1 = nlist.pop();
                op2 = nlist.pop();
            ch = sol.charAt(i);

        switch(ch){
            case '+':
                nlist.push(op1 + op2);  
                break;  
            case '-':
                nlist.push(op1 - op2);      
                break;  
            case '*':
                nlist.push(op1 * op2);      
                break;  
            case '/':
                nlist.push(op1 / op2);      
                break;  
            default:nlist.push(0.000);  
            }           
           }                    
      }
    result = nlist.pop();
    System.out.println(result);
   }

Solution

  • When you pop from the stack, op2 is the element at the top and op1 is at top-1. Change it to:

    op2 = nlist.pop();
    op1 = nlist.pop();
    


    To be more clear if your postfix expression is 56 - (so 5-6 in infix) your stack is

    | 6 |
    | 5 |
    

    and when you get the - you are doing nlist.push(op1 - op2); which pushes 6-5 into the stack while you should push 5-6.