Lecture Notes Data Structures and Applications [21CS35]
Stacks
Basic Operations
Stack is a special type of data structure where elements are inserted from one end called “top
of the stack and elements are deleted from the same end.
Y Using this approach the last element inserted is the first element to be deleted, so
stack is also called as Last-In-First-Out (LIFO) data structure,
Y Inset
ng an element to the stack is called as ‘push’ operation. Once the stack is full if
We try to insert an element stack overflow occurs.
Y Deleting an element from the stack is called ‘pop’ operation. Once the stack is empty
if we try to delete an element stack underflow occurs.
‘The schematic representation of a stack is as shown below.
Dr.MaheshG Dr.Harish G
push pop ‘Assoc. Prof. Assoc. Prof.
top ———— BMSIT aM rar
IFO structure with top pointing to the
top most element of the stack.
st]
The different operations that can be performed on a stack are
Y Insertion,
¥ Deletion.
Y Display.
Y Check whether the stack is full or not,
Y Check whether the stack is empty or not.
Implementation of Stacks using Arrays
#include
define stacksize 5
1/ function to insert an element into the stack
void pushtint item, int *top, int s{ ])
{
if(*top = = stacksize -1)
{
printf(“Stack overflow\n”);
return
}
Module 2Lecture Notes Data Structures and Applications [21CS35]
*op = "top + 1;
s{*top] = item;
}
// function to delete an element from the stack
int pop(int *top, int s[ ])
{
int item
if(*top = =-1)
{
)
item = s{*top];
top = *top -
return(item);
return -1;
1/ function to display the contents of a stack
void display(int top, int s{1)
{ Dr.MaheshG Dr.Harish G
inti; ‘Assoc. Prof. Assoc. Prof.
if(top == -1) MST aM. Or. ArT
{
printf(“Stack is empty\n”);
retui
}
printf(“Contents of the stack are\n”);
for(i = 0; i< = top; i++)
{
}
printf(“d\n”, sfil);
void main( )
{
int top, choice, item, s[stacksize], y;
top
fort
{
printi(“I.Push 2.Pop 3.Display 4.Exit\n”);
print{(“Enter your choice\n”);
scanf(“%d”, &choice);
switch(choice)
{
case 1: printf(“Enter element to insert\n”);
scanf(“%d”, &item);
push(item,8top, s);
break;
Module 2Lecture Notes Data Structures and Applications [21CS35]
case 2: y = pop(&top, s);
itty ==-1)
printi(“Stack underflow\n”);
else
printi(“item deleted = %ed\n”, y);
break;
case 3: display(top, 8);
break;
case 4: exit(O);
}
}
Other Stack Functions
// function to check if the stack is full
void isfull(int top)
{
iff(top = = stacksize -1)
{
printi(“Stack is full\n”);
}
else
{
printf(“Stack is not full\n”);
}
} Dr.Mahesh G
1/ function to check if the stack is empty sso. Prof.
void isempty(int top) sien eM
{
if(top = =-1)
{
printf(“Stack is empty\n”);
}
else
{
printf(“Stack is not empty\n”);
}
}
Applications of Stacks
Following are some of the applications of stacks.
Y Stacks are used in recursive functions.
Conversion of expressions.
Evaluation of Expressions.
For Traversing trees and graphs.
Reversal of a string.
Check if a given string is a palindrome or not.
0
Check for parenthesis matching.
Module 2Lecture Notes Data Struetures and Applications [21CS35]
System Stack and Activation Record
A stack used by the program at runtime is called as a system stack. The system stack is used when functions
are invoked and executed.
Note:
Y When a function is called, a structure called an activation record is created on top of the stack
¥ When a function is terminated, the activation record is deleted from the top of the system stack.
An activation record is also called as a stack frame. It is a structure consisting of various fields to store the
local variables (if any), parameters (if any), return addresses and pointer to the previous stack frame. Using
the activation record, the functions can communicate with each other.
Dr.Mahesh G Dr.Harish G
‘Assoc. Prof. Assoc. Prof.
BMSIT & M De AIT
‘The various actions that take place when we execute a program are,
Y The user gives the command to execute the program. Then, the OS calls the functions main( ) and the
body of the main( ) is executed.
¥ After executing the body of the function main( ), the control is returned to the operating system.
‘This is as shown in the following diagram
Operating
System
Frame Pointer
Local Variables of main( )
2 1 Maint)
@ i @ Previous Frame Pointer 5
| 0 z
fim |(@ Revo A 2
return turn Address
System Stack
Step1: The operating system transfers the control to the function main( ) along with the return address so
that after executing the body of the function main( ), the control is returned to OS.
Step 2: A stack frame or activation record is created consisting of
Y Return address of OS
Y Local variables of main( )
¥ Previous frame pointer (NULL in this case as itis the first record on the system stack)
This stack frame is pushed onto the stack.
Step 3: The mi
\() function is executed now.Lecture Notes Data Struetures and Applications [21CS35]
Step 4: When the return statement is executed in the main( ), the activation record is removed from the stack.
Using the removed activation record, we can get the return address of the OS using which the control is
transferred to OS.
Now suppose a funetion a() is invoked in main( ), the following are the further steps involved.
Step 5: When main( ) is being executed, if the function al() is invoked, a new stack frame or activation
record
created consisting of
¥ Return address of main( )
Dr.Mahesh G Dr.Harish G
Y Local variables of al( )
Y Current frame pointer which is on top of the stack.
This new stack frame is pushed onto the stack.
Note that the previous frame pointer of activation record which is on top of the stack points to the activation
record of the main( )
Operating
System
Return Address
of OS
Frame Pointer
Local Variables of al()
Previous Frame Pointer
Return Address
Qa
Local Variables of main( )
Previous Frame Pointer
0
Return Address.
© maine)
@
System Stack
Step 6: Control is transferred to the function al( ),
Module 2 5Lecture Notes Data Structures and Applications [21CS35]
Step 7: When the return statement in al( ) is executed, the activation record on top of the stack is removed.
Using the removed activation record, we can get the return address of the main using which the control is
transferred to main( )
Step 8: Finally, when the body of the function main( ) is completely executed, the return address of OS is
obtained from the activation record and control is transferred to OS.
Stack Abstract Datatype
Objects: A finite ordered list with zero or more elements,
Funetions:
For all s € Stack, item € element, stacksize € positive integer
‘Stack Create(stacksize) Creates an empty stack whose maximum size is stacksize
Boolean IsFull(s, stacksize) := if number of elements in stack s is stacksize return TRUE
else return FALSE
‘Stack Push(s, item)
if (IsFull(s)) stack is full
else insert item on to the stack § and return
= if no elements are there in stack return TRUE
else return FALSE
Boolean IsEmpty(s)
Element Pop(s) if (sEmpty(s)) return
else remove and return the element at the top of the stack
Stacks using Dynamic Arrays (with the concept of array doubling)
‘lude
5:
int capacity
int *s;
// function to insert an element
(0 the stack
void push(int item, int *top)
{
{
J! When stack is full double the size using realloc function
$= (int *) realloc(s, 2 * capacity * sizeof{int));
capacity = capacity * 2;
}
Module 2 6Lecture Notes Data Struetures and Applications [21CS35]
*top = *top +1;
s{*top!
tem;
// function to delete an element from the stack
int poptint *top)
i
int item;
iN
t
return -15 Dr.Mahesh G Dr.Harish G
: Asoo. Pro
SIT eM
item = s[*top];
“top = “top - 1;
return(item);
)
// function to display the contents of a stack
display(int top)
{
int i;
if(top = =-1)
{
printf(“Stack is empty\n”);
ret
a,
printf(“Contents of the stack are\n”);
for(i = 0; i< = top; i++)
{
printf(“%ed\n", sfil);
}
}
Module 2 7Lecture Notes Data Struetures and Applications [21CS35]
void main( )
{
int top, choice, item, y;
top
8 = (int *) malloc(capacity*sizeof(int));
for(;:)
{
printf(“1.Push 2.Pop 3.Display 4.Exit\n”);
printf(“Enter your choice\n”);
scanf(“%d”, &choice);
switch(choice)
{
case 1: printf(“Enter element to insert\n”);
scanf(“%d", &item);
push(item, &top);
Dr.Mahesh G Dr.Harish G
break; ‘Assoc, Prof. ‘Assoc, Prof
case 2: y= pop(&top); BSI M Dear
ifly ==-1)
printf(“Stack underflow\n”);
else
printf(“item deleted = %d\n”, y);
break;
case 3: display(top);
break;
case 4: free(s);
exit(0);
Module 2 8Lecture Notes Data Structures and Applications [21CS35]
Expressions
Types of Expressions
‘The different types of expressions are
Y Infix expression — Here an operator is in between 2 operands
EX: (a+b) /(c-d)
Y Postfix (Suffix or Reverse Polish) expression — Here an operator follows the 2
operands
EX: abted-/
Y Prefix (Polish) expression — Here an operator precedes the 2 operands
EX: /4ab-cd
In both postfix and prefix expression operator and operands define correctly the order of
operation.
Problem 1
Convert the following infix expression to postfix and prefix
((64+(3-2)*4)45+7)
Postfix Conversion
((6+(3-2)*4) 4547) HT1=32-
((O+TL#4)95+7) WT2=T14*
((6+T2)45+7) 73 =6T2+
(T345+7) NT4= 735%
T447 WT5=T47 +
TS
Ta7+
612+547+
OT14* 45°74
632-4 45474 (Postfix Expression)
Prefix Conversion
((6+(3-2)*4)9547) HTL s-32
((6+T1#4)45 +7) HT2=*T14
((6+72)45+7) HT3 =+6T2
(1345 +7) WT4=9 735
Module 2 9Lecture Notes Data Structures and Applications [21CS35]
(1447 WTS =+T47
TS
4047
+1357
+%+6T257
+%46*T1457
+%46"-32457 (Prefix Expression)
Problem 2
Convert the following infix expression to postfix and prefix
atbrerd
Postfix Conversion
at+b*erd WTlscd®
a+baTl WT2=bTI*
a+T2 WT3=aT2+
wes
oe Dr.Mahesh G Dr.Harish G
abTLe+ ‘Soren “Sear
abcd 4+ (Postfix Expression)
Prefix Conversion
atbrerd WTl=Acd
a+bATI WT2=AbTI
a+T2
ae
ee
+ahbTL
+arbred (Prefix Expression)
Module 2 10Lecture Notes Data Structures and Applications [21CS35]
Problem 3 (Sean from right to left)
Convert the prefix expression + - A B C to infix
+-ABC TI=A-B
+T1C T2=T1+C
nT
(T1+0)
(A-B}C)
Problem 4 (Scan from right to left)
Convert the prefix expression + A — B C to infix
+A=B T1=B-C
+ATI T2=A+TI
2 Dr.Mahesh G Dr.Harish G
ee Assoc. Prof. Assoc. Prof
(A+TI) ‘BMSIT & M_ Dr. AIT
(A+(B-O)
Problem 5 (Scan from left to right)
Convert the postfix expression A B + C - to infix
Apec” TI=A+B
T1C- Tl=TI-c
T2
a-O —
(A+B) -C)
Problem 6 (Scan from left to right)
Convert the postfix expression AB C + - to infix
ABC#- TI=B+C
ATI- T2=A-TI
2)
(A-TD
(A— (B+C))
Module 2 uLecture Notes Data Structures and Applications [21CS35]
Infix to Postfix Conversion
Algorithm to convert infix expression to postfix
The 2 functions which will be used while converting an expression from infix to postfix are
Y Input precedence function AER]
Y Stack precedence function Manest
MSI M
Note:
1. +,-,*, /and % are left associative. * and = are right associative.
2. If the operators are left associative, input precedence is less than the stack precedence.
3. If the operators are right associative, input precedence is greater than the stack
precedence.
4, The left parenthesis
precedence is zero,
5. The right parenthesis in the input has the precedence value of zero.
6. + and — have the least precedence (left associative) and next comes *, / and % (left
associative) then exponentiation (right associative) and then operands and finally left
parenthesis.
the input has the highest precedence and on the stack its
i
Input Precedence Stack Precedence
Symbol Value _ [Symbol Value
He 1 #- 2
“1% 3 "1% 4
ors 6 [For$ 5
Operands 7 [Operands 8
( oT 0
) Onna [tf =
General Procedure
Step 1: Obtain the next input symbol from the infix expression
Step 2: While precedence of the symbol which is there on top of the stack is greater than the
precedence of the current input symbol, pop an element from the stack and place it into the
postfix expression.
Step 3: If stack precedence symbol and input precedence symbol values are different push
the current symbol on to the stack otherwise (if they are equal) delete an element from the
stack,
Step 4: Repeat through Step 1 till you encounter end of input.
Step 5: If stack contains any other symbols other than #, pop all the symbols from the stack
and place them in the postfix expression till “#” is encountered on top of the stack.
Note: If un-parenthesized infix expression is used, only a partial postfix expression is
obtained and still some more symbols are left on top of stack. Therefore Step 5 is needed i
the general procedure.
Module 2 12Lecture Notes
Data Structures and Applications [21CS35]
Problem 1
Convert the expression ( 6 + (53) #4 ) to postfix
‘Scanned Symbol _| Stack Contents | Operation __| Postfix Expression
( # 179, Push (
6 # OFT, Push 6
+ #6 B>1,Pop6 [6
# OF 1. Push >
( a 279, Push(
3 #+C OFT, Push | 65
#46 8> 1, Pops
#GC OF 1, Push-
3 4G 2F7,Push3 | 653
y FCS $>0,Pop3 | 653
#GC 250, Pop-
HC , Delete (
« #(+ }. Push *
4 ‘id ait 4+7,Push4 653-4
y #44 8>0,Pop4 _ | 653-4
#G* 450, Pop* | 653-4%+
a 2>0, Pop +
#( 0=0, Delete (
End of input # 3
Problem 2 Decent eeoeen
Convert the expression 6 + 4 * 3 to postfix BMSIr a M
Scanned Symbol | Stack Con tents] Operation Postfix Expression
6 # “17, Push6
+ #6 B>1,Pop6 [6
# I, Push +
4 #e 277, Push4
¥ ea B>3,Pop4 [6a
ual 243 Push *
3 oe 427, Push
End of Input #3 Pop 3 643
#+* Pop * 643*
t+ Pop + 643 ee
# 643740
Module 2
13Lecture Notes Data Structures and Applications [21CS35]
Program to convert infix expression to postfix,
#include
# define stacksize 70
int input_precedence(char symbol)
i
switch(symbol)
{
case'+"
return 1;
return 3;
return 6;
return 9;
return 0;
return 7;
}
} Dr.Mahesh G Dr.Harish G
Assoc. Prof, Assoc. Prof.
int stack_precedence(char symbol) BMSIT De ATT
{
switch(symbol)
{
case '+'
’ return 2;
return 4;
return 5;
return 0;
return -1;
return 8;
}
}
void push(char item, int *top, char s[])
{
if(*top = = stacksize-1)
{
printf("stack overflow\n");
return;
}
Module 2 4Lecture Notes Data Structures and Appl
*top = *top + 13
s[*top] = item;
cations [21CS35]
}
char pop(int *top, char s{])
{
char item;
if(*top = =-1)
return -1;
item = s[*top];
top = *top - 1;
return item;
}
void infix_postfix(char infix{], char postfix{])
{
inti, n, j, tops
char symbol, s[stacksize];
j=0;
-1;
'#, &top, )5 Dr.Mahesh G Dr-Harish G
. te Assoc. Prof. Assoc. Prof.
n= strlen(infix); BMSIT.& M De AIT
for(i=0; isn; i++)
{
symbol = infixfils
while(stack_precedence(s[top]) > input_precedence(symbol))
{
postfix[j] = pop(&top, s)3
jeitls
}
if(stack_precedence (s{top])
{
push(symbol, &top, s);
}
else
{
pop(&top, s);
postfix[j] = pop(&top, s)s
jaith
}
postfix{j] = \0's
}
Module 2
15Lecture Notes Data Structures and Applications [21CS35]
void main()
{
char infix[70], postfix[70];
clrser( );
printf("enter the infix expression\n");
seanf("%s" jinfix);
infix_postfix (infix, postfix);
printf("the postfix expression is %s" postfix);
getch( );
Dr.Mahesh G Dr.Harish G
Assoc. Prof.
Module 2 16Lecture Notes Data Structures and Applications [21CS35]
Evaluation of Postfix Expression
Infix Expression: Evaluating an infix expression requires repeated scanning from left to
right and right to left because arithmetic operations have to be performed based on
precedence of operations. If there are parenthesis in the expression, the problem becomes
quite complex because parenthesis change the order of precedence.
Postfix and Prefix Expression: Here the operator and operands define correctly the order of
operations. Since no parenthesis is present, there is no repeated scanning and time taken is
less.
Algorithm for Evaluation of Postfix Expression
Step 1: Scan from left to right till we get an operator.
Step 2: Obtain immediate 2 left operands,
Step 3: Perform the indicated operation.
Step 4: Replace the operands and the operators by the result
Step 5: Repeat through Step | till the end of input.
Example: Consider the postfix expression 6 3 25 + for the infix expression (6 + (32)
#5), Itis evaluated as shown below.
632-5*+ 3-2
1*5
6+5=
Pseudocode for Evaluation of Postfix Expression
While( not end of input)
{
Obtain the next input symbol
if(symbol is an operand)
push(symbol, top, s)
else
{
push(res, top, s);
: }
return( pop(top, s));
Example: Evaluation of the postfix expression 6 3 2 ~ 5 * + is as shown below
‘Scanned Symbol | op2 | opt | res = opI op op2 | Stack Contents
6 6
3 63
2 632
- af = 7 ee 61
3 615
* 3) [#525 65
+ 5 6 6+5=11 u
End of input Return 11
Module 2 17Lecture Notes Data Structures and Applications [21CS35]
Program for Evaluation of Postfix Expression,
#include
# define stacksize 70
void push(int item, int *top, int s[])
{
if(*top = = stacksize-1)
{
printf("stack overflow\n");
return;
}
“top = top + 13
sf*top] = item;
}
int pop(int *top, int sf])
{
int item;
if(*top = =-1)
return -1; Dr.Mahesh G Dr.Harish G
item = s[*top}s Assoc Pol. Asse. Po
*top = “top - 1; zt
return item;
}
int evaluate(char postfix{])
{
int i, n, op1, op2, res, op, top, s[stack_size];
char symbol;
top =-1;
n = strlen(postfix);
for(i=05 i
Hdefine stacksize 10
// function to insert an element into the stack 1
void push (int item, int *top1, int *top2, int sf 1)
{
if(*top top2 -1)
{
printf(“Stack overflow\n”);
return;
}
top| = *topl + 1:
s{*topl] = item;
}
// function to insert an element into the stack 2
void push2(int item, int *top |, int *top2, int sf })
{
if(*top1 == *top2 -1)
{
printi(“Stack overflow\n”
return;
}
eo Dr.Mahesh G Dr.Harish G
item;
// function to delete an element from the stack
int popl (int *topl, int s[ })
{
int item;
if(top1 == -1)
{
return -1;
}
item = s[*top!};
top| = "top! -
return(item);
}
Module 2Lecture Notes Data Structures and Applications [21CS35]
// function to delete an element from the stack2
int pop2int *top2, int s{ 1)
{
int item;
if(*top2 = = stack_size)
{
return -1;
}
item = s[*top2];
*top2 = *top2 + 1;
return(item);
}
// function to display the contents of a stack
void display (int topI, int s{])
{
inti;
if(top! oe
{
printi(“Stack1 is empty\n”);
return;
y
printf(“Contents of the stack! are\n”);
for(i = 0; i< = top]; i+ +)
{
printi(“Sed\n”, sfiD)s
4 Dr.Mahesh G Dr.Harish G
Assoc. Prof
} De. AIT
// function to display the contents of a stack2
void display2Cint top2, int s{])
{
int is
ifltop2 = = stack_size)
{
printf(Stack2 is empty\n”);
return;
}
printf(“Contents of the stack? are\n”);
for(i = top2; is stack_size; i + +)
{
printi(“ed\n”, sli);
}
}
Module 2 m4Lecture Notes Data Structures and Applications [21CS35]
Program to reverse a given string using stacks
#include
define stacksize 50
void push(char item, int *top, char s[ ]) // function to insert an element into the stack
{
if((*top = = stacksize -1)
{
printi(“Stack overflow\n”
return;
}
op = *top +1;
s[*top] = item;
a
char pop(int *top, char s[ ]) // function to delete an element from the stack
{
char item;
if(*top =
{
}
item = s[*top];
*top = top - 1;
return(item);
-D
return -1;
}
void reverse_string(char str{ ], char revstr[ ]) // function to reverse the string
{
int top, n;
char s[stacksize], symbol;
top=-l;
ns strlen(str); Dr.Mahesh G Dr.Harish G
‘Assoc. Prof. Assoc. Prof.
i++) BMSIT & M Dr.
symbol = sti};
push(symbol, &top, s);
)
forli=O;i
define stacksize 50
void push(char item, int *top, char s[ ]) // function to insert an element into the stack
{
if*top = = stacksize -1)
{
}
*top = "top +1; s[*top] = item;
printf(“Stack overflow\n”); return;
}
char pop(int “top, char s[ }) // function to delete an element from the stack
{
char item;
iftop = = -1)
{
return -1;
}
item = s[*top]; “op = *top - 1; return(item);
}
int check_palindrome(char str[ ]) // function to check for palindrome
{
int top =-1, n;
char s[stacksize], symbol, s1, s2;
trlen( str
fori =O;i
define stacksize 50
void push(int item, int “top, int s[ ]) // function to insert an element into the stack
{
if*top = = stacksize -1)
{
print{(Stack overflow\n"); return;
}
*top = "op +1; s[*top] = item;
}
int pop(int *top, int s{ }) // function to delete an element from the stack
int item;
if*top = = -1)
{
return -1;
}
item = s[*top]; “op = “top - 1; return(item);
}
int check_palindrome(char str[ ]) // function to check for palindrome.
{
int top = -1, n, s[stacksize], s1, s2;
char symbol;
strlen( str) Dr.Mahesh G Dr.Harish G
fori =O;i