Dealing with expressions using stack

Infix to Postfix conversion

Example –
Infix: a+b*c+d
Postfix: abc*d++

Algorithm:

Read one element at a time from left to right. Use stack for dealing with operators.

  1. If element is a operand, print the output.
  2. If the element is a operator,
    1. If stack is empty, push the operator to stack.
    2. If stack not empty, check the precedence with the one in the top of the stack.
      1. If the precedence of the read operator is greater, push it to the stack.
      2. If the precedence of the read operator is less than the elements in the top of the stack, keep popping and printing from stack untill an operator is found which has the precedence less or equal to the read operator.
    3. If the read element is an ‘(‘, push it to the stack.
    4. If the read element is an ‘)’, pop and output from the stack until an ‘(‘ is encountered.
    5. Pop the content of stack and print.

Evaluation of postfix expression

Refer this link which has good explanation.

Related posts

Leave a Reply

Your email address will not be published. Required fields are marked *