Vous êtes sur la page 1sur 3

Data Structures and Algorithms

Lab Manual
Week 3 Lab 01

University of Sciences and Technology Bannu , USTB

INFIX TO POSTFIX CONVERSION USING STACK


Objectives
Implementation of stack concepts.

Understanding the use of stack data structure by performing:

Infix to Postfix conversion.

ADVANTAGES OF USING POSTFIX NOTATION OVER INFIX


NOTATION

While using infix notation one has to remember a set of rules like BODMAS to determine
the final value which is complex. Also the representation of arithmetic expression in an infix
form has been found to be inefficient form the compiler point of view because a repeated
scanning is required form left to right for the evolution of the expression.

Thus a postfix expression is preferred over an infix expression because of the following
reasons:-

(A). Postfix notation is easier to work with. In a postfix expression operators operands
appear before the operators, there is no need of operator precedence and other rules. In
postfix expression the topmost operands are popped off and operator is applied and the result
is again pushed to the stack and thus finally the stack contains a single value at the end of
the process.

(B). In postfix expression, there are no parentheses and therefore the order of evaluation
will be determined by the positions of the operators and related operands in the expression.

Lab Task 1

Implement stack and use it to convert infix to postfix expression.

Always scan given expression from left to right.

Hint (ALGORITHM):

1) Examine the next element in the input.

2) If it is operand, output it.


3) If it is opening parenthesis, push it on stack.

4) If it is an operator, then

i) If stack is empty, push operator on stack.

ii) If the top of stack is opening parenthesis, push operator on stack

iii) If it has higher priority than the top of stack, push operator on stack.

iv) Else pop up the operator from the stack and output it, repeat step 4

5) If it is a closing parenthesis, pop operators from stack and output them until an opening
parenthesis is encountered. Pop and discard the opening parenthesis.

6) If there is more input go to step 1

7) If there is no more input, pop the remaining operators to output.

Sample Input:

(2 + 3)*(9 6/ 3) + 7

Sample Output:

2, 3, +, 9, 6, 3, /, , *, 7, + (Commas are placed only to separately show each operators


and operand)

Vous aimerez peut-être aussi