Evaluate postfix expression 3 2 ↑ 5 4 3 ↑ * + 18 9 / - using stack.


Evaluate the postfix expression 3 2 5 4 3 * + 18 9 / -    using stack.

Write each step of this evaluation using the following table. 

Input

Op1

Op2

Value

Stack

 

 

 

 

 

 








Input

Op1

Op2

Value

Stack

3

 

 

 

3

 

 

 

2

 

 

 

3

2

 

 

3

2

9

9

 

 

 

5

3

2

9

9

5

 

 

4

3

2

9

9

5

4

 

3

3

2

9

9

5

4

3

4

3

64

9

5

64

 

*

5

64

320

9

320

 

 

+

9

320

329

329

 

 

 

18

9

320

329

329

18

 

 

9

9

320

329

329

18

9

 

/

18

9

2

329

2

 

 

-

329

2

327

327

 

 

 

Postfix Expression Evaluation Result is:  327

Rules/Algorithm

Ø Each operator in a postfix expression refers to the previous two operands.

Ø Each time we read an operand, we push it on a stack.

Ø When we reach an operator, we pop the two operands from the top of the stack, apply the operator and push the result back on the stack.

Evaluating Postfix Algorithm:

Stack s;
while( not end of input ) {
e = get next element of input
if( e is an operand )
s.push( e );
else {
op2 = s.pop();
op1 = s.pop();
value = result of applying operator ‘e’ to op1 and op2;
s.push( value );
}
}

finalresult = s.pop();

                       Thank you                  


Comments