You are on page 1of 9

Data Structures

Radhamadhab Dalai
Asst. Professor
CSE
BIT Mesra, Ranchi

24-09-2020 1
Stack

D TOP Push Pop

24-09-2020 2
Expressions
• Infix: A+B-C
• Prefix : -+ABC
• Postfix: AB+C-
• Example : A+B+C and A+B*C
• AB+C+ and ABC*+

24-09-2020 3
Prefix to postfix
• Reverse the prefix input string.
• Scan the input string from left to right.
• If ‘ch’ is an operand push it to stack
• 1. If ‘ch’ is an operator pop two elements(operand1
,operand2).
2. Make a string like str = operand1 + operand2 +
operator.
3.Push whole string (str) back to stack
• Repeat untill end of string
• Top of stack will contain whole string as output, pop.

24-09-2020 4
Prefix to postfix
• Prefix : +A*BC
• Reverse the string : CB*A+
Character Stack operation Stack
C push C
B Push CB
* Pop 2, append, BC*
push
A push BC*A
+ Pop 2, append, ABC*+
push

24-09-2020 5
Postfix to Prefix
• Scan the postfix input string from left to right.
• If ‘ch’ is an operand push it to stack
• 1. If ‘ch’ is an operator pop two
elements(operand1 ,operand2).
2. Make a string like str = operator + operand2 +
operand1.
3.Push whole string (str) back to stack
• Repeat untill end of string
• Top of stack will contain whole string as output,
pop.

24-09-2020 6
Postfix to Prefix
• Post fix : ABC*+
Character Stack operation Stack
A PUSH A
B PUSH AB
C PUSH ABC
* POP 2, APPEND, A*BC
PUSH
+ POP 2, APPEND, +A*BC
PUSH

24-09-2020 7
Problem
• A sequence of integers : 12, 0, 21, 2,19 ,26 ,8
• Sort the numbers(selection sort)
• A stack is given of size n.
• Hint

24-09-2020 8
Questions
• Questions ?
• Implement factorial(n) using stack ?
• T(n) = n T(n/2) + 1 what is O(n) = ?
• T(n/2) = n/2 T(n/2^2) + 1
• T(n/2^2) = n/4 T(n/2^3) + 1
• …………………………………
• T(n/2^k) = (n/ 2^k) T(n/2^(k+1)) + 1

24-09-2020 9

You might also like