Saturday, April 9, 2016

Postfix evaluation using stack algorithm with example


Postfix evaluation:

Algorithm:


1.       Scan the postfix expression P from the left to right.
2.       Initialize an empty stack or NULL stack.
3.       Repeat step 4 and 5 until all characters in P are scanned.
4.       If the scanned character is operator push it to the stack.
5.       If the scanned character is an operand then à
a.       Remove top two elements from the stack
b.       Evaluate two removes elements result using the scanned operand and push the result to the stack.
6.       Finally the result of the stack is the evaluation of the postfix expression.

Example:

 Say the postfix expression is : P = 562 +* 124/-

Scanned Character
Stack
5
6
2
+
*
12
4
/
-

5
56
562
58
40
4012
40124
403
37



So the result of the postfix evaluation is: 37 which is the top element of the stack now





If you face any problem in this example, please comment below.



9 comments:

  1. How to recognize that in given expression there is 124 it is 12,4 and not 1,2,4 as no space is given between digits

    ReplyDelete
    Replies
    1. This comment has been removed by the author.

      Delete
    2. If no space is given then there is no way to understand. We will push each digit individually. If space is given then we will follow the space.

      Delete
  2. correction if 5 is a one number it must be push(5) index0, push(6) index1,push(2)index2 with preceding indeces am i right?

    ReplyDelete