DAYANANDA SAGAR COLLEGE OF ENGINEERING
(An Autonomous Institute Affiliated to VTU, Belagavi)
Course :Data Structures with Applications Course code: 21CS34
Semester: III
UNIT -1
Syllabus:
Introduction: Introduction to Data Structures and its classification, Dynamic Memory
allocation.
Stack: Introduction to stack , Representation of stacks in C
Applications of Stack: Conversion of Expressions, Evaluation of Expressions Recursion:
Factorial, Fibonacci Sequence, Tower of Hanoi
Introduction to Data Structure
Data structures the way of organizing data in computer memory so that it can be used efficiently.
Classification of data structure
The need for Data structure: Allocate the memory for information of various forms. Data
structures are used in computing to make it easy to locate and retrieve information. Primitive
data structures are simple ways for programming languages to represent basic values. These
include data types like integer, char (character), Boolean, pointers, and the like. Non-primitive
data structures provide ways of storing multiple values in a single variable. These include arrays,
lists, stacks, trees, and so forth. Data structures can also be used to group and organize other data
structures. In databases, a record can be thought of as a data structure that contains all the data
structures related to a given key; in object oriented programming languages like Java, a class is a
data structure that organizes attributes and functions in such a way that they can be easily
replicated. In each case, the way the data is "structured" makes it easy to retrieve or manipulate.
Dr. Harish Kumar N, Assistant Professor, Dept. of CSE, DSCE, Bangalore -560078 1
Dynamic Memory allocation
Dynamic Memory Allocation can be defined as a procedure in which the size of a data structure
(like Array) is changed during the runtime.
C provides some functions to achieve these tasks. There are 4 library functions provided by C
defined under <stdlib.h> header file to facilitate dynamic memory allocation in C programming.
They are:
1. malloc()
2. calloc()
3. free()
4. realloc()
1. malloc() method
The “malloc” or “memory allocation” method in C is used to dynamically allocate a
single large block of memory with the specified size. It returns a pointer of type void
which can be cast into a pointer of any form. It doesn’t Initialize memory at execution
time so that it has initialized each block with the default garbage value initially.
Syntax:
ptr = (cast-type*) malloc(byte-size)
For Example:
ptr = (int*) malloc(100 * sizeof(int));
Since the size of int is 4 bytes, this statement will allocate 400 bytes of memory. And, the pointer
ptr holds the address of the first byte in the allocated memory.
If space is insufficient, allocation fails and returns a NULL pointer.
Dr. Harish Kumar N, Assistant Professor, Dept. of CSE, DSCE, Bangalore -560078 2
calloc() method
1. “calloc” or “contiguous allocation” method in C is used to dynamically allocate the
specified number of blocks of memory of the specified type. it is very much similar to
malloc() but has two different points and these are:
2. It initializes each block with a default value ‘0’.
3. It has two parameters or arguments as compare to malloc().
Syntax:
ptr = (cast-type*)calloc(n, element-size);
here, n is the no. of elements and element-size is the size of each element.
For Example:
ptr = (float*) calloc(25, sizeof(float));
This statement allocates contiguous space in memory for 25 elements each with the size of the
float.
free() method
“free” method in C is used to dynamically de-allocate the memory. The memory allocated using
functions malloc() and calloc() is not de-allocated on their own. Hence the free() method is used,
whenever the dynamic memory allocation takes place. It helps to reduce wastage of memory by
freeing it.
Syntax:
free(ptr);
Dr. Harish Kumar N, Assistant Professor, Dept. of CSE, DSCE, Bangalore -560078 3
realloc() method
“realloc” or “re-allocation” method in C is used to dynamically change the memory allocation
of a previously allocated memory. In other words, if the memory previously allocated with the
help of malloc or calloc is insufficient, realloc can be used to dynamically re-allocate memory.
re-allocation of memory maintains the already present value and new blocks will be initialized
with the default garbage value.
Syntax:
ptr = realloc(ptr, newSize);
where ptr is reallocated with new size 'newSize'.
Video URl:
https://drive.google.com/file/d/1U982fCz3E1I8goBPEf96SQe6vKKZMF7T/view?usp=sh
are_link
Dr. Harish Kumar N, Assistant Professor, Dept. of CSE, DSCE, Bangalore -560078 4
STACK
Stack is a linear non primitive data structure in which insertion and deletion
are made through the same end, according to last in first out (LIFO) principles.
The operation of stack
PUSH ,POP & Display
Push the item into the stack and pop to delete an item from a stack. A stack is
a limited access data structure - elements can be added and removed from the
stack only at the top. Push adds an item to the top of the stack, pop removes
the item from the top. A helpful analogy is to think of a stack of books; you can
remove only the top book, also you can add a new book on the top. The push
and pop operation as shown in figure 1.
Figure 1. Stack operation push & pop
Function push & pop.
void push()
{
if(top ==size -1)
printf(“Stack Full”)
else
s[++top]=item;
}
void pop()
{
if(top ==-1)
printf(“Stack Empty”)
else
top--;
}
Dr. Harish Kumar N, Assistant Professor, Dept. of CSE, DSCE, Bangalore -560078 5
Video URL:
1. https://drive.google.com/file/d/10hrIJtsM9yTuGNsDpUNH9qykRY6
INlY6/view?usp=share_link
2. https://drive.google.com/file/d/1vDMXIlLe3utyeHyP_uzqoq-I2m2F
TGO6/view?usp=share_link
Application of stack
1. Conversion of expressions
2. Evaluation of Expressions
3. Recursion
Expression: An expression is a mathematical phrase that combines of numbers
, variables and the mathematical operator.
Types of expression
1. infix expression
2. postfix expression
3. prefix expression
Infix expression: In infix expression the operator is placed between two or more
operands.
Example:
Infix expression = operand1 operator operand 2
Postfix expression = operand1 operand 2 operator
Prefix expression = operator operand1 operand 2
Sl.no Infix postfix prefix
1. a+b ab+ +ab
2. a*b + c ab*c+ +*abc
3. (a-b) * (c –d) ab-cd-* *-ab-cd
4. (a+b)*d+e/(f+p*h)+m ab+d*efph*+/+m+ ++*+abd
/e+f*phm
5. ((a/(b-c+d))*(e-p)*h) abc-d+/ep-*h* **/a+-bcd-eph
6. (1 + 2 * 3 ) / 4 + 2 – 4 * 6 123*+4/2+46*- -+/+1*2342*46
7. 2+3*4/6+6*8 234*6/+68*+ ++2/*346*68
I.Algorithm to convert the infix expression into postfix expression. It uses a
stack; but in this case, the stack is used to hold operators rather than
numbers. The purpose of the stack is to reverse the order of the operators in
the expression. It also serves as a storage structure, since no operator can
be printed until both of its operands have appeared.
1. Read the infix expression
2. Initially push # onto a stack, for # set priority as -1;
Dr. Harish Kumar N, Assistant Professor, Dept. of CSE, DSCE, Bangalore -560078 6
3. If the input symbol ‘(‘ push onto a stack
4. If the input symbol is a operand then place into a postfix expression
5. If the current input symbol is an operator then check the stack of top
precedence value, if the input symbol precedence value is more than push
onto stack otherwise pop from stack.
6. If the input symbol ‘)’ then pop all the element from the stack until we get
‘(‘ and append popped operation to postfix expression. Finally just pop ‘)’.
7. Finally pop the remaining content of stack until empty and store pop
element into postfix expression and the postfix expression end with null
character.
The input priority
Symbol Symbol Value
( # 1
+ - 2
* / 3
^ $ 4
Example: (a * b) +c / d
Input read Action Stack output
( Push ( (
a Print a ( a
* Push * (* a
b Print b (* ab
) Pop * & print it ab*
+ Push + + ab*
c Print c + ab*c
/ Push / +/ ab*c
D Print d +/ ab*cd
End of the Pop element by element and Empty ab*cd/+
input print it
Program in C to convert a given valid parenthesized infix arithmetic
expression to postfix expression and then print both the expressions. The
expression consists of single character operands and the binary operators
+, - , * , /
#include<stdio.h>
#include<string.h>
#include<conio.h>
char stack[50];
int top=-1;
void push(char x)
{
Dr. Harish Kumar N, Assistant Professor, Dept. of CSE, DSCE, Bangalore -560078 7
stack[++top]=x;
}
int pop()
{
return(stack[top--]);
}
int prior(char x)
{
int p;
if(x=='('||x=='#') p=1;
if(x=='+'||x=='-') p=2;
if(x=='*'||x=='/') p=3;
if(x=='^'||x=='$') p=4;
return p;
}
void main()
{
char infix[20], postfix[20];
int i,j=0;
clrscr();
printf("Enter an infix expression:\n");
gets(infix);
push('#');
for(i=0;i<strlen(infix);i++)
{
if(isalnum(infix[i]))
postfix[j++]=infix[i];
else if(infix[i]=='(' )
push(infix[i]);
else if(infix[i]==')')
{
while(stack[top]!='(')
postfix[j++]=pop();
pop();
}
else
{
while(prior(stack[top])>=prior(infix[i]))
postfix[j++]=pop();
push(infix[i]);
}
}
while(stack[top]!='#')
postfix[j++]=pop();
postfix[j]='\0';
printf("\nPostfix expression is:\n");
puts(postfix);
getch();
Dr. Harish Kumar N, Assistant Professor, Dept. of CSE, DSCE, Bangalore -560078 8
}
II. Algorithm to Evaluation of postfix expression
1. Read the postfix expression from left to right
2. If the input symbol is an operand push into a stack
3. If the input symbol is an operator and form the following operations
+ Then result = operand1 + operand2
- Then result = operand1 - operand2
* Then result = operand1 * operand2
/ Then result = operand 1 / operand2
4. Push the result onto stack
5. Repeat steps 1 to 4 until the postfix expression ends.
Input: 634+*98++
Input Action Stack
symbol
6 Push 6 6
3 Push 3 63
4 Push 4 634
+ Pop 4 Pop 3 and perform 3+4 push 67
7
* Pop 7 pop 6 and perform 6*7 push 42
42
9 Push 9 42 9
8 Push 8 42 9 8
+ Pop 8, pop 9 and perform 9+8 push 42 17
17
+ Pop 42, pop 17 and perform 17+42 59
push 59
Display stack[top] that is 59
Program in C to evaluate a valid postfix expression using stack. Assume that
the postfix expression is read as single line consisting of non-negative single
digit operands and binary arithmetic operators. The arithmetic operators are
+(add),-(sub),*(mul) and / (divide)
#include<stdio.h>
#include<math.h>
#include<conio.h>
int stack[20], top=-1;
void push(int x)
{
stack[++top]=x;
}
int pop()
Dr. Harish Kumar N, Assistant Professor, Dept. of CSE, DSCE, Bangalore -560078 9
{
return(stack[top--]);
}
void main()
{
char s[20];
int x, i, y;
clrscr();
printf("\n evaluation of postfix expression \n");
printf("\n enter a postfix expression ");
gets(s);
for(i=0;i<strlen(s);i++)
{
if(isdigit(s[i]))
push(s[i]-'0');
else
{
y=pop();
x=pop();
switch(s[i])
{
case '+':push(x+y); break;
case '-':push(x-y); break;
case '*':push(x*y); break;
case '/':push(x/y); break;
case '^':
case '$':push(pow(x,y)); break;
}
}
}
printf("\n result is %d ",pop());
getch();
}
III. Algorithm to convert postfix expression to infix expression
1. While there are input symbol left
2. Read the next symbol from input.
3. If the symbol is an operand
Push it onto the stack.
4. Otherwise, the symbol is an operator, pop the two element from the stack
and Perform the following
P2 =pop();
P1 =pop();
Strcpy(infix,’(‘);
Strcat(infix,p1);
Strcat(infix,op);
Dr. Harish Kumar N, Assistant Professor, Dept. of CSE, DSCE, Bangalore -560078 10
Strcat(infix,p2);
Strcat(infix,’)’);
Push(infix);
5. Push the resulted string back to stack.
7. Repeat step 2 to 4 till the postfix expression ends.
8. Finally display stack of top or the infix string.
Postfix expression: ab*cd/+
Current Action Stack
input
symbol
a Push a a
b Push b ab
+ Pop 2 values from the stack, P2 = b , p1= a,
then step 4 in the algorithm. (a + b)
c Push c (a + b) c
d Push d (a + b) c d
/ Pop 2 values from the stack, P2 = d, p1= c, (a + b) ( c / d)
then step 4 in the algorithm.
+ Pop 2 values from the stack, P2 = (c / d), p1= ((a + b) + ( c /
(a + b) & then step 4 in the algorithm. d))
End of Finally display stack of top. ((a + b) + ( c /
the d))
input.
IV. Algorithm to convert prefix expression to infix expression
1. Reverse the input string
2. Read the input symbol from input.
3. If the symbol is an operand then Push it onto the stack.
4. If the symbol is an operator, pop the two element from the stack and
Perform the following
P2 =pop();
P1 =pop();
strcpy(infix,’(‘);
strcat(infix,p1);
strcat(infix,op);
strcat(infix,p2);
strcat(infix,’)’);
push (infix);
5. Push the resulted string back to stack.
7. Repeat step 2 to 4 till the end of the input string.
9. Reverse the stack of top
10. Finally display stack of top or the infix string.
Example: Prefix expression: *+ab/cd
Reverse the prefix expression: dc/ba+*
Dr. Harish Kumar N, Assistant Professor, Dept. of CSE, DSCE, Bangalore -560078 11
Current Action Stack
input
symbol
d Push d d
c Push c dc
/ Pop 2 values from the stack, P2 = c , p1= d,
then step 1 to 5 in the algorithm. (d / c)
b Push b (d / c) b
a Push a (d / c) b a
+ Pop 2 values from the stack, P2 = a, p1= b, (d / c) (b + a)
then step 1 to 5 in the algorithm.
* Pop 2 values from the stack, P2 = (a + b) , ((d / c) * (b +
p1= (c / d) & then step 1 to 5 in the a))
algorithm.
End of Then reverse stack of top , Finally display ((a+b)*(c/d))
the stack of top.
input.
V. Algorithm conversion of postfix expression to prefix expression
1. Read the input string
2. scan the current input symbol from the left
3. If the scanned character is a digit, then push it into the stack.
4. If the scanned character is an operator, then pop two elements from
the stack. Form a string containing scanned operator and two
popped elements. Push the resultant string into the stack.
P2=pop( ), p1 =pop( );
strcpy(pre,op);
strcat(pre,p1);
strcat(pre,p2)
Push (pre);
5. Finally print prefix string or stack of top.
Example: Postfix expression: ab*cd/+
Current Action Stack
input
symbol
a Push a a
b Push b ab
* Pop 2 values from the stack, P2 = b , p1= a, *ab
then step 4 in the algorithm.
c Push c *ab c
d Push d *ab c d
Dr. Harish Kumar N, Assistant Professor, Dept. of CSE, DSCE, Bangalore -560078 12
/ Pop 2 values from the stack, P2 = d, p1= c, *ab
then step 4 in the algorithm. /cd
+ Pop 2 values from the stack, P2 = /cd , p1= +*ab/cd
*ab & then step 4 in the algorithm.
End of Finally display stack of top.
the
input.
VI. Algorithm conversion of prefix expression to postfix expression
1. Read the prefix expression
2. Reverse the input expression
3. If the input symbol is an operand then push into stack[top]
4. If the input symbol is an operator then perform the following, pop two
elements from the stack p1=pop(),p2=pop()
strcpy(post, p1);
strcat(post, p2);
strcat(post, op);
push (post);
5. Repeat step 3 to 4 till the end of the reversed string.
Example: Prefix expression: *+ab-cd
Reverse: dc-ba+*
Current Action Stack
input
symbol
d Push d d
c Push c dc
- Pop 2 values from the stack, P1 = c, p2= d, cd-
then step 4 in the algorithm.
b Push b cd- b
a Push a cd- b a
+ Pop 2 values from the stack, P1 = a, p2= b, cd- ab+
then step 4 in the algorithm.
* Pop 2 values from the stack, P1 =ab+, p2= ab+cd-*
cd- & then step 4 in the algorithm.
End of Finally display stack of top. ab+cd-*
the
input.
Recursion: A function calling itself is known as recursion.
1. The following example calculates the factorial of a given number using a
recursive function
#include <stdio.h>
int factorial(unsigned int i)
Dr. Harish Kumar N, Assistant Professor, Dept. of CSE, DSCE, Bangalore -560078 13
{
if(i <= 1) return 1;
}
return i * factorial(i - 1);
}
int main()
{
int i = 15;
printf("Factorial of %d is %d\n", i, factorial(i));
return 0;
}
2. The following example generates the Fibonacci series for a given number
using a recursive function
#include <stdio.h>
int fibonaci(int i)
{
if(i == 0) return 0;
if(i == 1) return 1;
return fibonaci(i-1) + fibonaci(i-2);
}
int main()
{
int i, n;
printf(“Enter the number \n”);
scanf(“%d”,&n);
for (i = 0; i < n; i++)
{
printf("%d\t\n", fibonaci(i));
}
return 0;
}
3. Recursive function for sum of natural numbers
int sum( int n)
{
if(n==1) return 1;
Return n + sum (n-1)
}
4. Recursive function to find the gcd of two integer numbers.
#include<stdio.h>
Dr. Harish Kumar N, Assistant Professor, Dept. of CSE, DSCE, Bangalore -560078 14
void main()
{
int m,n;
printf(“Enter two integer numbers \n”);
scanf(“%d %d”,&m,&n);
printf(“The gcd of two number is %d”, gcd(m,n));
getch();
}
int gcd(int m , int n)
{
if(n==0) return m;
return gcd(n, m%n);
}
5. Recursive function to find the sum of all the array elements.
int sum(int n, int a[ ])
{
if(n==1) return a[0];
return a[n-1] + sum(n-1,a);
}
Tower of Hanoi
Tower of Hanoi is a mathematical puzzle where we have three rods (A, B, and C)
and N disks. Initially, all the disks are stacked in decreasing value of diameter i.e., the
smallest disk is placed on the top and they are on rod A. The objective of the puzzle is to
move the entire stack to another rod (here considered C), obeying the following simple
rules:
● Only one disk can be moved at a time.
● Each move consists of taking the upper disk from one of the stacks and placing it on
top of another stack i.e. a disk can only be moved if it is the uppermost disk on a
stack.
● No disk may be placed on top of a smaller disk.
Tower of Hanoi using Recursion:
The idea is to use the helper node to reach the destination using recursion. Below is the pattern
for this problem:
● Shift ‘N-1’ disks from ‘A’ to ‘B’, using C.
● Shift last disk from ‘A’ to ‘C’.
● Shift ‘N-1’ disks from ‘B’ to ‘C’, using A.
Dr. Harish Kumar N, Assistant Professor, Dept. of CSE, DSCE, Bangalore -560078 15
#include<stdio.h>
void TOH(int n,char x,char y,char z)
{
if(n>0)
{
TOH(n-1,x,z,y);
printf(" %c to %c",x,y);
TOH(n-1,z,y,x);
}
}
int main()
{
int n=3;
TOH(n,'A','B','C');
}
Video URl: https://www.youtube.com/watch?v=q6RicK1FCUs
Dr. Harish Kumar N, Assistant Professor, Dept. of CSE, DSCE, Bangalore -560078 16