Professional Documents
Culture Documents
Applications of Stack
Applications of Stack
Applications of Stack
Need of Recursion:
Recursion is an amazing technique with the help of which we can reduce the
length of our code and make it easier to read and write.
Properties of Recursion:
• Performing the same operations multiple times with different inputs.
• In every step, we try smaller inputs to make the problem smaller.
• Base condition is needed to stop the recursion otherwise infinite loop will
occur
void display2(int n)
{
if(n ==0)
return;
display2(n-1); /* Not a Tail recursive call
printf(“%d”,n);
}
int fact(int n)
{
if(n ==0)
return 1;
return (n*fact(n-1)); /* Not a Tail recursive call
}
Step 3 − Move n-1 disks from aux(B) to destination (C) using source (A) as
the temporary pillar.
The final number in the stack, 1, is the value of the postfix expression.
Prepared by: Dr Deepak Gupta, CSED, MNNIT Allahabad, India
Evaluation of a Prefix Expression
Consider the following prefix notation: /+33-+47*+123.
First reverse the prefix expression is 321+*74+-33+/
A Empty A
+ + A
( +( A
B +( AB
* +(* AB
C +(* ABC
/ +(/ ABC*
D +(/ ABC*D
– +(- ABC*D/
E +(- ABC*D/E
^ +(-^ ABC*D/E
F +(-^ ABC*D/EF
^ +(-^ ABC*D/EF^
I +(-^ ABC*D/EF^I
+ +(+ ABC*D/EF^I^-
G +(+ ABC*D/EF^I^-G
) + ABC*D/EF^I^-G+
/ +/ ABC*D/EF^I^-G+
H +/ ABC*D/EF^I^-G+H
NULL Empty ABC*D/EF^I^-G+H/+
To convert an infix expression to a prefix expression, we can use the stack data
structure. The idea is as follows:
Step 1: Reverse the infix expression. Note while reversing each ‘(‘ will become
‘)’ and each ‘)’ becomes ‘(‘.