Data Structures
S. Y. B. Tech CSE Semester – III
SCHOOL OF COMPUTER ENGINEERING AND TECHNOLOGY
Syllabus
Unit 5 :
Stacks: Stack as an Abstract Data Type, Representation of Stack Using Sequential
Organization, stack operations, Multiple Stacks Applications of Stack- Expression
Conversion and Evaluation, Linked Stack and Operations, Recursion.
Queues: Queue as Abstract Data Type, Representation of Queue Using Sequential
Organization, Queue Operations Circular Queue, Advantages of Circular queues,
Linked Queue and Operations Deque-Basic concept, types (Input restricted and
Output restricted), Application of Queue: Job scheduling.
DATA STRUCTURES UNIT-III 2
Stack
Topics to be Covered
❑ Stack as an Abstract Data Type
❑ Representation of Stack Using Sequential Organization
❑ Applications of Stack- Expression Conversion and Evaluation
❑ Recursion
DATA STRUCTURES UNIT-III 3
Unit-V
Stacks
DATA STRUCTURES UNIT-III 4
Real life Applications of
Stack
DATA STRUCTURES UNIT-III 5
Stack
• Stack : Special case of ordered list also called as restricted/controlled
list where insertion and deletion happens at only one end called as top
of stack (homogeneous collection of elements.)
• Elements are added to and removed from the top of the stack (the most
recently added items are at the top of the stack).
• The last element to be added is the first to be removed (LIFO: Last In,
First Out). TOP
•Only access to the stack is the top element
- consider trays in a cafeteria
--to get the bottom tray out, you must first remove all of the elements
above
DATA STRUCTURES UNIT-III 6
Where stack resides in data
structure family?
DATA STRUCTURES UNIT-III 7
Stack ADT
structure STACK (item)
declare CREATE() -> stack
ADD(item, stack) -> stack
DELETE(stack) -> stack
TOP(stack) -> item
ISEMPS(stack) -> boolean;
for all S ∈ stack, i ∈ item let
ISEMPS(CREATE) ::= true
ISEMPS(ADD(i,S)) ::= false
DELETE(CREATE) ::= error
DELETE(ADD(i,S)) ::= S
TOP(CREATE)
TOP(ADD(i,S)) ::= i
end
end STACK
DATA STRUCTURES UNIT-III 8
Basic Stack Operations
Operations-
➢ isEmpty()-Checking stack is empty
➢ IsFull()-Checking stack is full
➢ push()-Pushing Element on top of stack
➢ pop() – Popping top element from stack
DATA STRUCTURES UNIT-III 9
Representation of stack
Stack can be represented(implemented) using two data
structures
❑ Array (Sequential Organization)
❑Linked List (Linked Organization)
DATA STRUCTURES UNIT-III 10
Representation of Stack using
Sequential Organization
• Allocate an array of some size (pre-defined) 4
- Maximum N elements in stack 3
2
• Index of bottom most element of stack is 0 1 78
0 56
• Increment top when one element is pushed, decrement after pop
•Index of the most recently added item is given by top TOP
DATA STRUCTURES UNIT-III 11
Stack Operations using Array : Example
Stack
6 Stack Max
5 Size=07
4 Stack Empty
Locations=07
3
2
1
Top = Stack Empty
0
-1
Empty Stack
DATA STRUCTURES UNIT-III 12
Stack Operations using Array : Example
Stack
6 Stack Max
5 Size=07
4 Stack Empty
Locations=06
3
2
1
Top =
0 50 0
Push (50)
DATA STRUCTURES UNIT-III 13
Stack Operations using Array : Example
Stack
6 Stack Max
5 Size=07
4 Stack Empty
Locations=05
3
2
1 25
Top =
0 50 1
Push (25)
DATA STRUCTURES UNIT-III 14
Stack Operations using Array : Example
Stack
6 Stack Max
5 Size=07
4 Stack Empty
Locations=04
3
2 78
1 25
Top =
0 50 2
Push (78)
DATA STRUCTURES UNIT-III 15
Stack Operations using Array : Example
Stack
6 Stack Max
5 Size=07
4 Stack Empty
Locations=05
3
2 Popped element :
78
1 25
Top =
0 50 1
Pop ()
DATA STRUCTURES UNIT-III 16
Stack Operations using Array : Example
Stack
6 Stack Max
5 Size=07
4 Stack Empty
Locations=06
3
2 Popped element :
1 25
Top =
0 50 0
Pop ()
DATA STRUCTURES UNIT-III 17
Stack Operations using Array : Example
Stack
6 Stack Max
5 Size=07
4 Stack Empty
Locations=07
3
2
1 Popped element :
0 50
Top =
Pop () -1
DATA STRUCTURES UNIT-III 18
Stack Operations using Array : Example
Stack
6 Stack Max
5 Size=07
4 Stack Empty
Locations=03
3 78
2 90
1 45
Top =
0 23 03
Push (23),Push(45),Push(90),Push(78)
DATA STRUCTURES UNIT-III 19
Stack Operations using Array : Example
Stack Stack Full
6 80 Stack Max
5 65 Size=07
4 43 Stack Empty
Locations=00
3 78
2 90 Top =
06
1 45
0 23
Push (43),Push(65),Push(80)
DATA STRUCTURES UNIT-III 20
Operations on Stack (Algorithm and
Pseudo Code)
Push (ItemType newItem)
• Function: Adds newItem to the top of the stack.
• Preconditions: Stack has been initialized and is not full.
• Postconditions: newItem is at the top of the stack.
DATA STRUCTURES UNIT-III 21
Operations on Stack (Algorithm and
Pseudo Code)
Pop ()
• Function: Removes top Item from stack and returns it .
• Preconditions: Stack has been initialized and is not empty.
• Postconditions: Top element has been removed from stack
DATA STRUCTURES UNIT-III 22
Operations on Stack(Algorithm and
Pseudo Code)
Pseudo of isFull() function −
isFull() Algorithm isFull()
Stack overflow {
The condition resulting from trying to if (top ==MAXSIZE-1)
push an element onto a full stack.
return true ;
else
return false ;
}
DATA STRUCTURES UNIT-III 23
Operations on Stack (Algorithm and
Pseudo Code)
Pseudo Code for Push
Algorithm push ( item)
{
if ( ! isFull ())
{
top=top+1
stack[top]=item;
}
}
DATA STRUCTURES UNIT-III 24
Operations on Stack (Algorithm and
Pseudo Code)
Pseudo of isEmpty() function −
isEmpty() Algorithm isEmpty( )
Stack underflow (check if stack is {
empty.) if (top = = -1)
The condition resulting from trying to pop return true ;
an empty stack. else
return false ;
}
DATA STRUCTURES UNIT-III 25
Operations on Stack (Algorithm and
Pseudo Code)
Pseudo Code for Pop
Algorithm pop ()
{
if ( ! isEmpty())
{
temp=stack[top];
top=top-1;
return (temp);
}
}
DATA STRUCTURES UNIT-III 26
Applications of Stacks in Computer
Science
❑ Process Function Calls
❑ Recursive Functions Calls
❑ Converting Expressions
❑ Evaluating expressions
❑ String Reverse
❑ Number Conversion
❑ Backtracking
❑ Parenthesis Checking
DATA STRUCTURES UNIT-III 27
Program/Process in memory
DATA STRUCTURES UNIT-III 28
Applications of Stacks (cont’d)
1. Processing Function calls:
A stack is useful for the compiler/operating system to store local variables used inside
a function block, so that they can be discarded once the control comes out of the
function block.
When function
execution completes, it
is popped from stack
DATA STRUCTURES UNIT-III 29
Applications of Stacks (cont’d)
main()
{
int a=10,b=15; Stack
float avg; Local variable of add
avg = average(a,b,2); return address of add
printf(“%f”,avg); Pushing add() Call
Parameters of add
}
Local variables of
float average(int x,y,n) average
{ float avg;
int sum=add(x,y); return address of
avg = sum/n; average Pushing average() Call
return avg; Parameters of
} average
Local variables
int add(int x,int y) Return Address of
{ Main()
int sum=x+y;
return sum;
}
DATA STRUCTURES UNIT-III 30
Applications of Stacks (cont’d)
2. Recursive functions:
The stack is very much useful while factorial(int x)
implementing recursive functions. { main()
If(x==1) {
return(1); factorial(4)
The return values and addresses of the function else ;
will be pushed into the stack and the lastly return(x* }
invoked function will first return the value by factorial(x-1));
popping the stack. }
factorial(1) Will return
factorial(4)= value 1 and
factorial(2)
4*factorial(3); exit
4*3*factorial(2); factorial(3)
4*3*2*factorial(1); factorial(4)
4*3*2*1
main()
DATA STRUCTURES UNIT-III 31
Applications of Stacks (cont’d)
DATA STRUCTURES UNIT-III 32
Applications of Stacks (cont’d)
Expression Conversion:There are different types of Expressions
1) Infix expression :- It is the general notation used for representing expressions.
“In this expression the operator is fixed in between the operands”
Ex: a + b*c
2) Postfix fix expression :- (Reverse polish notation)
“In this expression the operator is placed after the operands”.
Ex : abc*+
3) Prefix expression :- (Polish notation)
“In this expression the operators are followed by operands i.e the operators are fixed before
the operands”
Ex : *+abc
All the infix expression will be converted into postfix or prefix notation with
the help of stack in any program.
DATA STRUCTURES UNIT-III 33
Expression Conversion
Why to use PREFIX and POSTFIX notations when we have simple INFIX
notation?
❑ INFIX notations are not as simple as they seem specially while
evaluating them.
❑ To evaluate an infix expression we need to consider Operators’ Priority
and Associative Property
E.g. expression 3+5*4 evaluate to 32 i.e. (3+5)*4 or to 23 i.e. 3+(5*4).
To solve this problem Precedence or Priority of the operators were defined
DATA STRUCTURES UNIT-III 34
Expression Conversion (cont’d)
Operator
❑
Precedence
Operator precedence governs evaluation order. An operator with higher
precedence is applied before an operator with lower precedence.
Rank Operator
1 ^
2 */%
3 + - (Binary)
DATA STRUCTURES UNIT-III 35
Expression Conversion (cont’d)
Expression Conversion Forms
We can convert any expression to any other two forms using Stack Data Structure
DATA STRUCTURES UNIT-III 36
Infix to Postfix
Expression Conversion Infix to Postfix
Example
DATA STRUCTURES UNIT-III 37
Infix to Postfix
Operator Precedence (In stack and Incoming
❑
precedence)
Operator precedence governs evaluation order. An operator with higher
precedence is applied before an operator with lower precedence.
Operator ICP ISP
( 5 0
^ 4 3
*/% 2 2
+ - (Binary) 1 1
DATA STRUCTURES UNIT-III 38
Algorithm
Scan the symbols of the expression from left to right and for each symbol, do the following:
a. If symbol is an operand
• store in postfixexp that symbol onto the screen.
b. If symbol is a left parenthesis
•Push it on the stack.
C.If symbol is a right parenthesis
• Pop all the operators from the stack upto the first left parenthesis and store in
postfixexp
• Discard the left and right parentheses.
d. If symbol is an operator
•If the precedence of the operators in the stack are greater than or equal to the current
operator,then
•Pop the operators out of the stack and store in postfixexp , and push the
current operator onto the stack.
else
● Push the current operator onto the stack.
DATA STRUCTURES UNIT-III 39
Infix to Postfix : Example 1
★Let the incoming the Infix expression be:
A * (B + C) – D / E
Stage 1: Stack is empty and we only have the Infix Expression.
DATA STRUCTURES UNIT-III 40
Infix to Postfix : Example 1
Stage 2
★The first token is Operand A Operands are Appended to the
Output as it is.
DATA STRUCTURES UNIT-III 41
Infix to Postfix : Example 1
Stage 3
★Next token is * Since Stack is empty (top==-1) it is pushed into
the Stack
DATA STRUCTURES UNIT-III 42
Infix to Postfix : Example 1
Stage 4
★Next token is ( the precedence of open-parenthesis, when it is to go
inside, is maximum.
★But when another operator is to come on the top of ‘(‘ then its
precedence is least.
DATA STRUCTURES UNIT-III 43
Infix to Postfix : Example 1
Stage 5
★Next token, B is an operand which will go to the Output expression as it
is
DATA STRUCTURES UNIT-III 44
Infix to Postfix : Example 1
Stage 6
★Next token, + is operator, We consider the precedence of top element
in the Stack, ‘(‘. The outgoing precedence of open parenthesis is the
least (refer point 4. Above). So + gets pushed into the Stack
DATA STRUCTURES UNIT-III 45
Infix to Postfix : Example 1
Stage 7
★ Next token, C, is appended to the output
DATA STRUCTURES UNIT-III 46
Infix to Postfix : Example 1
Stage 8
★Next token ), means that pop all the elements from Stack and
append them to the output expression till we read an opening
parenthesis.
DATA STRUCTURES UNIT-III 47
Infix
Stage 9
to Postfix : Example 1
★Next token, -, is an operator. The precedence of operator on the top of Stack ‘*‘
is more than that of Minus. So we pop multiply and append it to output
expression. Then push minus in the Stack.
DATA STRUCTURES UNIT-III 48
Infix to Postfix : Example 1
Stage 10
★Next, Operand ‘D‘ gets appended to the output.
DATA STRUCTURES UNIT-III 49
Infix to Postfix : Example 1
Stage 11
★Next, we will insert the division operator into the Stack because its
precedence is more than that of minus.
DATA STRUCTURES UNIT-III 50
Infix to Postfix : Example 1
Stage 12
★The last token, E, is an operand, so we insert it to the output
Expression as it is.
DATA STRUCTURES UNIT-III 51
Infix to Postfix : Example 1
Stage 13
★The input Expression is complete now. So we pop the Stack and
Append it to the Output Expression as we pop it.
DATA STRUCTURES UNIT-III 52
Infix to Postfix : Example 2
infixVect
(a+b-c)*d–(e+f)
postfixVect
DATA STRUCTURES UNIT-III 53
Infix to Postfix : Example 2
stackVect
infixVect
a+b-c)*d–(e+f)
postfixVect
DATA STRUCTURES UNIT-III 54
Infix to Postfix : Example 2
stackVect
infixVect
+b-c)*d–(e+f)
postfixVect
a
DATA STRUCTURES UNIT-III 55
Infix to Postfix : Example 2
stackVect
infixVect
b-c)*d–(e+f)
postfixVect
a
+
(
DATA STRUCTURES UNIT-III 56
Infix to Postfix : Example 2
stackVect
infixVect
-c)*d–(e+f)
postfixVect
ab
+
(
DATA STRUCTURES UNIT-III 57
Infix to Postfix : Example 2
stackVect
infixVect
c)*d–(e+f)
postfixVect
ab+
-
(
DATA STRUCTURES UNIT-III 58
Infix to Postfix : Example 2
stackVect
infixVect
)*d–(e+f)
postfixVect
ab+c
-
(
DATA STRUCTURES UNIT-III 59
Infix to Postfix : Example 2
stackVect
infixVect
*d–(e+f)
postfixVect
ab+c-
DATA STRUCTURES UNIT-III 60
Infix to Postfix : Example 2
stackVect
infixVect
d–(e+f)
postfixVect
ab+c-
DATA STRUCTURES UNIT-III 61
Infix to Postfix : Example 2
infixVect
–(e+f)
postfixVect
ab+c-d
DATA STRUCTURES UNIT-III 62
Infix to Postfix : Example 2
infixVect
(e+f)
postfixVect
ab+c–d*
DATA STRUCTURES UNIT-III 63
Infix to Postfix : Example 2
infixVect
e+f)
postfixVect
ab+c–d*
(
-
DATA STRUCTURES UNIT-III 64
Infix to Postfix : Example 2
infixVect
+f)
postfixVect
ab+c–d*e
(
-
DATA STRUCTURES UNIT-III 65
Infix to Postfix : Example 2
infixVect
f)
postfixVect
+ ab+c–d*e
(
-
DATA STRUCTURES UNIT-III 66
Infix to Postfix : Example 2
infixVect
)
postfixVect
+ ab+c–d*ef
(
-
DATA STRUCTURES UNIT-III 67
Infix to Postfix : Example 2
infixVect
postfixVect
ab+c–d*ef+
DATA STRUCTURES UNIT-III 68
Infix to Postfix : Example 2
infixVect
postfixVect
ab+c–d*ef+-
DATA STRUCTURES UNIT-III 69
Infix to Postfix : Example 3
Expression Conversion Infix to
Postfix
Suppose we want to convert 2*3/(2-1)+5*3 into Postfix form
DATA STRUCTURES UNIT-III 70
In Stack and Incoming priorities functions
icp(ch) (Infix→Postfix)
{
if(ch=='+' || ch=='-')
return 1; isp( ch)
if(ch=='*' || ch=='/') {
return 2; if(ch=='+' || ch=='-')
if(ch=='^') return 1;
if(ch=='*' || ch=='/')
return 4;
return 2;
if(ch=='(')
if(ch=='^')
return 5; return 3;
else else
return 0; return 0;
} }
DATA STRUCTURES UNIT-III 71
Algorithm in_post(inexp[ ]) else //3rd
{ // postexp[ ] has the postfix expression { while (stack not empty &&
k=0; i=0; isp(stk[top]) >= icp(tkn) )
tkn=inexp[i]; { postexp[k]=pop(); k++;
while ( tkn!=‘\0’) }
{ if tkn is an operand push(tkn);
{ postexp[k]=inexp[i]; } // end of 3rd else
k++; }//end of 2nd else
} }// end of 1st else
else //1st
{ if tkn==‘(‘ //open paranthesis // read next token
{ push(‘(‘); } i++;
else //2nd tkn=inexp[i];
{ }//end of outer while
if tkn==‘)‘ //open paranthesis while stack not empty
{ while (tkn=pop()) !=‘(‘ { postexp[k]=pop(); k++ }
{ postexp[k]=tkn; k++; } }
}
DATA STRUCTURES UNIT-III 72
Infix to Prefix
Expression = (A+B^C)*D+E^5
Step 1. Reverse the infix expression.
5^E+D*)C^B+A(
Step 2. Make Every '(' as ')' and every ')' as '('
5^E+D*(C^B+A)
Step 3. use following algorithm in_pre(infix) for Infix to Prefix
conversion (Given on next to next slide)
Setp 4: Reverse the final output to get Prefix form
DATA STRUCTURES UNIT-III 73
In Stack and Incoming priorities functions
(Infix→Prefix)
Swap ICP and ISP for exponent(^) operator
icp(ch)
{ isp( ch)
if(ch=='+' || ch=='-') {
return 1; if(ch=='+' || ch=='-')
if(ch=='*' || ch=='/') return 1;
return 2;
if(ch=='*' || ch=='/')
if(ch=='^')
return 2;
return 3;
if(ch=='(') if(ch=='^')
return 5; return 4;
else else
return 0; return 0;
} }
DATA STRUCTURES UNIT-III 74
Algorithm in_pre(inexp[ ])
else //3rd
{//Input: reversed infix expression
{ while (stack not empty &&
// Output : pre_exp[ ] has the prefix expression
isp(stk[top]) > icp(tkn) )
k=0; i=0;
{ pre_exp[k]=pop(); k++;
tkn=inexp[i];
}
while ( tkn!=‘\0’)
push(tkn);
{ if tkn is an operand
} // end of 3rd else
{pre_exp[k]=inexp[i];
}//end of 2nd else
k++;
}// end of 1st else
}
st
// read next token
else //1
i++;
{ if tkn==‘(‘ //open parenthesis
tkn=inexp[i];
{ push(‘(‘); }
}//end of outer while
else //2nd
while stack not empty
{
{pre_exp[k]=pop(); k++ }
if tkn==‘)‘ //open parenthesis
// reverse pre_exp to get prefix expression
{ while (tkn=pop()) !=‘(‘
}
{pre_exp[k]=tkn; k++; }
}
DATA STRUCTURES UNIT-III 75
Infix to Prefix : Example 1
Operation
Expression Stack Output
5^E+D*(C^B+A) Empty -
^E+D*(C^B+A) Empty 5 Print
E+D*(C^B+A) ^ 5 Push
+D*(C^B+A) ^ 5E Push
D*(C^B+A) + 5E^ Pop And Push
*(C^B+A) + 5E^D Print
(C^B+A) +* 5E^D Push
C^B+A) +*( 5E^D Push
^B+A) +*( 5E^DC Print
B+A) +*(^ 5E^DC Push
+A) +*(^ 5E^DCB Print
A) +*(+ 5E^DCB^ Pop And Push
) +*(+ 5E^DCB^A Print
End +* 5E^DCB^A+ Pop Until '('
End Empty 5E^DCB^A+*+ Pop Every element
DATA STRUCTURES UNIT-III 76
Infix to Prefix : Example 2
Ch prefix stack
E E -
/ E /
D ED /
+ ED/ +
C ED/C +
* ED/C +, *
B ED/CB +, *
+ ED/CB* +
ED/CB*+ +
A ED/CB*+A +
ED/CB*+A+ -
DATA STRUCTURES UNIT-III
77
Algorithm :- Postfix to Infix
1. Read the symbol from the input based on the input symbol go to step
2 or 3.
2. If symbol is operand then push it into stack.
3. If symbol is operator then pop top 2 values from the stack.
4. this 2 popped value is our operand .
5. create a new string and put the operator between this operand in
string.
6. push this string into stack.
7. At the end only one value remain in stack which is our infix
expression.
DATA STRUCTURES UNIT-III 78
Postfix to Infix
Algorithm Post_infx(E)
l=length of E
for i =0 to l-1
x=next_token E
case x: = operand push(x)
x: = operator
op2=pop();
op1=pop();
E1=strcat(‘(‘,op1,x,op2,’)’);
push (E1)
end
End Post_infx(E)
DATA STRUCTURES UNIT-III 79
Postfix to prefix
Algorithm Post_pre(E)
l=length of E
for i =0 to l-1
x=next_token E
case x: = operand push(x)
x: = operator
op2=pop();
op1=pop();
E1=strcat(x,op1,op2);
push (E1)
end
end Post_pre(E)
DATA STRUCTURES UNIT-III 80
prefix to infix prefix to
postfix
Algorithm Pre_infx(E) Algorithm pre_post(E)
l=length of E l=length of E
for i =l-1 to 0 for i =l-1 to 0
x=next_token E
x=next_token E case x: = operand push(x)
case x: = operand push(x) x: = operator
op1=pop();
x: = operator
op2=pop();
op1=pop(); E1=strcat(op1,op2,x);
op2=pop(); push (E1)
end
E1=strcat(‘(‘,op1,x,op2,’)’);
End pre_post(E)
push (E1)
end
End Pre_infx(E)
DATA STRUCTURES UNIT-III 81
Applications of Stacks (cont’d)
3. Expression
Evaluation
❑ For evaluating expression ,it is converted into prefix or postfix form.
❑ Expression in postfix or prefix form can be easily evaluated by computer
because no precedence of operators is required in this.
DATA STRUCTURES UNIT-III 82
Applications of Stacks (cont’d)
3. Expression Evaluation
Example
DATA STRUCTURES UNIT-III 83
Algorithm for evaluating a postfix expression
WHILE more input items exist
{
If symb is an operand
then push (opndstk,symb)
else //symbol is an operator
{
Opnd2=pop(opndstk);
Opnd1=pop(opndnstk);
Value = result of applying symb to opnd1 & opnd2
Push(opndstk,value);
} //End of else
} // end while
Result = pop (opndstk);
DATA STRUCTURES UNIT-III 84
Question : Evaluate the following expression in
postfix : 623+-382/+*2^3+
Final answer is
• 49
• 51
• 52
• 7
• None of these
DATA STRUCTURES UNIT-III 85
Evaluate- 623+-382/+*2^3+
Symbol opnd1 opnd2 value opndstk
6 6
2 6,2
3 6,2,3
+ 2 3 5 6,5
- 6 5 1 1
3 6 5 1 1,3
8 6 5 1 1,3,8
2 6 5 1 1,3,8,2
/ 8 2 4 1,3,4
+ 3 4 7 1,7
* 1 7 7 7
2 7,2
^ 7 2 49 49
3 49,3
+ 49 3 52 52
DATA STRUCTURES UNIT-III 86
Concept of Recursion
•Sometimes, the best way to solve a problem is by solving a smaller version of
the exact same problem first
•Recursion is a technique that solves a problem by solving a smaller problem of
the same type
•A procedure that is defined in terms of itself
DATA STRUCTURES UNIT-III 87
Concept of Recursion
What’s Behind this function
?
int f(int a){
if (a==1)
return(1);
else
return(a * f( a-1));
}
It computes f! (factorial)
DATA STRUCTURES UNIT-III 88
Concept of Recursion
Factorial:
a! = 1 * 2 * 3 * ... * (a-1) * a
Note:
a! = a * (a-1)!
remember:
...splitting up the problem into a smaller problem of the same type...
a!
a * (a-1)!
DATA STRUCTURES UNIT-III 89
Concept of Recursion
int factorial(int a){
if (a==0) RECURSION !
return(1);
else
return(a * factorial( a-1));
}
DATA STRUCTURES UNIT-III 90
Concept of Recursion
int factorial(int a){
if (a==1) Watching the
return(1); Stack
else
return(a * factorial( a-1));
} a=1
Return to
L1
a=2
Return to
L2
a=3
Return to
a=4 L3
Return to a=4
Return to
L4 … L4
a=5 a=5 a=5
Initial After 1 recursion After 4th recursion
Every call to the method creates a new set of local
variables ! DATA STRUCTURES UNIT-III 91
Concept of Recursion
int factorial(int a){
if (a==1) Watching the
return(1); Stack
else
return(a * factorial( a-1));
}
a=1
Return to
L1 a = 2*1 =
a=2
Return to 2 to
Return
L2 L2 a = 3*2 =
a=3 a=3
Return to
Return to L3
6 to
Return
a = 4*6 =
L3 L3
a=4 a=4 a=4 24
Return to Return to Return to Return to
L4 L4 L4 L4 a = 5*24 =
a=5 a=5 a=5 a=5
120
After 4th recursion Result
DATA STRUCTURES UNIT-III 92
Properties of Recursion
Problems that can be solved by recursion have these characteristics:
❑ One or more stopping cases have a simple, nonrecursive solution
❑ The other cases of the problem can be reduced (using recursion) to problems that are
closer to stopping cases
❑ Eventually the problem can be reduced to only stopping cases, which are relatively easy to
solve
Follow these steps to solve a recursive problem:
❑ Try to express the problem as a simpler version of itself
❑ Determine the stopping cases
❑ Determine the recursive steps
DATA STRUCTURES UNIT-III 93
Concept of Recursion
The recursive algorithms we write generally consist of an if statement:
IF
the stopping case is reached solve it
ELSE
split the problem into simpler cases using recursion
Solution on stack
Solution on stack
DATA STRUCTURES UNIT-III 94
Concept of Recursion
Common Programming Error
Recursion does not terminate
properly: Stack Overflow !
DATA STRUCTURES UNIT-III 95
Exercise
Define a recursive solution for the following function:
n
f(x) = x
DATA STRUCTURES UNIT-III 96
Recursion vs. Iteration
You could have written the power-function iteratively, i.e. using a
loop construction
Where‘s the difference ?
DATA STRUCTURES UNIT-III 97
Recursion vs. Iteration
❑ Iteration can be used in place of recursion
❑ An iterative algorithm uses a looping construct
❑ A recursive algorithm uses a branching structure
❑ Recursive solutions are often less efficient, in terms of both time and space,
than iterative solutions
❑ Recursion can simplify the solution of a problem, often resulting in shorter,
more easily understood source code
❑ (Nearly) every recursively defined problem can be solved iteratively
iterative optimization can be implemented after recursive design
DATA STRUCTURES UNIT-III 98
Deciding whether to use a Recursive
Function
• When the depth of recursive calls is relatively “shallow”
• The recursive version does about the same amount of work as the non
recursive version
• The recursive version is shorter and simpler than the non recursive
solution
DATA STRUCTURES UNIT-III 99
Stack using
Linked List
typedef struct Stack stack* getnode(int val)
{ {
int data; stack *ptr;
struct Stack *link; allocate memory for ptr;
}stack; ptr->data = val;
ptr->link = NULL;
stack *top; return(ptr);
}
DATA STRUCTURES UNIT-III 100
Stack using
Linked List
void push(int val) int pop()
{
{ stack *temp;
stack *temp; int val;
temp=top;
temp = getnode(val);
val = temp->data;
temp->link=top; top=top->link;
top=temp; free(temp);
return(val);
}
}
DATA STRUCTURES UNIT-III 101
Multiple Stack
If we have only 2 stacks to represent. then the solution is simple.
We can use V (1) for the bottom most element in stack 1 and V(m) for the corresponding element in
stack 2.
Stack 1 can grow towards V(m) and stack 2 towards V (1).
It is therefore, possible to utilize efficiently all the available space.
Can we do the same when more than 2 stacks are to be represented?
The answer is no, because:
◦ a one-dimensional array has only two fixed points V (1) and V(m) and each stack requires a fixed point for
its bottommost element.
◦ When more than two stacks, say n, are to be represented sequentially, we can initially divide out the
available memory V(1:m) into n segments and allocate one of these segments to each of the n stacks.
◦ This initial division of V(1:m) into segments may be done in proportion to expected sizes of the various
stacks if the sizes are known.
◦ In the absence of such information, V(1:m) may be divided into equal segments.
◦ For each stack i, we shall use B(i) to represent a position one less than the position in V for the bottommost
element of that stack.
DATA STRUCTURES UNIT-III 102
MULTIPLE STACKS
Two stacks
m[0], m[1], …, m[n-2], m[n-1]
bottommost bottommost
stack 1 stack 2
More than two stacks (n)
memory is divided into n equal segments
boundary[stack_no]
0 ≤ stack_no < MAX_STACKS
top[stack_no]
0 ≤ stack_no < MAX_STACKS
DATA STRUCTURES UNIT-III 103
MULTIPLE STACKS
Initially, boundary[i]=top[i].
0 1 [ m/n ] 2[ m/n ] m-1
boundary[ 0] boundary[1] boundary[ 2]
boundary[n]
top[ 0] top[ 1] top[ 2]
All stacks are empty and divided into roughly equal segments.
DATA STRUCTURES UNIT-III 104
MULTIPLE STACKS
#define MEMORY_SIZE 100 /* size of memory */
#define MAX_STACK_SIZE 100 /* max number of stacks plus 1 */
/* global memory declaration */
element memory [MEMORY_SIZE];
int top [MAX_STACKS];
int boundary [MAX_STACKS];
int n; /* number of stacks entered by the user */
To divide the array into roughly equal segments :
top[0] = boundary[0] = -1;
for (i = 1; i < n; i++)
top [i] =boundary [i] =(MEMORY_SIZE/n)*i;
boundary [n] = MEMORY_SIZE-1;
DATA STRUCTURES UNIT-III 105
MULTIPLE STACKS
an item to the stack stack-no
void add (int i, element item) {
/* add an item to the ith stack */
if (top [i] == boundary [i+1])
stack_full (i); may have unused storage
memory [++top [i] ] = item;
}
an item from the stack stack-no
element delete (int i) {
/* remove top element from the ith stack */
if (top [i] == boundary [i])
return stack_empty (i);
return memory [ top [i]--];
}
DATA STRUCTURES UNIT-III 106
Takeaways
❑ Stack is Last in First Out(LIFO) Data Structure
❑ Primitive operations on Stack are push, pop, isEmpty and isFull
❑ Stack can be represented by using Array as well as linked list.
❑ Stack is commonly used in expression conversion and Evaluation.
❑ Recursion is one of the important application of stack
DATA STRUCTURES UNIT-III 107
FAQS
1. Write an ADT for Stack
2. What are the primitive operations of
stack.
3. Explain with example stack
applications.
DATA STRUCTURES UNIT-III 108