Mit Syllabus
Mit Syllabus
S. Y. B. Tech CSE
2
Stack
Topics to be Covered
❑ Recursion
3
Unit-V
Stacks
4
Real life Applications of
Stack
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
6
Where stack resides in data
structure family?
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
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
9
Representation of stack
Stack can be represented(implemented) using two data
structures
10
Representation of Stack using
Sequential Organization
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
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)
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)
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)
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 ()
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 ()
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
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)
19
Stack Operations using Array : Example
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)
20
Operations on Stack (Algorithm and
Pseudo Code)
21
Operations on Stack (Algorithm and
Pseudo Code)
Pop ()
22
Operations on Stack(Algorithm and
Pseudo Code)
23
Operations on Stack (Algorithm and
Pseudo Code)
24
Operations on Stack (Algorithm and
Pseudo Code)
25
Operations on Stack (Algorithm and
Pseudo Code)
26
Applications of Stacks in Computer
Science
❑Process Function Calls
❑Recursive Functions Calls
❑Converting Expressions
❑Evaluating expressions
❑String Reverse
❑ Number Conversion
❑Backtracking
❑Parenthesis Checking
27
Program/Process in memory
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
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); Parameters of add
Pushing add() Call
}
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;
}
30
Applications of Stacks (cont’d)
2. Recursive functions:
31
Applications of Stacks (cont’d)
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.
33
Expression Conversion
Why to use PREFIX and POSTFIX notations when we have simple INFIX
notation?
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)
35
Expression Conversion (cont’d)
Expression Conversion Forms
We can convert any expression to any other two forms using Stack Data Structure
36
Infix to Postfix
Expression Conversion Infix to Postfix
Example
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.
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.
39
Infix to Postfix : Example 1
★Let the incoming the Infix expression be:
A * (B + C) – D / E
Expression.
40
Infix to Postfix : Example 1
Stage 2
Output as it is.
41
Infix to Postfix : Example 1
Stage 3
42
Infix to Postfix : Example 1
Stage 4
inside, is maximum.
★But when another operator is to come on the top of ‘(‘ then its
precedence is least.
43
Infix to Postfix : Example 1
Stage 5
it is
44
Infix to Postfix : Example 1
Stage 6
45
Infix to Postfix : Example 1
Stage 7
46
Infix to Postfix : Example 1
Stage 8
★Next token ), means that pop all the elements from Stack and
parenthesis.
47
Infix to Postfix : Example 1
Stage 9
Stack ‘*‘ is more than that of Minus. So we pop multiply and append it to
48
Infix to Postfix : Example 1
Stage 10
49
Infix to Postfix : Example 1
Stage 11
★Next, we will insert the division operator into the Stack because its
50
Infix to Postfix : Example 1
Stage 12
Expression as it is.
51
Infix to Postfix : Example 1
Stage 13
52
Infix to Postfix : Example 2
infixVect
(a+b-c)*d–(e+f)
postfixVect
53
Infix to Postfix : Example 2
stackVect
infixVect
a+b-c)*d–(e+f)
postfixVect
54
Infix to Postfix : Example 2
stackVect
infixVect
+b-c)*d–(e+f)
postfixVect
a
55
Infix to Postfix : Example 2
stackVect
infixVect
b-c)*d–(e+f)
postfixVect
a
+
(
56
Infix to Postfix : Example 2
stackVect
infixVect
-c)*d–(e+f)
postfixVect
ab
+
(
57
Infix to Postfix : Example 2
stackVect
infixVect
c)*d–(e+f)
postfixVect
ab+
-
(
58
Infix to Postfix : Example 2
stackVect
infixVect
)*d–(e+f)
postfixVect
ab+c
-
(
59
Infix to Postfix : Example 2
stackVect
infixVect
*d–(e+f)
postfixVect
ab+c-
60
Infix to Postfix : Example 2
stackVect
infixVect
d–(e+f)
postfixVect
ab+c-
61
Infix to Postfix : Example 2
infixVect
–(e+f)
postfixVect
ab+c-d
62
Infix to Postfix : Example 2
infixVect
(e+f)
postfixVect
ab+c–d*
63
Infix to Postfix : Example 2
infixVect
e+f)
postfixVect
ab+c–d*
(
-
64
Infix to Postfix : Example 2
infixVect
+f)
postfixVect
ab+c–d*e
(
-
65
Infix to Postfix : Example 2
infixVect
f)
postfixVect
+ ab+c–d*e
(
-
66
Infix to Postfix : Example 2
infixVect
)
postfixVect
+ ab+c–d*ef
(
-
67
Infix to Postfix : Example 2
infixVect
postfixVect
ab+c–d*ef+
68
Infix to Postfix : Example 2
infixVect
postfixVect
ab+c–d*ef+-
69
Infix to Postfix : Example 3
Expression Conversion Infix to Postfix
Convert 2*3/(2-1)+5*3 into Postfix form
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;
} }
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++; } }
}
72
Infix to Prefix/Postfix
• Higher priority operators should be assigned higher values of ISP and
ICP.
73
Infix to Prefix
Expression = (A+B^C)*D+E^5
74
Infix to Prefix
A^B*C-C+D/A/(E+F)
+-*^ABCC//DA+EF
Input : A * B + C / D
Output : + * A B/ C D
75
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
}
// read next token
else //1st
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++; }
}
77
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
78
Infix to Prefix : Example 2
A+B*C+D/E
E/D+C*B+A
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+ -
79
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)
80
Void postinfx(char post[SIZE]){ }
char s1[SIZE] , s2[SIZE],s3[SIZE],temp[SIZE],inf[SIZE]; pop(inf);
for(int i=0;post[i]!='\0';i++){ printf("\nthe infix expr is: ");
s1[0]=post[i]; printf("\n%s",inf);
s1[1]='\0';
if(isalpha(post[i])!=0)
push(s1);
else{
pop(s2);
pop(s3);
strcpy(inf,"(");
strcat(inf,s3);
strcat(inf,s1);
strcat(inf,s2);
strcat(inf,")");
push(inf);
}
81
void pop(char str[20]){
char s[30][30];
if(isEmpty()){
void push(char str[SIZE]){
printf("\nStack is empty !");
if(isFull()){
}else{
printf("\nStack is full !");
}
strcpy(str,s[top]);
else{ top--;
strcpy(s[++top],str);
} }
} }
82
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)
83
prefix to infix prefix to
postfix
84
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.
85
Applications of Stacks (cont’d)
3. Expression Evaluation
Example
86
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);
87
void eval(char post[SIZE]) int calc(int c1,int c2,char op)
{ {
for(i=0;post[i]!='\0';i++) switch(op)
{ {
if(isalpha(post[i])!=0) case '+':
{ ans=a+b;
printf("\nEnter value of %c",post[i]); break;
scanf("%d",&z); case '-':
pushval(z); ans=a-b;
} break;
else case '*':
{ ans=a*b;
op1=popval(); break;
op2=popval(); case '/':
ans=calc(op1,op2,post[i]); ans=a/b;
pushval(ans); break;
} default:;
} }
printf("\nEvaluation is: "); return(ans);
printf("%d",stack[top]); }
}
88
Question : Evaluate the following expression in
postfix : 623+-382/+*2^3+
Final answer is
• 49
• 51
• 52
• 7
• None of these
89
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
90
Concept of Recursion
• Sometimes, the best way to solve a problem is by solving a smaller version of
the exact same problem first
91
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)
92
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)!
93
Concept of Recursion
int factorial(int a){
if (a==0) RECURSION !
return(1);
else
return(a * factorial( a-1));
}
94
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
a=5
L4
a=5
… L4
a=5
Initial After 1 recursion After 4th recursion
Every call to the method creates a new set of local
variables ! 95
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 6 to
Return
a = 4*6 =
L3 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
96
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
97
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
98
Concept of Recursion
Common Programming Error
99
Exercise
Define a recursive solution for the following function:
n
f(x) = x
100
Recursion vs. Iteration
You could have written the power-function iteratively, i.e. using a
loop construction
101
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
102
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
103
Linked List-based Stack
Implementation
Initially top=NULL
PUSH pnode
typedef struct
pnode
{ 23 45 67 78 NUL
L
pnode * next;
TOP
int item;
Stack implementation using Linked list
} POP includes
{ {
Stack_Node* NewNode;
int data;
Allocate memory for NewNode;
struct Node *link;
NewNode->data = value;
}; NewNode->link = Null;
Node *Top; NewNode->link = Top;
int IsEmpty(); Top = NewNode;
Top = Null; }
int Pop()
int IsEmpty()
{
{
Stack_Node* tmp = Top;
if(Top == Null)
int data = Top->data;
return 1; if(!IsEmpty())
else {
return 0; Top = Top->link;
} delete tmp;
return(data);
}
}
Linked List-based Queue
Implementation
Initially
Front=Rear =NULL
ADDQ
Front
pointer
typedef struct
pnode
{ 23 45 67 78 NUL
L
pnode * next;
front
int item; Rear
pointer
} DeletQ
107
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.
MULTIPLE STACKS
Two stacks
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
MULTIPLE STACKS
Initially, boundary[i]=top[i].
0 1 [ m/n ] 2[ m/n ] m-1
All stacks are empty and divided into roughly equal segments.
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 */
113
FAQS
1. Write an ADT for Stack
2. What are the primitive operations of
stack.
3. Explain with example stack
applications.
114