PRESIDENCY UNIVERSITY
Bengaluru, Karnataka
Computer Science & Engineering
School of Computer Science & Engineering
Subject: CSE2001 - Data Structures & Algorithms Semester: III
Date: 22/09/2023
Conversion of Infix expression to Postfix expression using stack:
a+b -> postfix = ab+
Example:
Consider the given Infix expression:
a+b*c–d+(e^f)/g/h*i+j^k^l
(Read the expression from left to right one symbol after another)
Input Symbol Stack Postfix Expression
a a
+ + a
b + ab
* +* ab
c +* abc
- - abc*+
d - abc*+d
+ + abc*+d-
( +( abc*+d-
e +( abc*+d-e
^ +(^ abc*+d-e
f +(^ abc*+d-ef
) + abc*+d-ef^
/ +/ abc*+d-ef^
g +/ abc*+d-ef^g
/ +/ abc*+d-ef^g/
h +/ abc*+d-ef^g/h
* +* abc*+d-ef^g/h/
i +* abc*+d-ef^g/h/i
+ + abc*+d-ef^g/h/i*+
j + abc*+d-ef^g/h/i*+j
^ +^ abc*+d-ef^g/h/i*+j
k +^ abc*+d-ef^g/h/i*+jk
^ +^^ abc*+d-ef^g/h/i*+jk
l +^^ abc*+d-ef^g/h/i*+jkl
abc*+d-ef^g/h/i*+jkl^^+
Postfix expression : abc*+d-ef^g/h/i*+jkl^^+
Prepared by,
Ms. Sridevi S, AP/SoCSE, Ms. Meena Kumari, AP/SoCSE, Ms. Rohini A, AP/SoCSE 1
Basic rules to convert infix expression to postfix expression using stack:
1. When an incoming symbol is an operand, print the operand.
2. When an incoming symbol is operator and has equal precedence than the top of the
stack, then check for Associativity,
(i) If Associativity is L to R, pop the top of stack and check the incoming operator
with the current top of the stack.
(ii) If Associativity is R to L, push the incoming operator to the stack
3. When an incoming symbol is operator and has precedence greater than top of the stack,
push the symbol to the stack.
4. When an incoming symbol is operator and has less precedence than the top of the stack,
pop the top of the stack and check the incoming symbol with top of the stack.
Prepared by,
Ms. Sridevi S, AP/SoCSE, Ms. Meena Kumari, AP/SoCSE, Ms. Rohini A, AP/SoCSE 2