SlideShare a Scribd company logo
1 of 213
Download to read offline
B.Tech II Sem „CST‟; Scheme 2020; AY: 2020_21
DATA STRUCTURES
Dr. C. Sreedhar
Unit 1: Arrays
 Introduction to Data Structures, Definition,
 Classification of Data Structures, Linear and Non Linear
 Sequential Storage Representation: Arrays,
 Operations on Arrays: Insertion, Deletion, Traversing;
 Applications of arrays: Linear Search, Binary Search,
Bubble Sort, Selection Sort, Insertion Sort, Merging of
arrays
Unit 2: Linked List
 Linked Storage Representation: Linked Lists
 Linked storage representation using pointers,
 Types of Linked Lists: Single linked list
 Double linked list
 Operations on linked lists: Traversing
 Searching, Insertion and Deletion
Unit III: Stack
 Linear Data Structures: Stacks
 Representation of stack using sequential storage
and linked allocation methods
 Operations on stacks:
 Push, Pop and Display
Unit IV: Queue
 Linear Data Structures: Queues
 Representation of Queue using sequential and
linked allocation
 Operations on Queues: Insertion, Deletion and
Traversing
 Circular queue
Unit V: Non Linear DS
 Non Linear Data Structures: Trees
 Basic terminology, Binary Trees, Representation of
Binary tree in memory using arrays and linked lists.
 Binary search trees, operations on binary search trees
 Insertion, Deletion
 Recursive traversals: Preorder, Inorder and Postorder
Definitions
 Data: a value or set of values
 Entity: is any object in the system that we want to
model and store information about
 Information: Processed data to gain knowledge
 Data type: is a classification of type of data that
a variable or object can hold.
 Built-in Data type
 Abstract Data Types (aka ADTs) are descriptions of
how a data type will work without implementation
details.
 Ex: Stack
Data Structure: Definition
 Data structure (DS) is representation of the logical
relationship existing between individual elements of data.
 Data structure is a data organization, management and
storage format that enables efficient access and
modification.
 Data structures provide a means to manage large amounts
of data efficiently for uses such as large databases
 Program=algorithm + Data Structure
DS
Linear DS Non-Linear DS
Array
Linked List Stack
Queue Graph Trees
DS : Classification
Linear Vs. Non-linear Data Structure
 The basic difference between linear and non-linear
data structure is that in linear data structures, for
each element there is a fixed next element but in
case of non-linear data structure, each element can
have many different next elelemts.
Linear DS
 Array: collection of finite number of homogeneous data elements
 Linked List: data elements are managed by collection of nodes,
where each node contains link or pointer which points to next
node in the list.
 Stacks: linear collection of data elements in which insertion and
deletion are restricted at only one end. (LIFO)
 Queues: linear collection of data elements in which insertion can
take place at one end and deletion can take place at other end.
(FIFO)
Identify the Data Structure
Array Stack
Queue
Stack
Queue
Linked
List
Non-Linear Data Structures
 Trees: is a non-linear data structure which is used to
represent data elements having hierarchical
relationship between them
 Graphs: is a non-linear data structure which is used to
represent data having relationship among its elements
which are not necessarily hierarchical in nature.
 Set: allows to add data to a container
 Table
Identify non-linear Data Structure
Tree Table Graph
Set
Graph
Applications of DS
 Stack: functions and stack, expression evaluation,
UNDO/REDO operation in word processors etc.
 Queues: Operating systems often maintain a queue of
processes that are ready to execute or that are waiting for
a particular event to occur.
 Graphs - Connections/relations in social networking sites,
Routing ,networks of communication, data organization etc.
Applications of Data Structures
 Dictionary: Arranged and ordered and unordered words
 Android Auto : City map, source, destination, shortest path
 Student details: Roll no, Name, age, address, marks, ...
 Library: Arranging books in certain order
 Travelling Salesperson problem
 Airport: Flights(Source, destination, connecting), companies...
Applications: Trees
largest element of an array
for(i = 1; i < n; i++)
{
if(arr[0] < arr[i])
arr[0] = arr[i];
}
printf("Largest element = %.2f", arr[0]);
Solved Example: Accept elements of array and display largest element
int i, n; float arr[100];
// Accept the value of n
for(i = 0; i < n; ++i)
{
printf("Enter Number %d: ", i+1); scanf("%f", &arr[i]);
}
for(i = 1; i < n; ++i)
{
if(arr[0] < arr[i])
arr[0] = arr[i];
}
printf("Largest element = %.2f", arr[0]);
Sequential Storage Representation
 Arrays:
 One dimensional Arrays
 Declaration; initialization; passing arguments to a function
 Two dimensional Arrays
 Declaration; initialization; passing arguments to a function
 Arrays Storage representation: address calculation
1 D Array: Finding address
 First location of an array is called Base Address
1D Array: Finding address
 To find the address of element of an array, say A[i],
 Address of A [ i ] = B + W * ( i – LB ); where
 B = Base address
W = Storage Size of one element stored in array
i = Subscript of element whose address is to be found
LB = Lower limit or Lower Bound of subscript

Finding address: 1D Array: Example 1
 Given Array A[20]; ie., A[0], A[1],......A[19]
 Consider B: 2000; W= 4 bytes; i= 12; Find the
address of where A[12] is stored?
 Address of A [ i ] = B + W * ( i – LB )
 A [12] = 2000 + 4 * (12-0)
= 2048
 Ans: The address of A[12] = 2048
Address calculation in 2D Arrays
 Given X[2][2]
Two types of arrangement
 Row major
 Column major
Row Major System:
Address of A [ I ][ J ] = B + W * [ N * ( I – Lr ) + ( J – Lc ) ]
Column Major System:
Address of A [ I ][ J ] = B + W * [( I – Lr ) + M * ( J – Lc )]
Where,
B = Base address
I = Row subscript of element whose address is to be found
J = Column subscript of element whose address is to be found
W = Storage Size of one element stored in the array (in byte)
Lr = Lower limit of row/start row index of matrix, if not given assume 0 (zero)
Lc = Lower limit of column/start column index of matrix, if not given assume 0 (zero)
M = Number of row of the given matrix
N = Number of column of the given matrix
2D Array Address Calculation(Row Major)
 Consider A[3][4]; with base address 2000. Find the
address of A[1][2] using row major.
 Address of A [ I ][ J ] = B + W * [N*(I – Lr)+(J–Lc) ]
 Given:
 I = 1; J = 2; W = 4 bytes; B = 2000;
 N: Total no. of cols = 4; Lr: 0; Lc: 0
 A[1][2]=2000+4*[4*(1-0)+(2-0)] = 2024
2D Array Address Calculation(Col Major)
 Consider A[3][4]; with base address 2000. Find the
address of A[1][2] using Column major.
 Address of A [ I ][ J ] = B+W*[(I – Lr)+M*( J – Lc )]
 Given:
 I = 1; J = 2; W = 4 bytes; B = 2000;
 M: Total no. of rows = 3; Lr: 0; Lc: 0
 A[1][2]=2000+4*[(1-0)+3*(2-0)] = 2028
Column Major
2D Array: Find address(Row Major)
 Consider A[10][20]; with base address 501. Find
the address of A[8][10] using row major.
 Address of A [ I ][ J ] = B + W * [N*(I – Lr)+(J–Lc) ]
 Given:
 I = 8; J = 10; W = 4 bytes; B = 501;
 N: Total no. of cols = 20; Lr: 0; Lc: 0
 A[8][10]=501+4*[20*(8-0)+(10-0)] = 1181
2D Array: Find address(Col Major)
 Consider A[10][20]; with base address 501. Find
the address of A[8][10] using Column major.
 Address of A [ I ][ J ] = B+W*[(I – Lr)+M*( J – Lc )]
 Given:
 I = 8; J = 10; W = 4 bytes; B = 501;
 M: Total no. of rows = 10; Lr: 0; Lc: 0
 A[8][10]=501+4*[(8-0)+10*(10-0)] = 933
largest element of an array
for(i = 1; i < n; i++)
{
if(arr[0] < arr[i])
arr[0] = arr[i];
}
printf("Largest element = %.2f", arr[0]);
Delete element in an Array
main()
{
....
AcceptArray(n,a);
DisplayArray(n,a);
Insert(n,a);
DisplayArray(n,a);
Delete(n,a);
DisplayArray(n,a);
}
1. Accept the position
2. Check whether position > = n+1;
True: Deletion not possible
False:
a) for(i=pos-1;i<n;i++)
a[i]=a[i+1]
b) n - -
c) print the elements of an array
3. Stop
Linear Search (Single Occurrence)
SEARCH (A [ ], n, s)
1. for(i=0; i<n; i++)
1a. if (s=A[i]) break;
2. if (i<n)
2a. Print "Element found at index, i"
3. else Print "Element not found "
4. STOP
Linear Search (Multiple occurrences)
SEARCH (A [ ], n, s)
1. Initialize count = 0
1. for(i=0; i<n; i++)
1a. if (A[i]=s)
1a.i. Print "element is found at location (i+1)"
1a.ii. count++
2. if (count=0)
2a. Print "Element is not found "
3. else Print "Element is found at count times in array "
4. STOP
 void read(int [ ],int);
 void display(int [ ],int);
 void search(int [ ],int,int);
main( ) {
//Accept n
read(a,n);
display(a,n);
do {
printf("Enter searching element:");
// Accept and store in „se‟ var
search(a,n,se);
printf("search another element?y/n: ");
scanf(" %c",&ch);
} while(ch=='y');
void read(int a[ ],int n)
{ int i; for(i=0;i<n;i++) scanf("%d",&a[i]);
}
void read(int a[ ],int n) { int i; for(i=0;i<n;i++) scanf("%d",&a[i]); }
void display(int a[ ],int n) { int i; for(i=0;i<n;i++) printf("%d ",a[i]);}
// Search for multiple occurrences
void search(int a[ ], int n, int se)
{
int i,count=0;
for(i=0;i<n;i++)
{ if(a[i]==se) { printf("%d is found at %d",se,i+1); count++; } }
if(count==0) printf("n%d is not found",se);
else printf("n%d is present %d times in array",se,count);
}
Binary Search: Algorithm
1. Initialize lb=0, ub=n-1, count = 0
2. while (lb < = ub)
2a. mid=(lb+ub)/2;
2b. if(se==a[mid])
2b.i. Print "element is found
at position,se,mid+1
2b.ii. count++;
2b.iii. break;
2c. else if(se<a[mid])
2c.i. ub=mid-1;
2d. else
2d.i lb=mid+1;
3. End while
4. if(count==0)
4a. print "Element not found"
5. STOP
Merging two arrays
void read(int [ ],int);
void display(int [ ],int);
void merge(int [ ],int [ ],int [ ],int,int);
main()
//Accept n
Read(a,n)
read(b,n);
display(a,m);
display(b,n);
merge(a,b,c,m,n);
display(c,m+n);
void read(int a[ ],int m) { int i; for(i=0;i<m;i++) scanf("%d",&a[i]); }
void display(int a[ ],int m) { int i; for(i=0;i<m;i++) printf("%d ",a[i]); }
void merge(int a[ ],int b[ ],int c[ ],int m,int n)
{
int i,j,k;
i=j=k=0;
while(i<m&&j<n)
{
if(a[i]<b[j]) c[k++]=a[i++];
else c[k++]=b[j++];
}
while(i<m) c[k++]=a[i++];
while(j<n) c[k++]=b[j++];
}
Finding Largest no. in array using fn‟s
 void CreateArray(int n,int a[ ]);
 void DisplayArray(int n,int a[ ]);
 void Largest(int n,int a[ ]);
void CreateArray(int n,int a[ ]) { int i; for(i=0;i<n;i++)
{ printf("Enter a[%d]:",i); scanf("%d",&a[i]); } }
int main()
{
.........
CreateArray(n,a);
DisplayArray(n,a);
Largest(n,a);
.....
}
void DisplayArray(int n,int a [ ]) { int i; for(i=0;i<n;i++) {
printf("%dt",a[i]); } printf("n"); }
void Largest(int n,int a[ ]) { int i; for(i=1;i<n;i++) {
if(a[0]<a[i]) a[0]=a[i]; }
printf("Largest element = %d",a[0]);
}
Lab1a) Array op‟s: insert,delete,traverse
void create();
void display();
void insert();
void del();
void create() { int i; for(i=0;i<n;i++) {
printf("Enter a[%d]:",i); scanf("%d",&a[i]); } }
int main()
{
.........
do { create(); display()
insert(); delete(); exit();
}while(..)
.....
}
void display() { int i; for(i=0;i<n;i++) { printf("%dt",a[i]); } }
void insert( ) {
// Accept the position to insert and store in „pos‟ variable
// Accept the value to insert and store in „val‟ variable
for(i=n-1;i>=pos-1;i--) a[i+1]=a[i]; a[pos-1]=val; n=n+1; }
void del() { // Accept the „pos‟; val=a[pos-1];
for(i=pos-1;i<n;i++) a[i]=a[i+1]; n=n-1;
printf("nThe deleted element is =%d",val); }
Lab 2a) Linear Search
 void read(int [ ],int);
 void display(int [ ],int);
 void search(int [ ],int,int);
void search(int a[ ], int n, int s) { // Single Occurance
...
for(i=0; i<n; i++) if (s=A[i]) break;
if (i<n) Print "Element found at index, i“
else Print "Element not found “ }
main() { //Accept n
read(a,n); display(a,n);
do { // Accept „se‟
search(a,n,se); }while(..);
}
void search (int a [ ], int n, int s){ // Multiple Occurances ...
Initialize count = 0
for(i=0; i<n; i++) if (A[i]=s)
{ Print "element is found at location (i+1)“
count++ } if (count=0) Print "Element is not found “
else Print "Element is found at count times in array “
}
Lab 2b) Binary Search
 void read(int [ ],int);
 void display(int [ ],int);
 void search(int [ ],int,int);
main() { //Accept n
read(a,n); display(a,n);
do { // Accept „se‟
search(a,n,se); }while(..);
}
void search(int a[ ],int n,int se) {
int lb,ub,mid,count=0; lb=0; ub=n-1;
while(lb<=ub) { mid=(lb+ub)/2;
if(se==a[mid]) { printf("nThe element %d is found
at position %dn",se,mid+1); count++; break;
}
else if(se<a[mid]) ub=mid-1;
else lb=mid+1;
}
if(count==0) printf("nElement not found");
}
Binary Search: Algorithm
1. Initialize lb=0, ub=n-1, count = 0
2. while (lb < = ub)
2a. mid=(lb+ub)/2;
2b. if(se==a[mid])
2b.i. Print "element is found
at position,se,mid+1
2b.ii. count++;
2b.iii. break;
2c. else if(se<a[mid])
2c.i. ub=mid-1;
2d. else
2d.i lb=mid+1;
3. End while
4. if(count==0)
4a. print "Element not found"
5. STOP
Merging of two sorted arrays
 Enter size of first array: 4
 Enter elements of first array: 1 3 5 7
 Enter size of Second array: 4
 Enter elements of Second array: 2 4 6 8
 Merged Final Sorted array elements are:
1 2 3 4 5 6 7 8
Merging of two sorted arrays
1 3 5 7 2 4 6 8
A B
C
Merging of two sorted arrays
1 3 5 7 2 4 6 8
A B
C
i j
1 2
<
1
Merging of two sorted arrays
1 3 5 7 2 4 6 8
A
B
C
j
1 2
<
1
i
3
2
Merging of two sorted arrays
1 3 5 7 2 4 6 8
A
B
C
1 2
<
1
i
3
2
j
4
3
Merging of two sorted arrays
1 3 5 7 2 4 6 8
A
B
C
1 2
<
1
i
3
2
j
4
3
5
4
Merging of two sorted arrays
1 3 5 7 2 4 6 8
A
B
C
1 2
<
1
i
3
2
j
4
3
5
4
6
5
Merging of two sorted arrays
1 3 5 7 2 4 6 8
A
B
C
1 2
<
1
i
3
2
j
4
3
5
4
6
5
7
6
Merging of two sorted arrays
1 3 5 7 2 4 6 8
A
B
C
1 2
<
1
i
3
2
j
4
3
5
4
6
5
7
6
8
7 8
How to code?
if ( a [ i ] < b [ j ] )
c[ k++ ] = a[ i++ ];
else
c[ k++ ] = b[ j++ ];
while( i<m && j<n )
{
}
while( i < m ) c[ k++ ] = a[ i++ ];
while( j < n ) c[ k++ ] = b[ j++ ];
Merging function definition
void merge( ..........)
{
int i,j,k; i=j=k=0;
while( i<m && j<n )
{
if ( a [ i ] < b [ j ] ) c[ k++ ] = a[ i++ ];
else c[ k++ ] = b[ j++ ];
}
while( i < m ) c[ k++ ] = a[ i++ ];
while( j < n ) c[ k++ ] = b[ j++ ];
Merging two arrays: Complete Program
void read(int [ ],int);
void display(int [ ],int);
void merge(int [ ],int [ ],int [ ],int,int);
main() {
//Accept n
read(a,n)
read(b,n);
display(a,m);
display(b,n);
merge(a,b,c,m,n);
display(c,m+n); ..}
void read(int a[ ],int m) { int i; for(i=0;i<m;i++) scanf("%d",&a[i]); }
void display(int a[ ],int m) { int i; for(i=0;i<m;i++) printf("%d ",a[i]); }
void merge(int a[ ],int b[ ],int c[ ],int m,int n) {
int i,j,k; i=j=k=0;
while(i<m&&j<n) {
if(a[i]<b[j]) c[k++]=a[i++];
else c[k++]=b[j++];
}
while(i<m) c[k++]=a[i++];
while(j<n) c[k++]=b[j++];
}
Sorting
 Sorting is the process of arranging unordered elements
into ordered (Ascending or descending order) elements.
 Sorting algorithms:
 Bubble Sort; Selection Sort; Recursive Bubble Sort;
 Insertion Sort; Merge Sort; Quick Sort; Heap Sort
 Radix sort; Bucket Sort; Shell Sort; Pigeonhole Sort;
 Pancake Sort; Gnome Sort; Stooge Sort; Tag Sort; Tree Sort
Bubble Sort: Input and Output
 Enter the size of the array : 6
 Enter the elements of the array : 4 3 6 1 5 2
 After sorting, elements of the array are:
1 2 3 4 5 6
Bubble Sort: Logic
6, 2, 9, 11, 9, 3, 7, 12
i
j
a[ j ] a[ j+1 ]
> then swap < then increment j
Swap
temp = a[ j ]
a[ j ] = a[ j+1 ]
a[ j+1 ] = temp
Iterate range of j: 0 to j < n-1-i
Iterate range of i: 0 to i < n-1
Bubble Sort: How to Code?
if(a[ j ] > a[ j+1 ])
{
temp = a[ j ];
a[ j ] = a[ j+1 ];
a[ j+1 ] = temp;
}
for(i=0;i < n-1;i++)
{
for(j=0;j < n-1-i;j++)
{
}
}
Defining Bubble Sort function
void sort(int a[ ],int n)
{
int i,j,temp;
for(i=0;i<n-1;i++)
{
for(j=0;j<n-1-i;j++)
{ if(a[ j ]>a[ j+1 ]) {temp=a[j]; a[j]=a[j+1]; a[j+1]=temp;}
}
}
}
Bubble Sort: Program
void read(int [ ],int);
void display(int [ ],int);
void bsort(int [ ],int);
int main() { // Declare necessary variables
// Accept size of the array and store in „n‟ variable
do
{
read(a,n);
display(a,n);
bsort(a,n);
printf(“Array after sorting are:");
display(a,n);
// Accept ch and decide to repeat or exit
} while(ch=='y'); return 0; }
// Define read(int [ ],int)
// Define display(int [ ],int)
// Define bsort(int [ ],int)
Selection Sort
void ssort ( )
{
int i, j, min, temp;
for (i=0; i<n; i++)
{
min = i;
for ( j=i+1; j<n; j++)
{
if (a[ j ] < a[min]) min = j;
}
temp = a[i]; a[i] = a[min]; a[min] = temp;
}
}
Selection Sort: Complete Program
void ssort ( );
int a[30], n;
int main()
{
// Declare variables
// Accept the size of array, store in „n‟
// Accept the elements of array, store in a[i]
ssort();
printf("nnAfter sorting:n");
// Display elements of array
}
void ssort ( )
{
int i, j, min, temp;
for (i=0; i<n; i++)
{
min = i;
for ( j=i+1; j<n; j++)
{
if (a[ j ] < a[min]) min = j;
}
temp = a[i]; a[i] = a[min]; a[min] = temp;
}
}
Insertion Sort: Logic
5 4 3
2 6 1
5 4 3
2 6 1
2 5
4 5 j=0
6
1
1 5
4
1
2
1 3 6
3 5
3 4 j=1
j=2
j=3
j=4
j=5
Insertion Sort
void isort(int a[ ],int n)
{
int i,j,key;
for(i=1;i<n;i++)
{
key=a[i];
for( j = i-1; j >= 0 && a[ j ] > key; j--) { a[ j+1]=a[ j ]; }
a[j+1]=key;
}
}
Insertion Sort: Complete program
void read(int [ ],int);
void display(int [ ],int);
void isort(int [ ],int);
int main()
{
// Declare necessary variables
// Accept size and store it in „n‟ variable
read(a,n);
display(a,n); // Before sorting
isort(a,n);
display(a,n); // After sorting
return 0;
}
// Define read(int [ ],int);
// Define display(int [ ],int);
// Define isort(int [ ],int);
Merge sort example
index 0 1 2 3 4 5 6 7
value 22 18 12 -4 58 7 31 42
22 18 12 -4
22 18
22 18
18 22
merge
split
12 -4
12 -4
-4 12
merge
split
split
-4 12 18 22
58 7 31 42
58 7
58 7
7 58
merge
split
31 42
31 42
31 42
merge
split
split
7 31 42 58
-4 7 12 18 22 31 42 58
split
merge merge
merge
Merge Sort: Function
void sort(int a[ ],int lb,int ub)
{
int mid;
if(lb<ub)
{
mid=(lb+ub)/2;
sort(a,lb,mid);
sort(a,mid+1,ub);
merge(a,lb,mid,ub);
}
}
void merge(int a[ ],int lb,int mid,int ub)
{
int b[50],i,j,k;
i=lb,j=mid+1,k=lb;
while(i<=mid&&j<=ub)
{
if(a[i]<a[j]) b[k++]=a[i++]; else b[k++]=a[j++];
}
while(i<=mid) b[k++]=a[i++];
while(j<=ub) b[k++]=a[j++];
for(i=lb;i<=ub;i++) a[i]=b[i];
}
Merge Sort: Complete Program
void read(int [ ],int);
void display(int [ ],int);
void sort(int [ ],int,int);
void merge(int [ ],int,int,int);
int main()
{
// Declare necessary variables
// Accept size of array and store it in „n‟
read(a,n);
display(a,n); // Before sorting
sort(a,0,n-1);
display(a,n); // After Sorting
return 0;
}
// Define read(int [ ],int)
// Define display(int [ ],int)
// Define sort(int [ ],int,int)
//Define merge(int [ ],int,int,int)
Unit 2: Linked Lists
 Linked Storage representation using pointers
 Types of Linked List:
 Single Linked List
 Double Linked List
 Operations on Linked Lists:
 Traversing
 Searching
 Insertion and Deletion
Linked List
 A Linked list is an ordered collection of finite,
homogeneous data elements called nodes, where
the linear order is maintained by means of links or
pointers.
 Each node is composed of data and a reference to
the next node in the sequence. This structure allows
for efficient insertion or removal of elements from
any position in the sequence during iteration.
Advantages of Linked Lists
 Linked lists are a dynamic data structure, which can grow and shrink during
the execution of the program.
 Insertion and deletion node operations are easily implemented in a linked list.
 Dynamic data structures such as stacks, queues can be implemented using
linked list.
 There is no need to define an initial size for a linked list.
 Items can be added or removed from the middle of list.
 Linked lists have efficient memory utilization. Memory is not pre-allocated in
linked list. Memory is allocated whenever it is required and is de-allocated
when it is no longer needed.
Disadvantages of Linked Lists
 They use more memory than arrays because of the storage
used by their pointers.
 Nodes in a linked list must be read in order from the beginning
as linked lists are inherently sequential access.
 Difficulties arise in linked lists when it comes to reverse
traversing. For instance, singly linked lists are cumbersome to
navigate backwards and while doubly linked lists are
somewhat easier to read, memory is consumed in allocating
space for a back-pointer.
Types of LL
 Single Linked List
 Double Linked List
 Circular Linked List
Create SLL
head
Data *link
one
Create a node One,
which contains data
and a link. Assign initial
value of data to 10
and link to NULL.
Traverse the single
linked list
SLL
typedef struct sll
{
int data;
struct sll *next;
}node;
node *head=NULL;
void display( );
void main()
{
int n;
node *one; one=NULL;
one=(node *) malloc (sizeof (node) );
onedata=10;
one  next=NULL;
head=one; display( );
}
Traversing SLL
void display()
{
node *temp;
if(head==NULL) printf("List is empty");
else
{
temp=head;
while(temp!=NULL)
{
printf(“n%d",temp->data);
temp=temp->next;
}
}
}
Create SLL with the following
head
Data(10) *next
one two
Data(20) *next Data(30) NULL
three
Coding SLL
typedef struct sll
{
int data;
struct sll *next;
}node;
node *head=NULL;
void main()
{
int n;
node *one,*two,*three;
one=NULL; two=NULL; three=NULL;
one=(node *)malloc(sizeof(node));
two=(node *)malloc(sizeof(node));
three=(node *)malloc(sizeof(node));
onedata=10; two  data=20; three  data=30;
one->next=two; two->next=three; three->next=NULL;
head=one;
display();
getch();
}
Create n nodes in SLL
typedef struct sll
{ int data; struct sll *next; }node;
node *head=NULL;
void createList(int n);
void traverseList();
int main()
{
int n;
printf("Enter n: "); scanf("%d", &n);
createList(n);
traverseList();
return 0;
}
void createList(int n)
{
node *newNode,*temp; int data, i;
head = (node *)malloc(sizeof(node));
if(head == NULL) printf("Unable to allocate memory.");
else
{
printf("Enter the data of node 1: "); scanf("%d", &data);
head->data = data; head->next = NULL;
temp = head;
for(i=2; i<=n; i++)
{
newNode = (node *)malloc(sizeof(node));
if(newNode == NULL)
{ printf("Unable to allocate memory.");
break; }
else
{
printf("nEnter data of node %d: ", i); scanf("%d", &data);
newNode->data = data; newNode->next = NULL;
temp->next = newNode;
temp = temp->next; } } } }
Single Linked List Creating node
typedef struct slist
{
int no;
char name[50];
struct slist *link;
} node;
node *first=NULL;
no name *link
first
node
NULL
Linked Lists
 A linked list is a series of connected nodes
 Each node contains at least
 A piece of data (any type)
 Pointer to the next node in the list
 Head: pointer to the first node
 The last node points to NULL
A 
Head
B C
A
data pointer
node
Create SLL with the following
head
Data(10) *next
one two
Data(20) *next Data(30) NULL
three
SLL: Create three nodes and traverse
typedef struct sll
{
int data;
struct sll *next;
}node;
node *head=NULL;
void main()
{
int n;
node *one,*two,*three;
one=NULL; two=NULL; three=NULL;
one=(node *)malloc(sizeof(node));
two=(node *)malloc(sizeof(node));
three=(node *)malloc(sizeof(node));
onedata=10; two  data=20; three  data=30;
one->next=two; two->next=three; three->next=NULL;
head=one;
display();
}
Create n nodes in SLL
typedef struct sll
{ int data; struct sll *next; }node;
node *head=NULL;
void createList(int n);
void traverseList();
int main()
{
int n;
printf("Enter n: "); scanf("%d", &n);
createList(n);
traverseList();
return 0;
}
void createList(int n)
{
node *newNode,*temp; int data, i;
head = (node *)malloc(sizeof(node));
if(head == NULL) printf("Unable to allocate memory.");
else
{
printf("Enter the data of node 1: "); scanf("%d", &data);
head->data = data; head->next = NULL;
temp = head;
for(i=2; i<=n; i++)
{
newNode = (node *)malloc(sizeof(node));
if(newNode == NULL)
{ printf("Unable to allocate memory."); break; }
else
{
printf("nEnter data of node %d: ", i); scanf("%d", &data);
newNode->data = data; newNode->next = NULL;
temp->next = newNode;
temp = temp->next; } } } }
Insert node at the beginning
48 17 142
head //
head 93
Step 1 Step 2
Step 3
Insert node at the end of the list
48 17 142
head //
Step 1 Step 2
Step 3
Insert node at specified position
Step 1 Step 2
Step 3
Step 4
SLL: Inserting a node
void insertion( )
{
node *p,*save,*ptr;
p=(node *) malloc(sizeof(node));
printf("nEnter rollno and name:");
scanf("%d %s",&pno,pname);
if(first==NULL)
{
plink=NULL;
first=p;
return;
}
save
ptr
1001 sree *link
first
NULL
p
p
1001 sree NULL
SLL: Insertion
if(p->no <= first->no)
{
p->link = first;
first = p;
return;
}
save = first; ptr = firstlink;
while(ptr !=NULL && ptrno < pno)
{
save = ptr;
ptr = ptr->link;
}
savelink = p;
plink = ptr;
}
1002 sri *link
p
1002 < = 1001
False
first
save
ptr
1001 sree NULL
SLL: Insertion
if(p->no <= first->no)
{
p->link = first;
first = p;
return;
}
save = first; ptr = firstlink;
while(ptr !=NULL && ptrno < pno)
{
save = ptr;
ptr = ptr->link;
}
savelink = p;
plink = ptr;
}
1004 dennis *link
p
1004 < = 1001
False
first
save
ptr
1001 sree NULL
void createList(int n);
void insertB(int data);
void insertE(int data);
void insertM(int data, int position);
void deleteF();
void displayList();
printf("nEnter data to insert at beginning of the list: ");
scanf("%d", &data);
insertB(data);
displayList();
printf("nEnter data to insert at middle of the list: ");
scanf("%d", &data);
printf("Enter the position to insert new node: " );
scanf("%d", &position);
insertM(data, position);
displayList();
printf("nEnter data to insert at end of the list: ");
scanf("%d", &data);
insertE(data);
printf("nPress 1 to delete first node: ");
scanf("%d", &choice);
if(choice == 1) deleteF();
displayList();
void insertB(int data)
{
struct node *newNode;
newNode = (struct node*)malloc(sizeof(struct node));
if(newNode == NULL) { printf("Unable to allocate memory."); }
else
{
newNode->data = data; // Link data part
newNode->next = head; // Link address part
head = newNode; // Make newNode as first node
printf("DATA INSERTED SUCCESSFULLYn");
}
}
void insertM(int data, int position)
{
int i; struct node *newNode, *temp;
newNode = (struct node*)malloc(sizeof(struct node));
if(newNode == NULL) { printf("Unable to allocate memory."); }
else
{
newNode->data = data; // Link data part
newNode->next = NULL;
temp = head;
for(i=2; i<=position-1; i++) { temp = temp->next; if(temp == NULL) break;}
if(temp != NULL)
{
newNode->next = temp->next;
temp->next = newNode;
printf("DATA INSERTED SUCCESSFULLYn");
}
else printf("UNABLE TO INSERT DATA AT THE GIVEN POSITIONn"); } }
void insertB(int data)
{
struct node *newNode;
newNode = (struct node*)malloc(sizeof(struct node));
if(newNode == NULL)
printf("Unable to allocate memory.");
else
{
newNode->data = data;
newNode->next = head;
head = newNode;
printf("DATA INSERTED SUCCESSFULLYn");
}
}
void insertM(int data, int position)
{
int i;
struct node *newNode, *temp;
newNode = (struct node*)malloc(sizeof(struct node));
if(newNode == NULL)
printf("Unable to allocate memory.");
else
{
newNode->data = data; // Link data part
newNode->next = NULL;
temp = head;
for(i=2; i<=position-1; i++)
{
temp = temp->next;
if(temp == NULL)
break;
}
if(temp != NULL)
{
/* Link address part of new node */
newNode->next = temp->next;
/* Link address part of n-1 node */
temp->next = newNode;
printf("DATA INSERTED SUCCESSFULLYn");
}
else
{
printf("UNABLE TO INSERT DATA AT THE GIVEN POSITIONn");
}
}
}
void insertE(int data)
{
struct node *newNode, *temp;
newNode = (struct node*)malloc(sizeof(struct node));
if(newNode == NULL)
{
printf("Unable to allocate memory.");
}
else
{
newNode->data = data;
newNode->next = NULL;
temp = head;
while(temp->next != NULL)
temp = temp->next;
temp->next = newNode; // Link address part
printf("DATA INSERTED SUCCESSFULLYn");
}
}
void deleteF()
{
struct node *toDelete;
if(head == NULL)
printf("List is already empty.");
else
{
toDelete = head;
head = head->next;
printf("nData deleted = %dn", toDelete->data);
/* Clears the memory occupied by first node*/
free(toDelete);
printf("SUCCESSFULLY DELETED FIRST NODE FROM LISTn");
}
}
Double Linked List
struct node { int data; struct node *prev, *next; };
struct node *head = NULL;
static int node_count = 0;
struct node *createNode(int);
void insertNode(int);
void deleteNode(int);
void display();
/* creating a new node */
struct node* createNode(int data)
{
struct node *ptr = (struct node *)malloc(sizeof (struct node));
ptr->data = data;
ptr->prev = NULL; ptr->next = NULL;
return (ptr);
}
void display() {
struct node *ptr = head; int i = 0;
while (ptr) { printf("data in node%d:%dn", i, ptr->data);
ptr = ptr->next; i++;
}
}
/* Insert a new node at the end of the list */
void insertNode(int data)
{
struct node *temp, *ptr = createNode(data);
if (!head) { head = ptr; node_count++; return; }
else { temp = head;
while (temp) {
if (temp->next == NULL)
{ temp->next = ptr; ptr->prev = temp;
node_count++; return; }
temp=temp->next;
} } }
/* Insert a new node at the end of the list */
void insertNode(int data)
{
struct node *temp, *ptr = createNode(data);
if (!head) { head = ptr; node_count++; return; }
else { temp = head;
while (temp) {
if (temp->next == NULL)
{ temp->next = ptr; ptr->prev = temp;
node_count++; return; }
temp=temp->next;
} } }
/* Insert a new node at the end of the list */
void insertNode(int data)
{
struct node *temp, *ptr = createNode(data);
if (!head) { head = ptr; node_count++; return; }
else { temp = head;
while (temp) {
if (temp->next == NULL)
{ temp->next = ptr; ptr->prev = temp;
node_count++; return; }
temp=temp->next;
} } }
Double Linked List: Deletion
head(200) (400)
NULL 10 (400) (200) 20 (600)
(600)
(400) 30 (800)
(800)
(600) 40 NULL
delete(10)
head(400)
NULL 20 (600)
(600)
(400) 30 (800)
(800)
(600) 40 NULL
Double Linked List: Deletion
head(200) (400)
NULL 10 (400) (200) 20 (600)
(600)
(400) 30 (800)
(800)
(600) 40 NULL
delete(20)
head(200)
NULL 10 (600)
(600)
(200) 30 (800)
(800)
(600) 40 NULL
Double Linked List: Deletion
head(200) (400)
NULL 10 (400) (200) 20 (600)
(600)
(400) 30 (800)
(800)
(600) 40 NULL
delete(30)
head(200)
NULL 10 (400)
(400)
(200) 20 (800)
(800)
(400) 40 NULL
Double Linked List: Deletion
head(200) (400)
NULL 10 (400) (200) 20 (600)
(600)
(400) 30 (800)
(800)
(600) 40 NULL
delete(40)
head(200)
NULL 10 (400)
(400)
(200) 20 (800)
(600)
(400) 30 NULL
/* delete the node with given data */
void deleteNode(int data)
{
struct node *ptr, *temp = head;
if (head == NULL) { printf("Data unavailablen"); return; }
else if (temp->data == data)
{
ptr = temp->next; temp->next = NULL; free(temp);
head = ptr; node_count--;
}
else {
while (temp->next != NULL && temp->data != data)
{ ptr = temp; temp = temp->next; }
if (temp->next == NULL && temp->data != data)
{ printf("Given data unvavailable in listn"); return; }
/* delete the node with given data */
void deleteNode(int data)
{
struct node *ptr, *temp = head;
if (head == NULL) { printf("Data unavailablen"); return; }
else if (temp->data == data)
{
ptr = temp->next; temp->next = NULL; free(temp);
head = ptr; node_count--;
}
else {
while (temp->next != NULL && temp->data != data)
{ ptr = temp; temp = temp->next; }
if (temp->next == NULL && temp->data != data)
{ printf("Given data unvavailable in listn"); return; }
else if (temp->next != NULL && temp->data == data)
{
ptr->next = temp->next;
temp->next->prev = temp->prev;
temp->next = NULL;
temp->prev = NULL;
free(temp);
printf("Data deleted successfullyn"); node_count--;
}
else if (temp->next == NULL && temp->data == data)
{
ptr->next = NULL; temp->next = temp->prev = NULL;
free(temp); printf("Data deleted successfullyn"); node_count--;
}
}
}
int main() {
int ch, data;
while (1)
{
printf("1.Insertionn2.Deletion 3. Display 4.Exitn Enter your choice n");
scanf("%d", &ch);
switch (ch)
{
case 1: printf("Enter data to insert:"); scanf("%d", &data); insertNode(data); break;
case 2: printf("Enter data to delete:"); scanf("%d", &data); deleteNode(data); break;
case 3: display(); break;
case 4: exit(0);
default: printf("please enter right optionn"); break;
}
}
}
Stack
Stack is an ordered list of similar data type.
Stack is a linear data structure in which the insertion and deletion
operations are performed at only one end.
Stacks can be implemented using either array or LL.
Stack follows LIFO (Last In First Out) principle.
push() function is used to insert new elements into Stack and pop()
function is used to remove an element from stack.
Both insertion and removal are allowed at only one end of Stack
called Top.
Stack is said to be in Overflow state when it is completely full
and is said to be in Underflow state if it is completely empty.
Applications of Stacks
 Many compilers use a stack for parsing the syntax of
expressions, program blocks etc. before translating into
low level code.
 Stack is used to evaluate prefix, postfix and infix
expressions.
 Reverse a string
 Processing function calls and return addresses
Stack Operations
 Push an element into stack
 Pop an element from stack
 Display the elements of stack
 Count the number of elements in the stack
#define MAX 6
int top=-1,stack[MAX];
void push(); void pop(); void display();
int main() {
int ch;
while(1) {
printf("n1.Pushn 2.Popn 3.Displayn 4.Exit");
printf("nEnter your choice(1-4):"); scanf("%d",&ch);
switch(ch)
{
case 1: push(); break; case 2: pop(); break;
case 3: display(); break; case 4: exit(0);
default: printf("nWrong Choice!!"); return 0; } } }
void push()
{
int val;
if(top==MAX-1) printf("nStack is full!!");
else
{
printf("nEnter element to push:");
scanf("%d",&val);
top=top+1;
stack[top]=val;
}
}
Push operation in stack (Array)
n = 6
top = -1
stack[0]
stack
stack[1]
stack[2]
stack[3]
stack[4]
stack[5]
Push ( )
Accept element 10
Increment top top = -1+1 = 0
top =0
Insert element in stack[top] 10
Push operation in stack (Array)
n = 6
top = 0
stack[0]
stack
stack[1]
stack[2]
stack[3]
stack[4]
stack[5]
Push ( )
Accept element 20
Increment top top = 0+1 = 1 top =1
Insert element in stack[top] 10
20
Push operation in stack (Array)
n = 6
top = 1
stack[0]
stack
stack[1]
stack[2]
stack[3]
stack[4]
stack[5]
Push ( ) top =2
10
20
30
Push operation in stack (Array)
n = 6
top = 2
stack[0]
stack
stack[1]
stack[2]
stack[3]
stack[4]
stack[5]
Push ( )
top =3
10
20
30
40
Push operation in stack (Array)
n = 6
top = 3
stack[0]
stack
stack[1]
stack[2]
stack[3]
stack[4]
stack[5]
Push ( )
top =4
10
20
30
40
50
Push operation in stack (Array)
n = 6
top = 4
stack[0]
stack
stack[1]
stack[2]
stack[3]
stack[4]
stack[5]
Push ( )
top =5
10
20
30
40
50
60
Push operation in stack (Array)
n = 6
top = 5
stack[0]
Stack is Full
stack[1]
stack[2]
stack[3]
stack[4]
stack[5]
Push ( )
top =5
10
20
30
40
50
60
if(top == n-1)
Print "Stack is Full"
void pop()
{
if(top==-1) printf("nStack is empty!!");
else
{
printf("nDeleted element is %d",stack[top]);
top=top-1;
}
}
void display()
{
int i;
if(top==-1) printf("nStack is empty!!");
else
{
printf("nStack is...n");
for(i=top; i >= 0 ;--i)
printf("%dn",stack[i]);
}
}
Display number of elements in stack
 static int count=0;
 Push function:
 After inserting an element, increment count
 Pop function
 After deleting an element, decrement count
 Display function
 Print “Count”
Stacks
 Demonstration of Stack using array
Stack using Linked List: Push Operation
no *next
node
Push ( )
10 NULL
(200)
(220)
20 (200)
(240)
30 (220)
(260)
30 (240)
top
Stack using Linked List: Pop Operation
10 NULL
(200)
(220)
20 (200)
(240)
30 (220)
(260)
30 (240)
top ptr
Stack using Linked List: Pop Operation
10 NULL
(200)
(220)
20 (200)
(240)
30 (220)
(260)
30 (240)
top
ptr
Stack using Linked List: Implementation
 Define node
struct Node
{
int data;
struct Node *next;
}*top = NULL;
void push(int);
void pop();
void display();
main() {
int choice, value;
while(1) {
printf("1. Pushn2. Popn3. Displayn4. Exitn");
printf("Enter your choice: "); scanf("%d",&choice);
switch(choice){
case 1: printf("Enter the value to be insert: ");
scanf("%d", &value); push(value);
break;
case 2: pop(); break;
case 3: display(); break;
case 4: exit(0);
default: printf("nWrong Option!!!n");
}
}
}
void push(int value)
{
struct Node *newNode;
newNode = (struct Node*)malloc(sizeof(struct Node));
newNode  data = value;
if(top == NULL)
newNodenext = NULL;
else
newNode  next = top;
top = newNode;
printf("nInsertion is Success!!!n");
}
void pop()
{
if(top == NULL)
printf("nStack is Empty!!!n");
else{
struct Node *temp = top;
printf("nDeleted element: %d", tempdata);
top = tempnext;
free(temp);
}
}
void display()
{
if(top == NULL) printf("nStack is Empty!!!n");
else{
struct Node *temp = top;
while(tempnext != NULL)
{
printf("%d--->",temp->data);
temp = temp  next;
}
printf("%d--->NULL",tempdata);
}
}
Stack using Linked List: Implementation
 Define node
typedef struct stack
{
int no;
struct stack *next;
} node;
node *top=NULL;
static int count=0;
void push();
void pop();
void display();
node *p;
p=(node *)malloc(sizeof(node));
printf("Enter no. to be pushed: "); scanf("%d",&p->no);
if(top==NULL) { pnext=NULL; top=p; count++; return; }
pnext=top;
top=p;
count++;
Push Operation: Implementation
Pop Operation: Implementation
node *ptr;
if(top==NULL) { printf("Stack is Empty"); return; }
ptr=top;
printf(“Popped number is: %d",ptrno);
top=topnext;
free(ptr);
count--;
}
Display Operation: Implementation
node *ptr;
printf("Total elements=%d",count);
if(top==NULL) { printf("nStack is empty"); return; }
ptr=top;
while(ptr != NULL)
{
printf("%d ",ptrno);
ptr=ptrnext;
}
Main function
void main()
{
int ch;
do
{
printf("n1.Push 2.Pop 3.Display 4.Exit");
printf("nEnter your choice: "); scanf("%d",&ch);
switch(ch) {case 1:push();break; case 2:pop(); break; case 3:display();
}
}
while(ch<4);
}
Unit 4
 Queue in Data structure
 Applications of Queues
 Operations on Queues
 Queue implementation using Arrays & LL
 Circular Queue
What is Queue
 Queue is a linear data structure in which the
insertion operation takes place at one end (Rear)
and deletion operation at the other end (Front).
 Queues can be implemented using either array or
linked list.
 Queue follows FIFO (First In First Out) principle
Queue Operations
 Enqueue
 Dequeue
 Display the elements of Queue
 Queues can be implemented using either Array of
Linked List
Queue using array (Insertion)
if (rear == MAX - 1)
printf("Queue is Full n");
else
{
if (front == - 1) front = 0;
printf("Insert element in queue : ");
scanf("%d", &value);
rear = rear + 1;
QueueA[rear] = value;
}
front = rear = -1
rear == MAX – 1
Print Queue Full front = -1 True: front = 0
Accept value
rear = rear + 1
QueueA[rear] = value
False:
True:
Queue using array (Deletion)
if (front == - 1 || front > rear)
{
printf("Queue is Empty n");
return ;
}
else
{
printf(“Deleted no. is : %dn",
QueueA[front]);
front = front + 1;
}
Print 'Deleted no. is', QueueA[front]
front = front + 1
Queue is empty when?
front = -1 front > rear
||
print Queue is Empty
False:
True:
Queue using Array (Display)
if (front == - 1)
printf("Queue is empty n");
else
{
printf("Queue is : n");
for (i = front; i <= rear; i++)
printf("%d ", QueueA[i]);
}
i = front i<=rear
Print QueueA[i]
i++
front = -1
Print "Queue is Empty"
for( ; ; )
False:
True:
Queue using Linked List: Insertion
10 NULL
no *next
node
(200)
front = NULL
rear = NULL
front = (200)
rear = NULL
(220)
20 NULL
10 (220)
front = (200)
rear = (220)
(240)
30 NULL
20 (240)
front = (200)
rear = (240)
(260)
40 NULL
30 (260)
front = (200)
rear = (260)
Queue using Linked List: Deletion
(200) (220)
20 NULL
(240)
30 NULL
20 (240)
(260)
40 NULL
30 (260)
front = (200)
rear = (260)
10 (220)
front = (200)
rear = (260)
ptr= front = (200)
10 (220)
Queue using Linked List: Deletion
(200) (220)
20 NULL
(240)
30 NULL
20 (240)
(260)
40 NULL
30 (260)
front = (220)
rear = (260)
10 (220)
front = (220)
rear = (260)
ptr = (200)
10 (220)
Queue using Linked List: Deletion
(200) (220)
20 NULL
(240)
30 NULL
20 (240)
(260)
40 NULL
30 (260)
front = (220)
rear = (260)
10 (220)
front = (220)
rear = (260)
ptr = (220)
10 (220)
Queue using Linked List: Deletion
(220)
20 NULL
(240)
30 NULL
20 (240)
(260)
40 NULL
30 (260)
front = (220)
rear = (260)
front = (220)
rear = (260)
ptr = (220)
Queue using Linked List: Deletion
(220)
20 NULL
(240)
30 NULL
20 (240)
(260)
40 NULL
30 (260)
front = (220)
rear = (260)
front = (240)
rear = (260)
ptr = (220)
Queue using Linked List: Deletion
(240)
30 NULL
(260)
40 NULL
30 (260)
front = (240)
rear = (260)
front = (240)
rear = (260)
ptr = (240)
Queue using Linked List
 Algorithm and Explanation for Insertion (Enqueue)
 Algorithm and Explanation for Deletion (Dequeue)
 Algorithm and Explanation for Display (Traversing)
Alg & Explanation for Insertion
no *next
node
Insertion()
1. Create node p and allocate memory
2. Accept no, store in p  no
3. Assign plink=NULL;
4. Check if rear=NULL
True:
a. front=rear=p;
b. return;
5. rear  link=p;
6. rear = p;
10 NULL
(200)
front = rear = NULL
front rear
(220)
20 NULL
10 (220)
Alg & Explanation for Insertion
no *next
node
Insertion()
1. Create node p and allocate memory
2. Accept no, store in p  no
3. Assign plink=NULL;
4. Check if rear=NULL
True:
a. front=rear=p;
b. return;
5. rear  link=p;
6. rear = p;
10 NULL
(200)
front = rear = NULL
front rear
(220)
20 NULL
10 (220)
(240)
30 NULL
20 (240)
Alg & Explanation for Insertion
no *next
node
Insertion()
1. Create node p and allocate memory
2. Accept no, store in p  no
3. Assign plink=NULL;
4. Check if rear=NULL
True:
a. front=rear=p;
b. return;
5. rear  link=p;
6. rear = p;
10 NULL
(200)
front = rear = NULL
front rear
(220)
20 NULL
10 (220)
(240)
30 NULL
20 (240)
Alg & Explanation for Deletion
no *next
node
Deletion
1. if(front==NULL)
a. Print “Queue Empty”
b. Return
2. ptr = front;
3. front=frontlink;
4. if(front==NULL)
a. rear=NULL;
5. Print ptrno;
6. free(ptr);
10 NULL
(200)
front = (200)
rear = (240)
front rear
(220)
20 NULL
10 (220)
(240)
30 NULL
20 (240)
Alg & Explanation for Deletion
no *next
node
Deletion
1. if(front==NULL)
a. Print “Queue Empty”
b. Return
2. ptr = front;
3. front=frontlink;
4. if(front==NULL)
a. rear=NULL;
5. Print ptrno;
6. free(ptr);
10 NULL
(200)
front = (200)
rear = (240)
ptr = (200)
front rear
(220)
20 NULL
10 (220)
(240)
30 NULL
20 (240)
ptr
Alg & Explanation for Deletion
no *next
node
Deletion
1. if(front==NULL)
a. Print “Queue Empty”
b. Return
2. ptr = front;
3. front=frontlink;
4. if(front==NULL)
a. rear=NULL;
5. Print ptrno;
6. free(ptr);
10 NULL
(200)
front = (220)
rear = (240)
ptr = 200
front rear
(220)
20 NULL
10 (220)
(240)
30 NULL
20 (240)
ptr
Alg & Explanation for Deletion
no *next
node
Deletion
1. if(front==NULL)
a. Print “Queue Empty”
b. Return
2. ptr = front;
3. front=frontlink;
4. if(front==NULL)
a. rear=NULL;
5. Print ptrno;
6. free(ptr);
10 NULL
(200)
front = (220)
rear = (240)
front rear
(220)
20 NULL
10 (220)
(240)
30 NULL
20 (240)
ptr
Alg & Explanation for Deletion
no *next
node
Deletion
1. if(front==NULL)
a. Print “Queue Empty”
b. Return
2. ptr = front;
3. front=frontlink;
4. if(front==NULL)
a. rear=NULL;
5. Print ptrno;
6. free(ptr);
front = (220)
rear = (240)
ptr = (220)
front rear
(220)
20 NULL
(240)
30 NULL
20 (240)
ptr
Alg & Explanation for Deletion
no *next
node
Deletion
1. if(front==NULL)
a. Print “Queue Empty”
b. Return
2. ptr = front;
3. front=frontlink;
4. if(front==NULL)
a. rear=NULL;
5. Print ptrno;
6. free(ptr);
front = (240)
rear = (240)
ptr = (220)
front
rear
(220)
20 NULL
(240)
30 NULL
20 (240)
ptr
Alg & Explanation for Deletion
no *next
node
Deletion
1. if(front==NULL)
a. Print “Queue Empty”
b. Return
2. ptr = front;
3. front=frontlink;
4. if(front==NULL)
a. rear=NULL;
5. Print ptrno;
6. free(ptr);
front = (240)
rear = (240)
ptr = (240)
front
rear
(240)
30 NULL
ptr
Alg & Explanation for Deletion
no *next
node
Deletion
1. if(front==NULL)
a. Print “Queue Empty”
b. Return
2. ptr = front;
3. front=frontlink;
4. if(front==NULL)
a. rear=NULL;
5. Print ptrno;
6. free(ptr);
front = NULL
rear = NULL
ptr = (240)
front
rear
(240)
30 NULL
ptr
Algorithm for Display
if(front == NULL)
{
Print “Queue is empty”;
return;
}
ptr = front;
while(ptr != NULL) { Print ptrno; ptr = ptrlink; }
}
Queue using Linked List: Implementation
 Define node
typedef struct queue
{
int no;
struct queue *link;
}node;
void insertion();
void deletion();
void display();
node *front=NULL,*rear=NULL;
insertion ( )
void insertion()
{
node *p; p=malloc(sizeof(node));
// Accept no and store in pno);
plink=NULL;
if(rear==NULL) { front=rear=p; return; }
rearlink=p;
rear=p;
}
Deletion ( )
void deletion()
{
node *ptr;
if(front == NULL) { printf("nUnderflow"); return; }
ptr = front; front = frontlink;
if(front == NULL) rear = NULL;
printf("nDeleted number is: %d",ptr  no);
free(ptr);
}
Display ( )
void display()
{
node *ptr;
if(front == NULL) { Print “Queue is empty”; return; }
ptr = front;
while(ptr != NULL) { Print ptrno; ptr = ptrlink;
}
}
Main function
void main()
{
int ch;
do
{
printf("n1.Insert 2.Delete 3.Display 4.Exit");
printf("nEnter your choice: "); scanf("%d",&ch);
switch(ch) { case 1:insertion();break; case 2:deletion();break;
case 3:display(); } }
while(ch<4);
}
Unit 5: Non Linear Data Structures
 Tree: Basic terminology, Binary Trees
 Representation of Binary Tree using array and LL
 Binary Search Trees
 Operations on BST: Insertion, Deletion
 Recursive Traversals: PreOrder, InOrder, PostOrder
Representation of binary tree using array
Sequential representation of Binary Tree
 For first case(0 to n-1),
if root is indicated by „p‟;
then left child=(2*p)+1;
and right child=(2*p)+2;
 For second case(1to n),
if root=p;
then left child=(2*p);
and right child=(2*p)+1;
where root, left child and
right child are the values of
indices of the array.
Representation of
binary tree using array
Representation
of
binary tree
using array
Sequential representation
 Advantages:
 best representation for complete and full binary tree
representation
 Disadvantages:
 Height of tree should be known
 Memory may be wasted
 Insertion and deletion of a node is difficult
Binary Tree:
Linked List
Representation
left right
Root
left right
data
left right
data
left right
data
left right
data
left right
data
left right
data
struct node
{
int data;
struct node *left;
struct node *right;
};
/* Initialize nodes */
struct node *root;
struct node *one = NULL;
struct node *two = NULL;
struct node *three = NULL;
Binary Tree: Linked List Representation
Binary Tree: Linked List Representation
/* Allocate memory */
one = malloc(sizeof(struct node));
two = malloc(sizeof(struct node));
three = malloc(sizeof(struct node));
/* Assign data values */
Onedata = 1;
two  data = 2;
three  data = 3;
/* Connect nodes */
oneleft = two; one  right = three;
two  left = NULL;
two  right = NULL;
three  left = NULL;
three  right = NULL;
/* Save address of first node in root */
root = one;
Binary Tree: Linked List Representation
 Advantages:
 Height of tree need not be known
 No memory wastage
 Insertion and deletion of a node is done without affecting other
nodes
 Disadvantages:
 Direct access to node is difficult
 Additional memory required for storing address of left and right
node
Binary Search Tree
 A binary tree T is termed as binary search tree (or
binary sorted tree) if each node N of T satisfies the
following property:
The value at N is a greater than every value in the
left sub-tree of N and is less than every value in the
right sub-tree of N.
Binary Search Trees (BSTs)
 Binary Search Tree Property:
The value stored at
a node is greater than
the value stored at its
left child and less than
the value stored at its
right child
Construct BST: 10, 12, 5, 4, 20, 8, 7, 15, 13
BST Example
 Construct the Binary Search Tree for the given
elements:
 50, 17, 72, 12, 23, 54, 76, 9, 14, 19, 67
Search an element in BST
 Algorithm:
1. If (root == NULL) return NULL;
2. If (num == rootdata) return root  data;
3. If (num < root  data)
return search(root  left)
4. If (num > root  data )
return search(root  right)
struct node
{
int data;
struct node* left;
struct node* right;
};
struct node* insert(struct node* root, int data)
{
if (root == NULL) return createNode(data);
if (data < root  data)
root  left = insert(root  left, data);
else if (data > root  data)
root  right = insert(root  right, data);
return root;
}
struct node* createNode(value) {
struct node* newNode=malloc(sizeof(struct node));
newNodedata = value;
newNode  left = NULL;
newNode  right = NULL;
return newNode; }
int main()
{
struct node *root = NULL;
root = insert(root, 8); insert(root, 3);
insert(root, 1); insert(root, 6);
insert(root, 7); insert(root, 10);
insert(root, 14); insert(root, 4); }
Insert value in Binary Search Tree(BST)
 Algorithm
1. If (node == NULL) return createNode(data)
2. if (data < nodedata)
node  left = insert(node  left, data);
3. else if (data > node  data)
node  right = insert(node  right, data);
return node;
Find the largest element in BST
if ( root == null) { return NULLL; }
struct node *currNode = root;
while(currNoderight != null)
{
currNode = currNoderight;
}
return currNodedata;
Deleting a node in BST
 Three cases in deleting a node:
 Case 1: Deleting a Leaf node (A node with no children)
 Case 2: Deleting a node with one child
 Case 3: Deleting a node with two children
Case 1: Deleting a leaf node
 Step 1 - Find the node to be deleted using search operation
 Step 2 - Delete the node using free function (If it is a leaf) and
assign NULL to the Parent‟s left or right accordingly.
Case 2: Deleting a node with one child
 Step 1 - Find the node to be deleted using search
operation
 Step 2 - If it has only one child then create a link
between its parent node and child node.
 Step 3 - Delete the node using free function and
terminate the function.
Deleting a node with one child
Find the smallest element in BST
if ( root == null ) return NULL;
struct node *currNode = root;
while(currNodeleft != null)
{
currNode = currNodeleft;
}
return currNodedata;
Case 3: Deleting a node with two children
Step1: Find the deletion node p (the node that we want to delete)
Step 2: Find the successor node of p
2.1 Successor node is the node in the right subtree that has the
minimum value (Or)
2.1 Successor node is the node in the left subtree that has the
maximum value
Step 3: Replace the content of node p with the content of the successor
node
Step 4: Delete the successor node
Deleting a node with 2 children
Recursive Tree Traversals
 InOrder
 PreOrder
 PostOrder
209
Preoder, Inorder, Postorder
 In Preorder, the root
is visited before (pre)
the subtrees traversals
 In Inorder, the root is
visited in-between left
and right subtree traversal
 In Postorder, the root
is visited after (post)
Preorder Traversal:
1. Visit the root
2. Traverse left subtree
3. Traverse right subtree
Inorder Traversal:
1. Traverse left subtree
2. Visit the root
3. Traverse right subtree
Postorder Traversal:
1. Traverse left subtree
2. Traverse right subtree
3. Visit the root
InOrder Tree Traversal
void InOrder (node *ptr)
{
if(ptr == NULL) return;
else
{
InOrder(ptrleft);
Print ptr  value
InOrder (ptr  right);
}
}
InOrder: Example 5
Pre Order Traversal
void PreOrder(node *ptr)
{
if(ptr == NULL) return;
else
{
Print ptr  value;
PreOrder (ptr  left);
PreOrder (ptr  right);
}
}
BTech II Sem CST Scheme 2020 AY 2020_21 Data Structures

More Related Content

What's hot (20)

String functions in C
String functions in CString functions in C
String functions in C
 
Input and output in C++
Input and output in C++Input and output in C++
Input and output in C++
 
Sets in python
Sets in pythonSets in python
Sets in python
 
Array Introduction One-dimensional array Multidimensional array
Array Introduction One-dimensional array Multidimensional arrayArray Introduction One-dimensional array Multidimensional array
Array Introduction One-dimensional array Multidimensional array
 
Infix prefix postfix
Infix prefix postfixInfix prefix postfix
Infix prefix postfix
 
Linklist
LinklistLinklist
Linklist
 
Strings
StringsStrings
Strings
 
Strings in C
Strings in CStrings in C
Strings in C
 
Circular queue
Circular queueCircular queue
Circular queue
 
Linked list
Linked listLinked list
Linked list
 
Introduction to data structure ppt
Introduction to data structure pptIntroduction to data structure ppt
Introduction to data structure ppt
 
Linked list
Linked listLinked list
Linked list
 
Data structure
Data structureData structure
Data structure
 
Multidimensional array in C
Multidimensional array in CMultidimensional array in C
Multidimensional array in C
 
Binary Tree Traversal
Binary Tree TraversalBinary Tree Traversal
Binary Tree Traversal
 
Data Structures - Lecture 9 [Stack & Queue using Linked List]
 Data Structures - Lecture 9 [Stack & Queue using Linked List] Data Structures - Lecture 9 [Stack & Queue using Linked List]
Data Structures - Lecture 9 [Stack & Queue using Linked List]
 
Data Structure (Tree)
Data Structure (Tree)Data Structure (Tree)
Data Structure (Tree)
 
Singly link list
Singly link listSingly link list
Singly link list
 
User defined functions in C
User defined functions in CUser defined functions in C
User defined functions in C
 
Unit 1 introduction to data structure
Unit 1   introduction to data structureUnit 1   introduction to data structure
Unit 1 introduction to data structure
 

Similar to BTech II Sem CST Scheme 2020 AY 2020_21 Data Structures

DATA STRUCTURE CLASS 12 COMPUTER SCIENCE
DATA STRUCTURE CLASS 12 COMPUTER SCIENCEDATA STRUCTURE CLASS 12 COMPUTER SCIENCE
DATA STRUCTURE CLASS 12 COMPUTER SCIENCEDev Chauhan
 
Datastructures and algorithms prepared by M.V.Brehmanada Reddy
Datastructures and algorithms prepared by M.V.Brehmanada ReddyDatastructures and algorithms prepared by M.V.Brehmanada Reddy
Datastructures and algorithms prepared by M.V.Brehmanada ReddyMalikireddy Bramhananda Reddy
 
DS Complete notes for Computer science and Engineering
DS Complete notes for Computer science and EngineeringDS Complete notes for Computer science and Engineering
DS Complete notes for Computer science and EngineeringRAJASEKHARV8
 
Basic of array and data structure, data structure basics, array, address calc...
Basic of array and data structure, data structure basics, array, address calc...Basic of array and data structure, data structure basics, array, address calc...
Basic of array and data structure, data structure basics, array, address calc...nsitlokeshjain
 
8074.pdf
8074.pdf8074.pdf
8074.pdfBAna36
 
02 Arrays And Memory Mapping
02 Arrays And Memory Mapping02 Arrays And Memory Mapping
02 Arrays And Memory MappingQundeel
 
data structure unit -1_170434dd7400.pptx
data structure unit -1_170434dd7400.pptxdata structure unit -1_170434dd7400.pptx
data structure unit -1_170434dd7400.pptxcoc7987515756
 
ARRAYS IN C++ CBSE AND STATE +2 COMPUTER SCIENCE
ARRAYS IN C++ CBSE AND STATE +2 COMPUTER SCIENCEARRAYS IN C++ CBSE AND STATE +2 COMPUTER SCIENCE
ARRAYS IN C++ CBSE AND STATE +2 COMPUTER SCIENCEVenugopalavarma Raja
 
2. Linear Data Structure Using Arrays - Data Structures using C++ by Varsha P...
2. Linear Data Structure Using Arrays - Data Structures using C++ by Varsha P...2. Linear Data Structure Using Arrays - Data Structures using C++ by Varsha P...
2. Linear Data Structure Using Arrays - Data Structures using C++ by Varsha P...widespreadpromotion
 
datastructureppt-190327174340 (1).pptx
datastructureppt-190327174340 (1).pptxdatastructureppt-190327174340 (1).pptx
datastructureppt-190327174340 (1).pptxDEEPAK948083
 
DATA STRUCTURE BY SIVASANKARI
DATA STRUCTURE BY SIVASANKARIDATA STRUCTURE BY SIVASANKARI
DATA STRUCTURE BY SIVASANKARISivaSankari36
 
Data structures: linear lists
Data structures: linear listsData structures: linear lists
Data structures: linear listsToniyaP1
 
C++ Data Structure PPT.pptx
C++ Data Structure PPT.pptxC++ Data Structure PPT.pptx
C++ Data Structure PPT.pptxMukesh Thakur
 

Similar to BTech II Sem CST Scheme 2020 AY 2020_21 Data Structures (20)

DATA STRUCTURE CLASS 12 COMPUTER SCIENCE
DATA STRUCTURE CLASS 12 COMPUTER SCIENCEDATA STRUCTURE CLASS 12 COMPUTER SCIENCE
DATA STRUCTURE CLASS 12 COMPUTER SCIENCE
 
Datastructures and algorithms prepared by M.V.Brehmanada Reddy
Datastructures and algorithms prepared by M.V.Brehmanada ReddyDatastructures and algorithms prepared by M.V.Brehmanada Reddy
Datastructures and algorithms prepared by M.V.Brehmanada Reddy
 
1st lecture.ppt
1st lecture.ppt1st lecture.ppt
1st lecture.ppt
 
DS Complete notes for Computer science and Engineering
DS Complete notes for Computer science and EngineeringDS Complete notes for Computer science and Engineering
DS Complete notes for Computer science and Engineering
 
Basic of array and data structure, data structure basics, array, address calc...
Basic of array and data structure, data structure basics, array, address calc...Basic of array and data structure, data structure basics, array, address calc...
Basic of array and data structure, data structure basics, array, address calc...
 
8074.pdf
8074.pdf8074.pdf
8074.pdf
 
02 Arrays And Memory Mapping
02 Arrays And Memory Mapping02 Arrays And Memory Mapping
02 Arrays And Memory Mapping
 
M v bramhananda reddy dsa complete notes
M v bramhananda reddy dsa complete notesM v bramhananda reddy dsa complete notes
M v bramhananda reddy dsa complete notes
 
arrays.pptx
arrays.pptxarrays.pptx
arrays.pptx
 
data structure unit -1_170434dd7400.pptx
data structure unit -1_170434dd7400.pptxdata structure unit -1_170434dd7400.pptx
data structure unit -1_170434dd7400.pptx
 
ARRAYS IN C++ CBSE AND STATE +2 COMPUTER SCIENCE
ARRAYS IN C++ CBSE AND STATE +2 COMPUTER SCIENCEARRAYS IN C++ CBSE AND STATE +2 COMPUTER SCIENCE
ARRAYS IN C++ CBSE AND STATE +2 COMPUTER SCIENCE
 
2. Linear Data Structure Using Arrays - Data Structures using C++ by Varsha P...
2. Linear Data Structure Using Arrays - Data Structures using C++ by Varsha P...2. Linear Data Structure Using Arrays - Data Structures using C++ by Varsha P...
2. Linear Data Structure Using Arrays - Data Structures using C++ by Varsha P...
 
cluod.pdf
cluod.pdfcluod.pdf
cluod.pdf
 
datastructureppt-190327174340 (1).pptx
datastructureppt-190327174340 (1).pptxdatastructureppt-190327174340 (1).pptx
datastructureppt-190327174340 (1).pptx
 
DSA Unit II array.pptx
DSA Unit II array.pptxDSA Unit II array.pptx
DSA Unit II array.pptx
 
03-Lists.ppt
03-Lists.ppt03-Lists.ppt
03-Lists.ppt
 
DATA STRUCTURE BY SIVASANKARI
DATA STRUCTURE BY SIVASANKARIDATA STRUCTURE BY SIVASANKARI
DATA STRUCTURE BY SIVASANKARI
 
Data structures: linear lists
Data structures: linear listsData structures: linear lists
Data structures: linear lists
 
C++ Data Structure PPT.pptx
C++ Data Structure PPT.pptxC++ Data Structure PPT.pptx
C++ Data Structure PPT.pptx
 
Data structure ppt
Data structure pptData structure ppt
Data structure ppt
 

More from Sreedhar Chowdam

Design and Analysis of Algorithms Lecture Notes
Design and Analysis of Algorithms Lecture NotesDesign and Analysis of Algorithms Lecture Notes
Design and Analysis of Algorithms Lecture NotesSreedhar Chowdam
 
Design and Analysis of Algorithms (Knapsack Problem)
Design and Analysis of Algorithms (Knapsack Problem)Design and Analysis of Algorithms (Knapsack Problem)
Design and Analysis of Algorithms (Knapsack Problem)Sreedhar Chowdam
 
DCCN Network Layer congestion control TCP
DCCN Network Layer congestion control TCPDCCN Network Layer congestion control TCP
DCCN Network Layer congestion control TCPSreedhar Chowdam
 
Data Communication and Computer Networks
Data Communication and Computer NetworksData Communication and Computer Networks
Data Communication and Computer NetworksSreedhar Chowdam
 
Data Communication & Computer Networks
Data Communication & Computer NetworksData Communication & Computer Networks
Data Communication & Computer NetworksSreedhar Chowdam
 
PPS Arrays Matrix operations
PPS Arrays Matrix operationsPPS Arrays Matrix operations
PPS Arrays Matrix operationsSreedhar Chowdam
 
Programming for Problem Solving
Programming for Problem SolvingProgramming for Problem Solving
Programming for Problem SolvingSreedhar Chowdam
 
Python Programming: Lists, Modules, Exceptions
Python Programming: Lists, Modules, ExceptionsPython Programming: Lists, Modules, Exceptions
Python Programming: Lists, Modules, ExceptionsSreedhar Chowdam
 
Python Programming by Dr. C. Sreedhar.pdf
Python Programming by Dr. C. Sreedhar.pdfPython Programming by Dr. C. Sreedhar.pdf
Python Programming by Dr. C. Sreedhar.pdfSreedhar Chowdam
 
Python Programming Strings
Python Programming StringsPython Programming Strings
Python Programming StringsSreedhar Chowdam
 
C Recursion, Pointers, Dynamic memory management
C Recursion, Pointers, Dynamic memory managementC Recursion, Pointers, Dynamic memory management
C Recursion, Pointers, Dynamic memory managementSreedhar Chowdam
 
C Programming Storage classes, Recursion
C Programming Storage classes, RecursionC Programming Storage classes, Recursion
C Programming Storage classes, RecursionSreedhar Chowdam
 
Programming For Problem Solving Lecture Notes
Programming For Problem Solving Lecture NotesProgramming For Problem Solving Lecture Notes
Programming For Problem Solving Lecture NotesSreedhar Chowdam
 
Computer Networks Lecture Notes 01
Computer Networks Lecture Notes 01Computer Networks Lecture Notes 01
Computer Networks Lecture Notes 01Sreedhar Chowdam
 

More from Sreedhar Chowdam (20)

Design and Analysis of Algorithms Lecture Notes
Design and Analysis of Algorithms Lecture NotesDesign and Analysis of Algorithms Lecture Notes
Design and Analysis of Algorithms Lecture Notes
 
Design and Analysis of Algorithms (Knapsack Problem)
Design and Analysis of Algorithms (Knapsack Problem)Design and Analysis of Algorithms (Knapsack Problem)
Design and Analysis of Algorithms (Knapsack Problem)
 
DCCN Network Layer congestion control TCP
DCCN Network Layer congestion control TCPDCCN Network Layer congestion control TCP
DCCN Network Layer congestion control TCP
 
Data Communication and Computer Networks
Data Communication and Computer NetworksData Communication and Computer Networks
Data Communication and Computer Networks
 
DCCN Unit 1.pdf
DCCN Unit 1.pdfDCCN Unit 1.pdf
DCCN Unit 1.pdf
 
Data Communication & Computer Networks
Data Communication & Computer NetworksData Communication & Computer Networks
Data Communication & Computer Networks
 
PPS Notes Unit 5.pdf
PPS Notes Unit 5.pdfPPS Notes Unit 5.pdf
PPS Notes Unit 5.pdf
 
PPS Arrays Matrix operations
PPS Arrays Matrix operationsPPS Arrays Matrix operations
PPS Arrays Matrix operations
 
Programming for Problem Solving
Programming for Problem SolvingProgramming for Problem Solving
Programming for Problem Solving
 
Big Data Analytics Part2
Big Data Analytics Part2Big Data Analytics Part2
Big Data Analytics Part2
 
Python Programming: Lists, Modules, Exceptions
Python Programming: Lists, Modules, ExceptionsPython Programming: Lists, Modules, Exceptions
Python Programming: Lists, Modules, Exceptions
 
Python Programming by Dr. C. Sreedhar.pdf
Python Programming by Dr. C. Sreedhar.pdfPython Programming by Dr. C. Sreedhar.pdf
Python Programming by Dr. C. Sreedhar.pdf
 
Python Programming Strings
Python Programming StringsPython Programming Strings
Python Programming Strings
 
Python Programming
Python Programming Python Programming
Python Programming
 
Python Programming
Python ProgrammingPython Programming
Python Programming
 
C Recursion, Pointers, Dynamic memory management
C Recursion, Pointers, Dynamic memory managementC Recursion, Pointers, Dynamic memory management
C Recursion, Pointers, Dynamic memory management
 
C Programming Storage classes, Recursion
C Programming Storage classes, RecursionC Programming Storage classes, Recursion
C Programming Storage classes, Recursion
 
Programming For Problem Solving Lecture Notes
Programming For Problem Solving Lecture NotesProgramming For Problem Solving Lecture Notes
Programming For Problem Solving Lecture Notes
 
Big Data Analytics
Big Data AnalyticsBig Data Analytics
Big Data Analytics
 
Computer Networks Lecture Notes 01
Computer Networks Lecture Notes 01Computer Networks Lecture Notes 01
Computer Networks Lecture Notes 01
 

Recently uploaded

Robotics Group 10 (Control Schemes) cse.pdf
Robotics Group 10  (Control Schemes) cse.pdfRobotics Group 10  (Control Schemes) cse.pdf
Robotics Group 10 (Control Schemes) cse.pdfsahilsajad201
 
Katarzyna Lipka-Sidor - BIM School Course
Katarzyna Lipka-Sidor - BIM School CourseKatarzyna Lipka-Sidor - BIM School Course
Katarzyna Lipka-Sidor - BIM School Coursebim.edu.pl
 
Comprehensive energy systems.pdf Comprehensive energy systems.pdf
Comprehensive energy systems.pdf Comprehensive energy systems.pdfComprehensive energy systems.pdf Comprehensive energy systems.pdf
Comprehensive energy systems.pdf Comprehensive energy systems.pdfalene1
 
Robotics-Asimov's Laws, Mechanical Subsystems, Robot Kinematics, Robot Dynami...
Robotics-Asimov's Laws, Mechanical Subsystems, Robot Kinematics, Robot Dynami...Robotics-Asimov's Laws, Mechanical Subsystems, Robot Kinematics, Robot Dynami...
Robotics-Asimov's Laws, Mechanical Subsystems, Robot Kinematics, Robot Dynami...Sumanth A
 
『澳洲文凭』买麦考瑞大学毕业证书成绩单办理澳洲Macquarie文凭学位证书
『澳洲文凭』买麦考瑞大学毕业证书成绩单办理澳洲Macquarie文凭学位证书『澳洲文凭』买麦考瑞大学毕业证书成绩单办理澳洲Macquarie文凭学位证书
『澳洲文凭』买麦考瑞大学毕业证书成绩单办理澳洲Macquarie文凭学位证书rnrncn29
 
SOFTWARE ESTIMATION COCOMO AND FP CALCULATION
SOFTWARE ESTIMATION COCOMO AND FP CALCULATIONSOFTWARE ESTIMATION COCOMO AND FP CALCULATION
SOFTWARE ESTIMATION COCOMO AND FP CALCULATIONSneha Padhiar
 
multiple access in wireless communication
multiple access in wireless communicationmultiple access in wireless communication
multiple access in wireless communicationpanditadesh123
 
Gravity concentration_MI20612MI_________
Gravity concentration_MI20612MI_________Gravity concentration_MI20612MI_________
Gravity concentration_MI20612MI_________Romil Mishra
 
System Simulation and Modelling with types and Event Scheduling
System Simulation and Modelling with types and Event SchedulingSystem Simulation and Modelling with types and Event Scheduling
System Simulation and Modelling with types and Event SchedulingBootNeck1
 
Computer Graphics Introduction, Open GL, Line and Circle drawing algorithm
Computer Graphics Introduction, Open GL, Line and Circle drawing algorithmComputer Graphics Introduction, Open GL, Line and Circle drawing algorithm
Computer Graphics Introduction, Open GL, Line and Circle drawing algorithmDeepika Walanjkar
 
Cost estimation approach: FP to COCOMO scenario based question
Cost estimation approach: FP to COCOMO scenario based questionCost estimation approach: FP to COCOMO scenario based question
Cost estimation approach: FP to COCOMO scenario based questionSneha Padhiar
 
CME 397 - SURFACE ENGINEERING - UNIT 1 FULL NOTES
CME 397 - SURFACE ENGINEERING - UNIT 1 FULL NOTESCME 397 - SURFACE ENGINEERING - UNIT 1 FULL NOTES
CME 397 - SURFACE ENGINEERING - UNIT 1 FULL NOTESkarthi keyan
 
Engineering Drawing section of solid
Engineering Drawing     section of solidEngineering Drawing     section of solid
Engineering Drawing section of solidnamansinghjarodiya
 
11. Properties of Liquid Fuels in Energy Engineering.pdf
11. Properties of Liquid Fuels in Energy Engineering.pdf11. Properties of Liquid Fuels in Energy Engineering.pdf
11. Properties of Liquid Fuels in Energy Engineering.pdfHafizMudaserAhmad
 
Main Memory Management in Operating System
Main Memory Management in Operating SystemMain Memory Management in Operating System
Main Memory Management in Operating SystemRashmi Bhat
 
Paper Tube : Shigeru Ban projects and Case Study of Cardboard Cathedral .pdf
Paper Tube : Shigeru Ban projects and Case Study of Cardboard Cathedral .pdfPaper Tube : Shigeru Ban projects and Case Study of Cardboard Cathedral .pdf
Paper Tube : Shigeru Ban projects and Case Study of Cardboard Cathedral .pdfNainaShrivastava14
 
signals in triangulation .. ...Surveying
signals in triangulation .. ...Surveyingsignals in triangulation .. ...Surveying
signals in triangulation .. ...Surveyingsapna80328
 
Levelling - Rise and fall - Height of instrument method
Levelling - Rise and fall - Height of instrument methodLevelling - Rise and fall - Height of instrument method
Levelling - Rise and fall - Height of instrument methodManicka Mamallan Andavar
 
Ch10-Global Supply Chain - Cadena de Suministro.pdf
Ch10-Global Supply Chain - Cadena de Suministro.pdfCh10-Global Supply Chain - Cadena de Suministro.pdf
Ch10-Global Supply Chain - Cadena de Suministro.pdfChristianCDAM
 
Artificial Intelligence in Power System overview
Artificial Intelligence in Power System overviewArtificial Intelligence in Power System overview
Artificial Intelligence in Power System overviewsandhya757531
 

Recently uploaded (20)

Robotics Group 10 (Control Schemes) cse.pdf
Robotics Group 10  (Control Schemes) cse.pdfRobotics Group 10  (Control Schemes) cse.pdf
Robotics Group 10 (Control Schemes) cse.pdf
 
Katarzyna Lipka-Sidor - BIM School Course
Katarzyna Lipka-Sidor - BIM School CourseKatarzyna Lipka-Sidor - BIM School Course
Katarzyna Lipka-Sidor - BIM School Course
 
Comprehensive energy systems.pdf Comprehensive energy systems.pdf
Comprehensive energy systems.pdf Comprehensive energy systems.pdfComprehensive energy systems.pdf Comprehensive energy systems.pdf
Comprehensive energy systems.pdf Comprehensive energy systems.pdf
 
Robotics-Asimov's Laws, Mechanical Subsystems, Robot Kinematics, Robot Dynami...
Robotics-Asimov's Laws, Mechanical Subsystems, Robot Kinematics, Robot Dynami...Robotics-Asimov's Laws, Mechanical Subsystems, Robot Kinematics, Robot Dynami...
Robotics-Asimov's Laws, Mechanical Subsystems, Robot Kinematics, Robot Dynami...
 
『澳洲文凭』买麦考瑞大学毕业证书成绩单办理澳洲Macquarie文凭学位证书
『澳洲文凭』买麦考瑞大学毕业证书成绩单办理澳洲Macquarie文凭学位证书『澳洲文凭』买麦考瑞大学毕业证书成绩单办理澳洲Macquarie文凭学位证书
『澳洲文凭』买麦考瑞大学毕业证书成绩单办理澳洲Macquarie文凭学位证书
 
SOFTWARE ESTIMATION COCOMO AND FP CALCULATION
SOFTWARE ESTIMATION COCOMO AND FP CALCULATIONSOFTWARE ESTIMATION COCOMO AND FP CALCULATION
SOFTWARE ESTIMATION COCOMO AND FP CALCULATION
 
multiple access in wireless communication
multiple access in wireless communicationmultiple access in wireless communication
multiple access in wireless communication
 
Gravity concentration_MI20612MI_________
Gravity concentration_MI20612MI_________Gravity concentration_MI20612MI_________
Gravity concentration_MI20612MI_________
 
System Simulation and Modelling with types and Event Scheduling
System Simulation and Modelling with types and Event SchedulingSystem Simulation and Modelling with types and Event Scheduling
System Simulation and Modelling with types and Event Scheduling
 
Computer Graphics Introduction, Open GL, Line and Circle drawing algorithm
Computer Graphics Introduction, Open GL, Line and Circle drawing algorithmComputer Graphics Introduction, Open GL, Line and Circle drawing algorithm
Computer Graphics Introduction, Open GL, Line and Circle drawing algorithm
 
Cost estimation approach: FP to COCOMO scenario based question
Cost estimation approach: FP to COCOMO scenario based questionCost estimation approach: FP to COCOMO scenario based question
Cost estimation approach: FP to COCOMO scenario based question
 
CME 397 - SURFACE ENGINEERING - UNIT 1 FULL NOTES
CME 397 - SURFACE ENGINEERING - UNIT 1 FULL NOTESCME 397 - SURFACE ENGINEERING - UNIT 1 FULL NOTES
CME 397 - SURFACE ENGINEERING - UNIT 1 FULL NOTES
 
Engineering Drawing section of solid
Engineering Drawing     section of solidEngineering Drawing     section of solid
Engineering Drawing section of solid
 
11. Properties of Liquid Fuels in Energy Engineering.pdf
11. Properties of Liquid Fuels in Energy Engineering.pdf11. Properties of Liquid Fuels in Energy Engineering.pdf
11. Properties of Liquid Fuels in Energy Engineering.pdf
 
Main Memory Management in Operating System
Main Memory Management in Operating SystemMain Memory Management in Operating System
Main Memory Management in Operating System
 
Paper Tube : Shigeru Ban projects and Case Study of Cardboard Cathedral .pdf
Paper Tube : Shigeru Ban projects and Case Study of Cardboard Cathedral .pdfPaper Tube : Shigeru Ban projects and Case Study of Cardboard Cathedral .pdf
Paper Tube : Shigeru Ban projects and Case Study of Cardboard Cathedral .pdf
 
signals in triangulation .. ...Surveying
signals in triangulation .. ...Surveyingsignals in triangulation .. ...Surveying
signals in triangulation .. ...Surveying
 
Levelling - Rise and fall - Height of instrument method
Levelling - Rise and fall - Height of instrument methodLevelling - Rise and fall - Height of instrument method
Levelling - Rise and fall - Height of instrument method
 
Ch10-Global Supply Chain - Cadena de Suministro.pdf
Ch10-Global Supply Chain - Cadena de Suministro.pdfCh10-Global Supply Chain - Cadena de Suministro.pdf
Ch10-Global Supply Chain - Cadena de Suministro.pdf
 
Artificial Intelligence in Power System overview
Artificial Intelligence in Power System overviewArtificial Intelligence in Power System overview
Artificial Intelligence in Power System overview
 

BTech II Sem CST Scheme 2020 AY 2020_21 Data Structures

  • 1. B.Tech II Sem „CST‟; Scheme 2020; AY: 2020_21 DATA STRUCTURES Dr. C. Sreedhar
  • 2. Unit 1: Arrays  Introduction to Data Structures, Definition,  Classification of Data Structures, Linear and Non Linear  Sequential Storage Representation: Arrays,  Operations on Arrays: Insertion, Deletion, Traversing;  Applications of arrays: Linear Search, Binary Search, Bubble Sort, Selection Sort, Insertion Sort, Merging of arrays
  • 3. Unit 2: Linked List  Linked Storage Representation: Linked Lists  Linked storage representation using pointers,  Types of Linked Lists: Single linked list  Double linked list  Operations on linked lists: Traversing  Searching, Insertion and Deletion
  • 4. Unit III: Stack  Linear Data Structures: Stacks  Representation of stack using sequential storage and linked allocation methods  Operations on stacks:  Push, Pop and Display
  • 5. Unit IV: Queue  Linear Data Structures: Queues  Representation of Queue using sequential and linked allocation  Operations on Queues: Insertion, Deletion and Traversing  Circular queue
  • 6. Unit V: Non Linear DS  Non Linear Data Structures: Trees  Basic terminology, Binary Trees, Representation of Binary tree in memory using arrays and linked lists.  Binary search trees, operations on binary search trees  Insertion, Deletion  Recursive traversals: Preorder, Inorder and Postorder
  • 7.
  • 8. Definitions  Data: a value or set of values  Entity: is any object in the system that we want to model and store information about  Information: Processed data to gain knowledge  Data type: is a classification of type of data that a variable or object can hold.  Built-in Data type
  • 9.  Abstract Data Types (aka ADTs) are descriptions of how a data type will work without implementation details.  Ex: Stack
  • 10. Data Structure: Definition  Data structure (DS) is representation of the logical relationship existing between individual elements of data.  Data structure is a data organization, management and storage format that enables efficient access and modification.  Data structures provide a means to manage large amounts of data efficiently for uses such as large databases  Program=algorithm + Data Structure
  • 11. DS Linear DS Non-Linear DS Array Linked List Stack Queue Graph Trees DS : Classification
  • 12. Linear Vs. Non-linear Data Structure  The basic difference between linear and non-linear data structure is that in linear data structures, for each element there is a fixed next element but in case of non-linear data structure, each element can have many different next elelemts.
  • 13. Linear DS  Array: collection of finite number of homogeneous data elements  Linked List: data elements are managed by collection of nodes, where each node contains link or pointer which points to next node in the list.  Stacks: linear collection of data elements in which insertion and deletion are restricted at only one end. (LIFO)  Queues: linear collection of data elements in which insertion can take place at one end and deletion can take place at other end. (FIFO)
  • 14. Identify the Data Structure Array Stack Queue
  • 16. Non-Linear Data Structures  Trees: is a non-linear data structure which is used to represent data elements having hierarchical relationship between them  Graphs: is a non-linear data structure which is used to represent data having relationship among its elements which are not necessarily hierarchical in nature.  Set: allows to add data to a container  Table
  • 17. Identify non-linear Data Structure Tree Table Graph Set
  • 18. Graph
  • 19.
  • 20. Applications of DS  Stack: functions and stack, expression evaluation, UNDO/REDO operation in word processors etc.  Queues: Operating systems often maintain a queue of processes that are ready to execute or that are waiting for a particular event to occur.  Graphs - Connections/relations in social networking sites, Routing ,networks of communication, data organization etc.
  • 21. Applications of Data Structures  Dictionary: Arranged and ordered and unordered words  Android Auto : City map, source, destination, shortest path  Student details: Roll no, Name, age, address, marks, ...  Library: Arranging books in certain order  Travelling Salesperson problem  Airport: Flights(Source, destination, connecting), companies...
  • 23. largest element of an array for(i = 1; i < n; i++) { if(arr[0] < arr[i]) arr[0] = arr[i]; } printf("Largest element = %.2f", arr[0]);
  • 24. Solved Example: Accept elements of array and display largest element int i, n; float arr[100]; // Accept the value of n for(i = 0; i < n; ++i) { printf("Enter Number %d: ", i+1); scanf("%f", &arr[i]); } for(i = 1; i < n; ++i) { if(arr[0] < arr[i]) arr[0] = arr[i]; } printf("Largest element = %.2f", arr[0]);
  • 25. Sequential Storage Representation  Arrays:  One dimensional Arrays  Declaration; initialization; passing arguments to a function  Two dimensional Arrays  Declaration; initialization; passing arguments to a function  Arrays Storage representation: address calculation
  • 26. 1 D Array: Finding address  First location of an array is called Base Address
  • 27. 1D Array: Finding address  To find the address of element of an array, say A[i],  Address of A [ i ] = B + W * ( i – LB ); where  B = Base address W = Storage Size of one element stored in array i = Subscript of element whose address is to be found LB = Lower limit or Lower Bound of subscript 
  • 28. Finding address: 1D Array: Example 1  Given Array A[20]; ie., A[0], A[1],......A[19]  Consider B: 2000; W= 4 bytes; i= 12; Find the address of where A[12] is stored?  Address of A [ i ] = B + W * ( i – LB )  A [12] = 2000 + 4 * (12-0) = 2048  Ans: The address of A[12] = 2048
  • 29. Address calculation in 2D Arrays  Given X[2][2] Two types of arrangement  Row major  Column major
  • 30. Row Major System: Address of A [ I ][ J ] = B + W * [ N * ( I – Lr ) + ( J – Lc ) ] Column Major System: Address of A [ I ][ J ] = B + W * [( I – Lr ) + M * ( J – Lc )] Where, B = Base address I = Row subscript of element whose address is to be found J = Column subscript of element whose address is to be found W = Storage Size of one element stored in the array (in byte) Lr = Lower limit of row/start row index of matrix, if not given assume 0 (zero) Lc = Lower limit of column/start column index of matrix, if not given assume 0 (zero) M = Number of row of the given matrix N = Number of column of the given matrix
  • 31. 2D Array Address Calculation(Row Major)  Consider A[3][4]; with base address 2000. Find the address of A[1][2] using row major.  Address of A [ I ][ J ] = B + W * [N*(I – Lr)+(J–Lc) ]  Given:  I = 1; J = 2; W = 4 bytes; B = 2000;  N: Total no. of cols = 4; Lr: 0; Lc: 0  A[1][2]=2000+4*[4*(1-0)+(2-0)] = 2024
  • 32.
  • 33. 2D Array Address Calculation(Col Major)  Consider A[3][4]; with base address 2000. Find the address of A[1][2] using Column major.  Address of A [ I ][ J ] = B+W*[(I – Lr)+M*( J – Lc )]  Given:  I = 1; J = 2; W = 4 bytes; B = 2000;  M: Total no. of rows = 3; Lr: 0; Lc: 0  A[1][2]=2000+4*[(1-0)+3*(2-0)] = 2028
  • 35. 2D Array: Find address(Row Major)  Consider A[10][20]; with base address 501. Find the address of A[8][10] using row major.  Address of A [ I ][ J ] = B + W * [N*(I – Lr)+(J–Lc) ]  Given:  I = 8; J = 10; W = 4 bytes; B = 501;  N: Total no. of cols = 20; Lr: 0; Lc: 0  A[8][10]=501+4*[20*(8-0)+(10-0)] = 1181
  • 36. 2D Array: Find address(Col Major)  Consider A[10][20]; with base address 501. Find the address of A[8][10] using Column major.  Address of A [ I ][ J ] = B+W*[(I – Lr)+M*( J – Lc )]  Given:  I = 8; J = 10; W = 4 bytes; B = 501;  M: Total no. of rows = 10; Lr: 0; Lc: 0  A[8][10]=501+4*[(8-0)+10*(10-0)] = 933
  • 37. largest element of an array for(i = 1; i < n; i++) { if(arr[0] < arr[i]) arr[0] = arr[i]; } printf("Largest element = %.2f", arr[0]);
  • 38. Delete element in an Array main() { .... AcceptArray(n,a); DisplayArray(n,a); Insert(n,a); DisplayArray(n,a); Delete(n,a); DisplayArray(n,a); } 1. Accept the position 2. Check whether position > = n+1; True: Deletion not possible False: a) for(i=pos-1;i<n;i++) a[i]=a[i+1] b) n - - c) print the elements of an array 3. Stop
  • 39. Linear Search (Single Occurrence) SEARCH (A [ ], n, s) 1. for(i=0; i<n; i++) 1a. if (s=A[i]) break; 2. if (i<n) 2a. Print "Element found at index, i" 3. else Print "Element not found " 4. STOP
  • 40. Linear Search (Multiple occurrences) SEARCH (A [ ], n, s) 1. Initialize count = 0 1. for(i=0; i<n; i++) 1a. if (A[i]=s) 1a.i. Print "element is found at location (i+1)" 1a.ii. count++ 2. if (count=0) 2a. Print "Element is not found " 3. else Print "Element is found at count times in array " 4. STOP
  • 41.  void read(int [ ],int);  void display(int [ ],int);  void search(int [ ],int,int); main( ) { //Accept n read(a,n); display(a,n); do { printf("Enter searching element:"); // Accept and store in „se‟ var search(a,n,se); printf("search another element?y/n: "); scanf(" %c",&ch); } while(ch=='y'); void read(int a[ ],int n) { int i; for(i=0;i<n;i++) scanf("%d",&a[i]); }
  • 42. void read(int a[ ],int n) { int i; for(i=0;i<n;i++) scanf("%d",&a[i]); } void display(int a[ ],int n) { int i; for(i=0;i<n;i++) printf("%d ",a[i]);} // Search for multiple occurrences void search(int a[ ], int n, int se) { int i,count=0; for(i=0;i<n;i++) { if(a[i]==se) { printf("%d is found at %d",se,i+1); count++; } } if(count==0) printf("n%d is not found",se); else printf("n%d is present %d times in array",se,count); }
  • 43. Binary Search: Algorithm 1. Initialize lb=0, ub=n-1, count = 0 2. while (lb < = ub) 2a. mid=(lb+ub)/2; 2b. if(se==a[mid]) 2b.i. Print "element is found at position,se,mid+1 2b.ii. count++; 2b.iii. break; 2c. else if(se<a[mid]) 2c.i. ub=mid-1; 2d. else 2d.i lb=mid+1; 3. End while 4. if(count==0) 4a. print "Element not found" 5. STOP
  • 44. Merging two arrays void read(int [ ],int); void display(int [ ],int); void merge(int [ ],int [ ],int [ ],int,int); main() //Accept n Read(a,n) read(b,n); display(a,m); display(b,n); merge(a,b,c,m,n); display(c,m+n);
  • 45. void read(int a[ ],int m) { int i; for(i=0;i<m;i++) scanf("%d",&a[i]); } void display(int a[ ],int m) { int i; for(i=0;i<m;i++) printf("%d ",a[i]); } void merge(int a[ ],int b[ ],int c[ ],int m,int n) { int i,j,k; i=j=k=0; while(i<m&&j<n) { if(a[i]<b[j]) c[k++]=a[i++]; else c[k++]=b[j++]; } while(i<m) c[k++]=a[i++]; while(j<n) c[k++]=b[j++]; }
  • 46. Finding Largest no. in array using fn‟s  void CreateArray(int n,int a[ ]);  void DisplayArray(int n,int a[ ]);  void Largest(int n,int a[ ]); void CreateArray(int n,int a[ ]) { int i; for(i=0;i<n;i++) { printf("Enter a[%d]:",i); scanf("%d",&a[i]); } } int main() { ......... CreateArray(n,a); DisplayArray(n,a); Largest(n,a); ..... } void DisplayArray(int n,int a [ ]) { int i; for(i=0;i<n;i++) { printf("%dt",a[i]); } printf("n"); } void Largest(int n,int a[ ]) { int i; for(i=1;i<n;i++) { if(a[0]<a[i]) a[0]=a[i]; } printf("Largest element = %d",a[0]); }
  • 47. Lab1a) Array op‟s: insert,delete,traverse void create(); void display(); void insert(); void del(); void create() { int i; for(i=0;i<n;i++) { printf("Enter a[%d]:",i); scanf("%d",&a[i]); } } int main() { ......... do { create(); display() insert(); delete(); exit(); }while(..) ..... } void display() { int i; for(i=0;i<n;i++) { printf("%dt",a[i]); } } void insert( ) { // Accept the position to insert and store in „pos‟ variable // Accept the value to insert and store in „val‟ variable for(i=n-1;i>=pos-1;i--) a[i+1]=a[i]; a[pos-1]=val; n=n+1; } void del() { // Accept the „pos‟; val=a[pos-1]; for(i=pos-1;i<n;i++) a[i]=a[i+1]; n=n-1; printf("nThe deleted element is =%d",val); }
  • 48. Lab 2a) Linear Search  void read(int [ ],int);  void display(int [ ],int);  void search(int [ ],int,int); void search(int a[ ], int n, int s) { // Single Occurance ... for(i=0; i<n; i++) if (s=A[i]) break; if (i<n) Print "Element found at index, i“ else Print "Element not found “ } main() { //Accept n read(a,n); display(a,n); do { // Accept „se‟ search(a,n,se); }while(..); } void search (int a [ ], int n, int s){ // Multiple Occurances ... Initialize count = 0 for(i=0; i<n; i++) if (A[i]=s) { Print "element is found at location (i+1)“ count++ } if (count=0) Print "Element is not found “ else Print "Element is found at count times in array “ }
  • 49. Lab 2b) Binary Search  void read(int [ ],int);  void display(int [ ],int);  void search(int [ ],int,int); main() { //Accept n read(a,n); display(a,n); do { // Accept „se‟ search(a,n,se); }while(..); } void search(int a[ ],int n,int se) { int lb,ub,mid,count=0; lb=0; ub=n-1; while(lb<=ub) { mid=(lb+ub)/2; if(se==a[mid]) { printf("nThe element %d is found at position %dn",se,mid+1); count++; break; } else if(se<a[mid]) ub=mid-1; else lb=mid+1; } if(count==0) printf("nElement not found"); }
  • 50. Binary Search: Algorithm 1. Initialize lb=0, ub=n-1, count = 0 2. while (lb < = ub) 2a. mid=(lb+ub)/2; 2b. if(se==a[mid]) 2b.i. Print "element is found at position,se,mid+1 2b.ii. count++; 2b.iii. break; 2c. else if(se<a[mid]) 2c.i. ub=mid-1; 2d. else 2d.i lb=mid+1; 3. End while 4. if(count==0) 4a. print "Element not found" 5. STOP
  • 51. Merging of two sorted arrays  Enter size of first array: 4  Enter elements of first array: 1 3 5 7  Enter size of Second array: 4  Enter elements of Second array: 2 4 6 8  Merged Final Sorted array elements are: 1 2 3 4 5 6 7 8
  • 52. Merging of two sorted arrays 1 3 5 7 2 4 6 8 A B C
  • 53. Merging of two sorted arrays 1 3 5 7 2 4 6 8 A B C i j 1 2 < 1
  • 54. Merging of two sorted arrays 1 3 5 7 2 4 6 8 A B C j 1 2 < 1 i 3 2
  • 55. Merging of two sorted arrays 1 3 5 7 2 4 6 8 A B C 1 2 < 1 i 3 2 j 4 3
  • 56. Merging of two sorted arrays 1 3 5 7 2 4 6 8 A B C 1 2 < 1 i 3 2 j 4 3 5 4
  • 57. Merging of two sorted arrays 1 3 5 7 2 4 6 8 A B C 1 2 < 1 i 3 2 j 4 3 5 4 6 5
  • 58. Merging of two sorted arrays 1 3 5 7 2 4 6 8 A B C 1 2 < 1 i 3 2 j 4 3 5 4 6 5 7 6
  • 59. Merging of two sorted arrays 1 3 5 7 2 4 6 8 A B C 1 2 < 1 i 3 2 j 4 3 5 4 6 5 7 6 8 7 8
  • 60. How to code? if ( a [ i ] < b [ j ] ) c[ k++ ] = a[ i++ ]; else c[ k++ ] = b[ j++ ]; while( i<m && j<n ) { } while( i < m ) c[ k++ ] = a[ i++ ]; while( j < n ) c[ k++ ] = b[ j++ ];
  • 61. Merging function definition void merge( ..........) { int i,j,k; i=j=k=0; while( i<m && j<n ) { if ( a [ i ] < b [ j ] ) c[ k++ ] = a[ i++ ]; else c[ k++ ] = b[ j++ ]; } while( i < m ) c[ k++ ] = a[ i++ ]; while( j < n ) c[ k++ ] = b[ j++ ];
  • 62. Merging two arrays: Complete Program void read(int [ ],int); void display(int [ ],int); void merge(int [ ],int [ ],int [ ],int,int); main() { //Accept n read(a,n) read(b,n); display(a,m); display(b,n); merge(a,b,c,m,n); display(c,m+n); ..}
  • 63. void read(int a[ ],int m) { int i; for(i=0;i<m;i++) scanf("%d",&a[i]); } void display(int a[ ],int m) { int i; for(i=0;i<m;i++) printf("%d ",a[i]); } void merge(int a[ ],int b[ ],int c[ ],int m,int n) { int i,j,k; i=j=k=0; while(i<m&&j<n) { if(a[i]<b[j]) c[k++]=a[i++]; else c[k++]=b[j++]; } while(i<m) c[k++]=a[i++]; while(j<n) c[k++]=b[j++]; }
  • 64. Sorting  Sorting is the process of arranging unordered elements into ordered (Ascending or descending order) elements.  Sorting algorithms:  Bubble Sort; Selection Sort; Recursive Bubble Sort;  Insertion Sort; Merge Sort; Quick Sort; Heap Sort  Radix sort; Bucket Sort; Shell Sort; Pigeonhole Sort;  Pancake Sort; Gnome Sort; Stooge Sort; Tag Sort; Tree Sort
  • 65. Bubble Sort: Input and Output  Enter the size of the array : 6  Enter the elements of the array : 4 3 6 1 5 2  After sorting, elements of the array are: 1 2 3 4 5 6
  • 66. Bubble Sort: Logic 6, 2, 9, 11, 9, 3, 7, 12 i j a[ j ] a[ j+1 ] > then swap < then increment j Swap temp = a[ j ] a[ j ] = a[ j+1 ] a[ j+1 ] = temp Iterate range of j: 0 to j < n-1-i Iterate range of i: 0 to i < n-1
  • 67. Bubble Sort: How to Code? if(a[ j ] > a[ j+1 ]) { temp = a[ j ]; a[ j ] = a[ j+1 ]; a[ j+1 ] = temp; } for(i=0;i < n-1;i++) { for(j=0;j < n-1-i;j++) { } }
  • 68. Defining Bubble Sort function void sort(int a[ ],int n) { int i,j,temp; for(i=0;i<n-1;i++) { for(j=0;j<n-1-i;j++) { if(a[ j ]>a[ j+1 ]) {temp=a[j]; a[j]=a[j+1]; a[j+1]=temp;} } } }
  • 69. Bubble Sort: Program void read(int [ ],int); void display(int [ ],int); void bsort(int [ ],int); int main() { // Declare necessary variables // Accept size of the array and store in „n‟ variable do { read(a,n); display(a,n); bsort(a,n); printf(“Array after sorting are:"); display(a,n); // Accept ch and decide to repeat or exit } while(ch=='y'); return 0; } // Define read(int [ ],int) // Define display(int [ ],int) // Define bsort(int [ ],int)
  • 70. Selection Sort void ssort ( ) { int i, j, min, temp; for (i=0; i<n; i++) { min = i; for ( j=i+1; j<n; j++) { if (a[ j ] < a[min]) min = j; } temp = a[i]; a[i] = a[min]; a[min] = temp; } }
  • 71. Selection Sort: Complete Program void ssort ( ); int a[30], n; int main() { // Declare variables // Accept the size of array, store in „n‟ // Accept the elements of array, store in a[i] ssort(); printf("nnAfter sorting:n"); // Display elements of array } void ssort ( ) { int i, j, min, temp; for (i=0; i<n; i++) { min = i; for ( j=i+1; j<n; j++) { if (a[ j ] < a[min]) min = j; } temp = a[i]; a[i] = a[min]; a[min] = temp; } }
  • 73. 5 4 3 2 6 1 5 4 3 2 6 1 2 5 4 5 j=0 6 1 1 5 4 1 2 1 3 6 3 5 3 4 j=1 j=2 j=3 j=4 j=5
  • 74. Insertion Sort void isort(int a[ ],int n) { int i,j,key; for(i=1;i<n;i++) { key=a[i]; for( j = i-1; j >= 0 && a[ j ] > key; j--) { a[ j+1]=a[ j ]; } a[j+1]=key; } }
  • 75. Insertion Sort: Complete program void read(int [ ],int); void display(int [ ],int); void isort(int [ ],int); int main() { // Declare necessary variables // Accept size and store it in „n‟ variable read(a,n); display(a,n); // Before sorting isort(a,n); display(a,n); // After sorting return 0; } // Define read(int [ ],int); // Define display(int [ ],int); // Define isort(int [ ],int);
  • 76. Merge sort example index 0 1 2 3 4 5 6 7 value 22 18 12 -4 58 7 31 42 22 18 12 -4 22 18 22 18 18 22 merge split 12 -4 12 -4 -4 12 merge split split -4 12 18 22 58 7 31 42 58 7 58 7 7 58 merge split 31 42 31 42 31 42 merge split split 7 31 42 58 -4 7 12 18 22 31 42 58 split merge merge merge
  • 77. Merge Sort: Function void sort(int a[ ],int lb,int ub) { int mid; if(lb<ub) { mid=(lb+ub)/2; sort(a,lb,mid); sort(a,mid+1,ub); merge(a,lb,mid,ub); } } void merge(int a[ ],int lb,int mid,int ub) { int b[50],i,j,k; i=lb,j=mid+1,k=lb; while(i<=mid&&j<=ub) { if(a[i]<a[j]) b[k++]=a[i++]; else b[k++]=a[j++]; } while(i<=mid) b[k++]=a[i++]; while(j<=ub) b[k++]=a[j++]; for(i=lb;i<=ub;i++) a[i]=b[i]; }
  • 78. Merge Sort: Complete Program void read(int [ ],int); void display(int [ ],int); void sort(int [ ],int,int); void merge(int [ ],int,int,int); int main() { // Declare necessary variables // Accept size of array and store it in „n‟ read(a,n); display(a,n); // Before sorting sort(a,0,n-1); display(a,n); // After Sorting return 0; } // Define read(int [ ],int) // Define display(int [ ],int) // Define sort(int [ ],int,int) //Define merge(int [ ],int,int,int)
  • 79. Unit 2: Linked Lists  Linked Storage representation using pointers  Types of Linked List:  Single Linked List  Double Linked List  Operations on Linked Lists:  Traversing  Searching  Insertion and Deletion
  • 80. Linked List  A Linked list is an ordered collection of finite, homogeneous data elements called nodes, where the linear order is maintained by means of links or pointers.  Each node is composed of data and a reference to the next node in the sequence. This structure allows for efficient insertion or removal of elements from any position in the sequence during iteration.
  • 81. Advantages of Linked Lists  Linked lists are a dynamic data structure, which can grow and shrink during the execution of the program.  Insertion and deletion node operations are easily implemented in a linked list.  Dynamic data structures such as stacks, queues can be implemented using linked list.  There is no need to define an initial size for a linked list.  Items can be added or removed from the middle of list.  Linked lists have efficient memory utilization. Memory is not pre-allocated in linked list. Memory is allocated whenever it is required and is de-allocated when it is no longer needed.
  • 82. Disadvantages of Linked Lists  They use more memory than arrays because of the storage used by their pointers.  Nodes in a linked list must be read in order from the beginning as linked lists are inherently sequential access.  Difficulties arise in linked lists when it comes to reverse traversing. For instance, singly linked lists are cumbersome to navigate backwards and while doubly linked lists are somewhat easier to read, memory is consumed in allocating space for a back-pointer.
  • 83. Types of LL  Single Linked List  Double Linked List  Circular Linked List
  • 84. Create SLL head Data *link one Create a node One, which contains data and a link. Assign initial value of data to 10 and link to NULL. Traverse the single linked list
  • 85. SLL typedef struct sll { int data; struct sll *next; }node; node *head=NULL; void display( ); void main() { int n; node *one; one=NULL; one=(node *) malloc (sizeof (node) ); onedata=10; one  next=NULL; head=one; display( ); }
  • 86. Traversing SLL void display() { node *temp; if(head==NULL) printf("List is empty"); else { temp=head; while(temp!=NULL) { printf(“n%d",temp->data); temp=temp->next; } } }
  • 87. Create SLL with the following head Data(10) *next one two Data(20) *next Data(30) NULL three
  • 88. Coding SLL typedef struct sll { int data; struct sll *next; }node; node *head=NULL; void main() { int n; node *one,*two,*three; one=NULL; two=NULL; three=NULL; one=(node *)malloc(sizeof(node)); two=(node *)malloc(sizeof(node)); three=(node *)malloc(sizeof(node)); onedata=10; two  data=20; three  data=30; one->next=two; two->next=three; three->next=NULL; head=one; display(); getch(); }
  • 89. Create n nodes in SLL typedef struct sll { int data; struct sll *next; }node; node *head=NULL; void createList(int n); void traverseList(); int main() { int n; printf("Enter n: "); scanf("%d", &n); createList(n); traverseList(); return 0; } void createList(int n) { node *newNode,*temp; int data, i; head = (node *)malloc(sizeof(node)); if(head == NULL) printf("Unable to allocate memory."); else { printf("Enter the data of node 1: "); scanf("%d", &data); head->data = data; head->next = NULL; temp = head; for(i=2; i<=n; i++) { newNode = (node *)malloc(sizeof(node)); if(newNode == NULL) { printf("Unable to allocate memory."); break; } else { printf("nEnter data of node %d: ", i); scanf("%d", &data); newNode->data = data; newNode->next = NULL; temp->next = newNode; temp = temp->next; } } } }
  • 90. Single Linked List Creating node typedef struct slist { int no; char name[50]; struct slist *link; } node; node *first=NULL; no name *link first node NULL
  • 91. Linked Lists  A linked list is a series of connected nodes  Each node contains at least  A piece of data (any type)  Pointer to the next node in the list  Head: pointer to the first node  The last node points to NULL A  Head B C A data pointer node
  • 92. Create SLL with the following head Data(10) *next one two Data(20) *next Data(30) NULL three
  • 93. SLL: Create three nodes and traverse typedef struct sll { int data; struct sll *next; }node; node *head=NULL; void main() { int n; node *one,*two,*three; one=NULL; two=NULL; three=NULL; one=(node *)malloc(sizeof(node)); two=(node *)malloc(sizeof(node)); three=(node *)malloc(sizeof(node)); onedata=10; two  data=20; three  data=30; one->next=two; two->next=three; three->next=NULL; head=one; display(); }
  • 94. Create n nodes in SLL typedef struct sll { int data; struct sll *next; }node; node *head=NULL; void createList(int n); void traverseList(); int main() { int n; printf("Enter n: "); scanf("%d", &n); createList(n); traverseList(); return 0; } void createList(int n) { node *newNode,*temp; int data, i; head = (node *)malloc(sizeof(node)); if(head == NULL) printf("Unable to allocate memory."); else { printf("Enter the data of node 1: "); scanf("%d", &data); head->data = data; head->next = NULL; temp = head; for(i=2; i<=n; i++) { newNode = (node *)malloc(sizeof(node)); if(newNode == NULL) { printf("Unable to allocate memory."); break; } else { printf("nEnter data of node %d: ", i); scanf("%d", &data); newNode->data = data; newNode->next = NULL; temp->next = newNode; temp = temp->next; } } } }
  • 95. Insert node at the beginning 48 17 142 head // head 93 Step 1 Step 2 Step 3
  • 96. Insert node at the end of the list 48 17 142 head // Step 1 Step 2 Step 3
  • 97. Insert node at specified position Step 1 Step 2 Step 3 Step 4
  • 98. SLL: Inserting a node void insertion( ) { node *p,*save,*ptr; p=(node *) malloc(sizeof(node)); printf("nEnter rollno and name:"); scanf("%d %s",&pno,pname); if(first==NULL) { plink=NULL; first=p; return; } save ptr 1001 sree *link first NULL p p 1001 sree NULL
  • 99. SLL: Insertion if(p->no <= first->no) { p->link = first; first = p; return; } save = first; ptr = firstlink; while(ptr !=NULL && ptrno < pno) { save = ptr; ptr = ptr->link; } savelink = p; plink = ptr; } 1002 sri *link p 1002 < = 1001 False first save ptr 1001 sree NULL
  • 100. SLL: Insertion if(p->no <= first->no) { p->link = first; first = p; return; } save = first; ptr = firstlink; while(ptr !=NULL && ptrno < pno) { save = ptr; ptr = ptr->link; } savelink = p; plink = ptr; } 1004 dennis *link p 1004 < = 1001 False first save ptr 1001 sree NULL
  • 101. void createList(int n); void insertB(int data); void insertE(int data); void insertM(int data, int position); void deleteF(); void displayList(); printf("nEnter data to insert at beginning of the list: "); scanf("%d", &data); insertB(data); displayList(); printf("nEnter data to insert at middle of the list: "); scanf("%d", &data); printf("Enter the position to insert new node: " ); scanf("%d", &position); insertM(data, position); displayList(); printf("nEnter data to insert at end of the list: "); scanf("%d", &data); insertE(data); printf("nPress 1 to delete first node: "); scanf("%d", &choice); if(choice == 1) deleteF(); displayList();
  • 102. void insertB(int data) { struct node *newNode; newNode = (struct node*)malloc(sizeof(struct node)); if(newNode == NULL) { printf("Unable to allocate memory."); } else { newNode->data = data; // Link data part newNode->next = head; // Link address part head = newNode; // Make newNode as first node printf("DATA INSERTED SUCCESSFULLYn"); } }
  • 103. void insertM(int data, int position) { int i; struct node *newNode, *temp; newNode = (struct node*)malloc(sizeof(struct node)); if(newNode == NULL) { printf("Unable to allocate memory."); } else { newNode->data = data; // Link data part newNode->next = NULL; temp = head; for(i=2; i<=position-1; i++) { temp = temp->next; if(temp == NULL) break;} if(temp != NULL) { newNode->next = temp->next; temp->next = newNode; printf("DATA INSERTED SUCCESSFULLYn"); } else printf("UNABLE TO INSERT DATA AT THE GIVEN POSITIONn"); } }
  • 104. void insertB(int data) { struct node *newNode; newNode = (struct node*)malloc(sizeof(struct node)); if(newNode == NULL) printf("Unable to allocate memory."); else { newNode->data = data; newNode->next = head; head = newNode; printf("DATA INSERTED SUCCESSFULLYn"); } }
  • 105. void insertM(int data, int position) { int i; struct node *newNode, *temp; newNode = (struct node*)malloc(sizeof(struct node)); if(newNode == NULL) printf("Unable to allocate memory."); else { newNode->data = data; // Link data part newNode->next = NULL; temp = head;
  • 106. for(i=2; i<=position-1; i++) { temp = temp->next; if(temp == NULL) break; } if(temp != NULL) { /* Link address part of new node */ newNode->next = temp->next; /* Link address part of n-1 node */ temp->next = newNode; printf("DATA INSERTED SUCCESSFULLYn"); } else { printf("UNABLE TO INSERT DATA AT THE GIVEN POSITIONn"); } } }
  • 107. void insertE(int data) { struct node *newNode, *temp; newNode = (struct node*)malloc(sizeof(struct node)); if(newNode == NULL) { printf("Unable to allocate memory."); } else { newNode->data = data; newNode->next = NULL; temp = head; while(temp->next != NULL) temp = temp->next; temp->next = newNode; // Link address part printf("DATA INSERTED SUCCESSFULLYn"); } }
  • 108. void deleteF() { struct node *toDelete; if(head == NULL) printf("List is already empty."); else { toDelete = head; head = head->next; printf("nData deleted = %dn", toDelete->data); /* Clears the memory occupied by first node*/ free(toDelete); printf("SUCCESSFULLY DELETED FIRST NODE FROM LISTn"); } }
  • 109. Double Linked List struct node { int data; struct node *prev, *next; }; struct node *head = NULL; static int node_count = 0; struct node *createNode(int); void insertNode(int); void deleteNode(int); void display();
  • 110. /* creating a new node */ struct node* createNode(int data) { struct node *ptr = (struct node *)malloc(sizeof (struct node)); ptr->data = data; ptr->prev = NULL; ptr->next = NULL; return (ptr); } void display() { struct node *ptr = head; int i = 0; while (ptr) { printf("data in node%d:%dn", i, ptr->data); ptr = ptr->next; i++; } }
  • 111. /* Insert a new node at the end of the list */ void insertNode(int data) { struct node *temp, *ptr = createNode(data); if (!head) { head = ptr; node_count++; return; } else { temp = head; while (temp) { if (temp->next == NULL) { temp->next = ptr; ptr->prev = temp; node_count++; return; } temp=temp->next; } } }
  • 112. /* Insert a new node at the end of the list */ void insertNode(int data) { struct node *temp, *ptr = createNode(data); if (!head) { head = ptr; node_count++; return; } else { temp = head; while (temp) { if (temp->next == NULL) { temp->next = ptr; ptr->prev = temp; node_count++; return; } temp=temp->next; } } }
  • 113. /* Insert a new node at the end of the list */ void insertNode(int data) { struct node *temp, *ptr = createNode(data); if (!head) { head = ptr; node_count++; return; } else { temp = head; while (temp) { if (temp->next == NULL) { temp->next = ptr; ptr->prev = temp; node_count++; return; } temp=temp->next; } } }
  • 114. Double Linked List: Deletion head(200) (400) NULL 10 (400) (200) 20 (600) (600) (400) 30 (800) (800) (600) 40 NULL delete(10) head(400) NULL 20 (600) (600) (400) 30 (800) (800) (600) 40 NULL
  • 115. Double Linked List: Deletion head(200) (400) NULL 10 (400) (200) 20 (600) (600) (400) 30 (800) (800) (600) 40 NULL delete(20) head(200) NULL 10 (600) (600) (200) 30 (800) (800) (600) 40 NULL
  • 116. Double Linked List: Deletion head(200) (400) NULL 10 (400) (200) 20 (600) (600) (400) 30 (800) (800) (600) 40 NULL delete(30) head(200) NULL 10 (400) (400) (200) 20 (800) (800) (400) 40 NULL
  • 117. Double Linked List: Deletion head(200) (400) NULL 10 (400) (200) 20 (600) (600) (400) 30 (800) (800) (600) 40 NULL delete(40) head(200) NULL 10 (400) (400) (200) 20 (800) (600) (400) 30 NULL
  • 118. /* delete the node with given data */ void deleteNode(int data) { struct node *ptr, *temp = head; if (head == NULL) { printf("Data unavailablen"); return; } else if (temp->data == data) { ptr = temp->next; temp->next = NULL; free(temp); head = ptr; node_count--; } else { while (temp->next != NULL && temp->data != data) { ptr = temp; temp = temp->next; } if (temp->next == NULL && temp->data != data) { printf("Given data unvavailable in listn"); return; }
  • 119. /* delete the node with given data */ void deleteNode(int data) { struct node *ptr, *temp = head; if (head == NULL) { printf("Data unavailablen"); return; } else if (temp->data == data) { ptr = temp->next; temp->next = NULL; free(temp); head = ptr; node_count--; } else { while (temp->next != NULL && temp->data != data) { ptr = temp; temp = temp->next; } if (temp->next == NULL && temp->data != data) { printf("Given data unvavailable in listn"); return; }
  • 120. else if (temp->next != NULL && temp->data == data) { ptr->next = temp->next; temp->next->prev = temp->prev; temp->next = NULL; temp->prev = NULL; free(temp); printf("Data deleted successfullyn"); node_count--; } else if (temp->next == NULL && temp->data == data) { ptr->next = NULL; temp->next = temp->prev = NULL; free(temp); printf("Data deleted successfullyn"); node_count--; } } }
  • 121. int main() { int ch, data; while (1) { printf("1.Insertionn2.Deletion 3. Display 4.Exitn Enter your choice n"); scanf("%d", &ch); switch (ch) { case 1: printf("Enter data to insert:"); scanf("%d", &data); insertNode(data); break; case 2: printf("Enter data to delete:"); scanf("%d", &data); deleteNode(data); break; case 3: display(); break; case 4: exit(0); default: printf("please enter right optionn"); break; } } }
  • 122. Stack Stack is an ordered list of similar data type. Stack is a linear data structure in which the insertion and deletion operations are performed at only one end. Stacks can be implemented using either array or LL. Stack follows LIFO (Last In First Out) principle. push() function is used to insert new elements into Stack and pop() function is used to remove an element from stack. Both insertion and removal are allowed at only one end of Stack called Top. Stack is said to be in Overflow state when it is completely full and is said to be in Underflow state if it is completely empty.
  • 123. Applications of Stacks  Many compilers use a stack for parsing the syntax of expressions, program blocks etc. before translating into low level code.  Stack is used to evaluate prefix, postfix and infix expressions.  Reverse a string  Processing function calls and return addresses
  • 124. Stack Operations  Push an element into stack  Pop an element from stack  Display the elements of stack  Count the number of elements in the stack
  • 125. #define MAX 6 int top=-1,stack[MAX]; void push(); void pop(); void display(); int main() { int ch; while(1) { printf("n1.Pushn 2.Popn 3.Displayn 4.Exit"); printf("nEnter your choice(1-4):"); scanf("%d",&ch); switch(ch) { case 1: push(); break; case 2: pop(); break; case 3: display(); break; case 4: exit(0); default: printf("nWrong Choice!!"); return 0; } } }
  • 126. void push() { int val; if(top==MAX-1) printf("nStack is full!!"); else { printf("nEnter element to push:"); scanf("%d",&val); top=top+1; stack[top]=val; } }
  • 127. Push operation in stack (Array) n = 6 top = -1 stack[0] stack stack[1] stack[2] stack[3] stack[4] stack[5] Push ( ) Accept element 10 Increment top top = -1+1 = 0 top =0 Insert element in stack[top] 10
  • 128. Push operation in stack (Array) n = 6 top = 0 stack[0] stack stack[1] stack[2] stack[3] stack[4] stack[5] Push ( ) Accept element 20 Increment top top = 0+1 = 1 top =1 Insert element in stack[top] 10 20
  • 129. Push operation in stack (Array) n = 6 top = 1 stack[0] stack stack[1] stack[2] stack[3] stack[4] stack[5] Push ( ) top =2 10 20 30
  • 130. Push operation in stack (Array) n = 6 top = 2 stack[0] stack stack[1] stack[2] stack[3] stack[4] stack[5] Push ( ) top =3 10 20 30 40
  • 131. Push operation in stack (Array) n = 6 top = 3 stack[0] stack stack[1] stack[2] stack[3] stack[4] stack[5] Push ( ) top =4 10 20 30 40 50
  • 132. Push operation in stack (Array) n = 6 top = 4 stack[0] stack stack[1] stack[2] stack[3] stack[4] stack[5] Push ( ) top =5 10 20 30 40 50 60
  • 133. Push operation in stack (Array) n = 6 top = 5 stack[0] Stack is Full stack[1] stack[2] stack[3] stack[4] stack[5] Push ( ) top =5 10 20 30 40 50 60 if(top == n-1) Print "Stack is Full"
  • 134. void pop() { if(top==-1) printf("nStack is empty!!"); else { printf("nDeleted element is %d",stack[top]); top=top-1; } }
  • 135. void display() { int i; if(top==-1) printf("nStack is empty!!"); else { printf("nStack is...n"); for(i=top; i >= 0 ;--i) printf("%dn",stack[i]); } }
  • 136. Display number of elements in stack  static int count=0;  Push function:  After inserting an element, increment count  Pop function  After deleting an element, decrement count  Display function  Print “Count”
  • 137. Stacks  Demonstration of Stack using array
  • 138. Stack using Linked List: Push Operation no *next node Push ( ) 10 NULL (200) (220) 20 (200) (240) 30 (220) (260) 30 (240) top
  • 139. Stack using Linked List: Pop Operation 10 NULL (200) (220) 20 (200) (240) 30 (220) (260) 30 (240) top ptr
  • 140. Stack using Linked List: Pop Operation 10 NULL (200) (220) 20 (200) (240) 30 (220) (260) 30 (240) top ptr
  • 141. Stack using Linked List: Implementation  Define node struct Node { int data; struct Node *next; }*top = NULL; void push(int); void pop(); void display();
  • 142. main() { int choice, value; while(1) { printf("1. Pushn2. Popn3. Displayn4. Exitn"); printf("Enter your choice: "); scanf("%d",&choice); switch(choice){ case 1: printf("Enter the value to be insert: "); scanf("%d", &value); push(value); break; case 2: pop(); break; case 3: display(); break; case 4: exit(0); default: printf("nWrong Option!!!n"); } } }
  • 143. void push(int value) { struct Node *newNode; newNode = (struct Node*)malloc(sizeof(struct Node)); newNode  data = value; if(top == NULL) newNodenext = NULL; else newNode  next = top; top = newNode; printf("nInsertion is Success!!!n"); }
  • 144. void pop() { if(top == NULL) printf("nStack is Empty!!!n"); else{ struct Node *temp = top; printf("nDeleted element: %d", tempdata); top = tempnext; free(temp); } }
  • 145. void display() { if(top == NULL) printf("nStack is Empty!!!n"); else{ struct Node *temp = top; while(tempnext != NULL) { printf("%d--->",temp->data); temp = temp  next; } printf("%d--->NULL",tempdata); } }
  • 146. Stack using Linked List: Implementation  Define node typedef struct stack { int no; struct stack *next; } node; node *top=NULL; static int count=0; void push(); void pop(); void display();
  • 147. node *p; p=(node *)malloc(sizeof(node)); printf("Enter no. to be pushed: "); scanf("%d",&p->no); if(top==NULL) { pnext=NULL; top=p; count++; return; } pnext=top; top=p; count++; Push Operation: Implementation
  • 148. Pop Operation: Implementation node *ptr; if(top==NULL) { printf("Stack is Empty"); return; } ptr=top; printf(“Popped number is: %d",ptrno); top=topnext; free(ptr); count--; }
  • 149. Display Operation: Implementation node *ptr; printf("Total elements=%d",count); if(top==NULL) { printf("nStack is empty"); return; } ptr=top; while(ptr != NULL) { printf("%d ",ptrno); ptr=ptrnext; }
  • 150. Main function void main() { int ch; do { printf("n1.Push 2.Pop 3.Display 4.Exit"); printf("nEnter your choice: "); scanf("%d",&ch); switch(ch) {case 1:push();break; case 2:pop(); break; case 3:display(); } } while(ch<4); }
  • 151. Unit 4  Queue in Data structure  Applications of Queues  Operations on Queues  Queue implementation using Arrays & LL  Circular Queue
  • 152. What is Queue  Queue is a linear data structure in which the insertion operation takes place at one end (Rear) and deletion operation at the other end (Front).  Queues can be implemented using either array or linked list.  Queue follows FIFO (First In First Out) principle
  • 153. Queue Operations  Enqueue  Dequeue  Display the elements of Queue  Queues can be implemented using either Array of Linked List
  • 154. Queue using array (Insertion) if (rear == MAX - 1) printf("Queue is Full n"); else { if (front == - 1) front = 0; printf("Insert element in queue : "); scanf("%d", &value); rear = rear + 1; QueueA[rear] = value; } front = rear = -1 rear == MAX – 1 Print Queue Full front = -1 True: front = 0 Accept value rear = rear + 1 QueueA[rear] = value False: True:
  • 155. Queue using array (Deletion) if (front == - 1 || front > rear) { printf("Queue is Empty n"); return ; } else { printf(“Deleted no. is : %dn", QueueA[front]); front = front + 1; } Print 'Deleted no. is', QueueA[front] front = front + 1 Queue is empty when? front = -1 front > rear || print Queue is Empty False: True:
  • 156. Queue using Array (Display) if (front == - 1) printf("Queue is empty n"); else { printf("Queue is : n"); for (i = front; i <= rear; i++) printf("%d ", QueueA[i]); } i = front i<=rear Print QueueA[i] i++ front = -1 Print "Queue is Empty" for( ; ; ) False: True:
  • 157. Queue using Linked List: Insertion 10 NULL no *next node (200) front = NULL rear = NULL front = (200) rear = NULL (220) 20 NULL 10 (220) front = (200) rear = (220) (240) 30 NULL 20 (240) front = (200) rear = (240) (260) 40 NULL 30 (260) front = (200) rear = (260)
  • 158. Queue using Linked List: Deletion (200) (220) 20 NULL (240) 30 NULL 20 (240) (260) 40 NULL 30 (260) front = (200) rear = (260) 10 (220) front = (200) rear = (260) ptr= front = (200) 10 (220)
  • 159. Queue using Linked List: Deletion (200) (220) 20 NULL (240) 30 NULL 20 (240) (260) 40 NULL 30 (260) front = (220) rear = (260) 10 (220) front = (220) rear = (260) ptr = (200) 10 (220)
  • 160. Queue using Linked List: Deletion (200) (220) 20 NULL (240) 30 NULL 20 (240) (260) 40 NULL 30 (260) front = (220) rear = (260) 10 (220) front = (220) rear = (260) ptr = (220) 10 (220)
  • 161. Queue using Linked List: Deletion (220) 20 NULL (240) 30 NULL 20 (240) (260) 40 NULL 30 (260) front = (220) rear = (260) front = (220) rear = (260) ptr = (220)
  • 162. Queue using Linked List: Deletion (220) 20 NULL (240) 30 NULL 20 (240) (260) 40 NULL 30 (260) front = (220) rear = (260) front = (240) rear = (260) ptr = (220)
  • 163. Queue using Linked List: Deletion (240) 30 NULL (260) 40 NULL 30 (260) front = (240) rear = (260) front = (240) rear = (260) ptr = (240)
  • 164. Queue using Linked List  Algorithm and Explanation for Insertion (Enqueue)  Algorithm and Explanation for Deletion (Dequeue)  Algorithm and Explanation for Display (Traversing)
  • 165. Alg & Explanation for Insertion no *next node Insertion() 1. Create node p and allocate memory 2. Accept no, store in p  no 3. Assign plink=NULL; 4. Check if rear=NULL True: a. front=rear=p; b. return; 5. rear  link=p; 6. rear = p; 10 NULL (200) front = rear = NULL front rear (220) 20 NULL 10 (220)
  • 166. Alg & Explanation for Insertion no *next node Insertion() 1. Create node p and allocate memory 2. Accept no, store in p  no 3. Assign plink=NULL; 4. Check if rear=NULL True: a. front=rear=p; b. return; 5. rear  link=p; 6. rear = p; 10 NULL (200) front = rear = NULL front rear (220) 20 NULL 10 (220) (240) 30 NULL 20 (240)
  • 167. Alg & Explanation for Insertion no *next node Insertion() 1. Create node p and allocate memory 2. Accept no, store in p  no 3. Assign plink=NULL; 4. Check if rear=NULL True: a. front=rear=p; b. return; 5. rear  link=p; 6. rear = p; 10 NULL (200) front = rear = NULL front rear (220) 20 NULL 10 (220) (240) 30 NULL 20 (240)
  • 168. Alg & Explanation for Deletion no *next node Deletion 1. if(front==NULL) a. Print “Queue Empty” b. Return 2. ptr = front; 3. front=frontlink; 4. if(front==NULL) a. rear=NULL; 5. Print ptrno; 6. free(ptr); 10 NULL (200) front = (200) rear = (240) front rear (220) 20 NULL 10 (220) (240) 30 NULL 20 (240)
  • 169. Alg & Explanation for Deletion no *next node Deletion 1. if(front==NULL) a. Print “Queue Empty” b. Return 2. ptr = front; 3. front=frontlink; 4. if(front==NULL) a. rear=NULL; 5. Print ptrno; 6. free(ptr); 10 NULL (200) front = (200) rear = (240) ptr = (200) front rear (220) 20 NULL 10 (220) (240) 30 NULL 20 (240) ptr
  • 170. Alg & Explanation for Deletion no *next node Deletion 1. if(front==NULL) a. Print “Queue Empty” b. Return 2. ptr = front; 3. front=frontlink; 4. if(front==NULL) a. rear=NULL; 5. Print ptrno; 6. free(ptr); 10 NULL (200) front = (220) rear = (240) ptr = 200 front rear (220) 20 NULL 10 (220) (240) 30 NULL 20 (240) ptr
  • 171. Alg & Explanation for Deletion no *next node Deletion 1. if(front==NULL) a. Print “Queue Empty” b. Return 2. ptr = front; 3. front=frontlink; 4. if(front==NULL) a. rear=NULL; 5. Print ptrno; 6. free(ptr); 10 NULL (200) front = (220) rear = (240) front rear (220) 20 NULL 10 (220) (240) 30 NULL 20 (240) ptr
  • 172. Alg & Explanation for Deletion no *next node Deletion 1. if(front==NULL) a. Print “Queue Empty” b. Return 2. ptr = front; 3. front=frontlink; 4. if(front==NULL) a. rear=NULL; 5. Print ptrno; 6. free(ptr); front = (220) rear = (240) ptr = (220) front rear (220) 20 NULL (240) 30 NULL 20 (240) ptr
  • 173. Alg & Explanation for Deletion no *next node Deletion 1. if(front==NULL) a. Print “Queue Empty” b. Return 2. ptr = front; 3. front=frontlink; 4. if(front==NULL) a. rear=NULL; 5. Print ptrno; 6. free(ptr); front = (240) rear = (240) ptr = (220) front rear (220) 20 NULL (240) 30 NULL 20 (240) ptr
  • 174. Alg & Explanation for Deletion no *next node Deletion 1. if(front==NULL) a. Print “Queue Empty” b. Return 2. ptr = front; 3. front=frontlink; 4. if(front==NULL) a. rear=NULL; 5. Print ptrno; 6. free(ptr); front = (240) rear = (240) ptr = (240) front rear (240) 30 NULL ptr
  • 175. Alg & Explanation for Deletion no *next node Deletion 1. if(front==NULL) a. Print “Queue Empty” b. Return 2. ptr = front; 3. front=frontlink; 4. if(front==NULL) a. rear=NULL; 5. Print ptrno; 6. free(ptr); front = NULL rear = NULL ptr = (240) front rear (240) 30 NULL ptr
  • 176. Algorithm for Display if(front == NULL) { Print “Queue is empty”; return; } ptr = front; while(ptr != NULL) { Print ptrno; ptr = ptrlink; } }
  • 177. Queue using Linked List: Implementation  Define node typedef struct queue { int no; struct queue *link; }node; void insertion(); void deletion(); void display(); node *front=NULL,*rear=NULL;
  • 178. insertion ( ) void insertion() { node *p; p=malloc(sizeof(node)); // Accept no and store in pno); plink=NULL; if(rear==NULL) { front=rear=p; return; } rearlink=p; rear=p; }
  • 179. Deletion ( ) void deletion() { node *ptr; if(front == NULL) { printf("nUnderflow"); return; } ptr = front; front = frontlink; if(front == NULL) rear = NULL; printf("nDeleted number is: %d",ptr  no); free(ptr); }
  • 180. Display ( ) void display() { node *ptr; if(front == NULL) { Print “Queue is empty”; return; } ptr = front; while(ptr != NULL) { Print ptrno; ptr = ptrlink; } }
  • 181. Main function void main() { int ch; do { printf("n1.Insert 2.Delete 3.Display 4.Exit"); printf("nEnter your choice: "); scanf("%d",&ch); switch(ch) { case 1:insertion();break; case 2:deletion();break; case 3:display(); } } while(ch<4); }
  • 182. Unit 5: Non Linear Data Structures  Tree: Basic terminology, Binary Trees  Representation of Binary Tree using array and LL  Binary Search Trees  Operations on BST: Insertion, Deletion  Recursive Traversals: PreOrder, InOrder, PostOrder
  • 183. Representation of binary tree using array
  • 184. Sequential representation of Binary Tree  For first case(0 to n-1), if root is indicated by „p‟; then left child=(2*p)+1; and right child=(2*p)+2;  For second case(1to n), if root=p; then left child=(2*p); and right child=(2*p)+1; where root, left child and right child are the values of indices of the array.
  • 187.
  • 188. Sequential representation  Advantages:  best representation for complete and full binary tree representation  Disadvantages:  Height of tree should be known  Memory may be wasted  Insertion and deletion of a node is difficult
  • 189. Binary Tree: Linked List Representation left right Root left right data left right data left right data left right data left right data left right data
  • 190. struct node { int data; struct node *left; struct node *right; }; /* Initialize nodes */ struct node *root; struct node *one = NULL; struct node *two = NULL; struct node *three = NULL; Binary Tree: Linked List Representation
  • 191. Binary Tree: Linked List Representation /* Allocate memory */ one = malloc(sizeof(struct node)); two = malloc(sizeof(struct node)); three = malloc(sizeof(struct node)); /* Assign data values */ Onedata = 1; two  data = 2; three  data = 3; /* Connect nodes */ oneleft = two; one  right = three; two  left = NULL; two  right = NULL; three  left = NULL; three  right = NULL; /* Save address of first node in root */ root = one;
  • 192. Binary Tree: Linked List Representation  Advantages:  Height of tree need not be known  No memory wastage  Insertion and deletion of a node is done without affecting other nodes  Disadvantages:  Direct access to node is difficult  Additional memory required for storing address of left and right node
  • 193. Binary Search Tree  A binary tree T is termed as binary search tree (or binary sorted tree) if each node N of T satisfies the following property: The value at N is a greater than every value in the left sub-tree of N and is less than every value in the right sub-tree of N.
  • 194. Binary Search Trees (BSTs)  Binary Search Tree Property: The value stored at a node is greater than the value stored at its left child and less than the value stored at its right child
  • 195. Construct BST: 10, 12, 5, 4, 20, 8, 7, 15, 13
  • 196. BST Example  Construct the Binary Search Tree for the given elements:  50, 17, 72, 12, 23, 54, 76, 9, 14, 19, 67
  • 197. Search an element in BST  Algorithm: 1. If (root == NULL) return NULL; 2. If (num == rootdata) return root  data; 3. If (num < root  data) return search(root  left) 4. If (num > root  data ) return search(root  right)
  • 198. struct node { int data; struct node* left; struct node* right; }; struct node* insert(struct node* root, int data) { if (root == NULL) return createNode(data); if (data < root  data) root  left = insert(root  left, data); else if (data > root  data) root  right = insert(root  right, data); return root; } struct node* createNode(value) { struct node* newNode=malloc(sizeof(struct node)); newNodedata = value; newNode  left = NULL; newNode  right = NULL; return newNode; } int main() { struct node *root = NULL; root = insert(root, 8); insert(root, 3); insert(root, 1); insert(root, 6); insert(root, 7); insert(root, 10); insert(root, 14); insert(root, 4); }
  • 199. Insert value in Binary Search Tree(BST)  Algorithm 1. If (node == NULL) return createNode(data) 2. if (data < nodedata) node  left = insert(node  left, data); 3. else if (data > node  data) node  right = insert(node  right, data); return node;
  • 200. Find the largest element in BST if ( root == null) { return NULLL; } struct node *currNode = root; while(currNoderight != null) { currNode = currNoderight; } return currNodedata;
  • 201. Deleting a node in BST  Three cases in deleting a node:  Case 1: Deleting a Leaf node (A node with no children)  Case 2: Deleting a node with one child  Case 3: Deleting a node with two children
  • 202. Case 1: Deleting a leaf node  Step 1 - Find the node to be deleted using search operation  Step 2 - Delete the node using free function (If it is a leaf) and assign NULL to the Parent‟s left or right accordingly.
  • 203. Case 2: Deleting a node with one child  Step 1 - Find the node to be deleted using search operation  Step 2 - If it has only one child then create a link between its parent node and child node.  Step 3 - Delete the node using free function and terminate the function.
  • 204. Deleting a node with one child
  • 205. Find the smallest element in BST if ( root == null ) return NULL; struct node *currNode = root; while(currNodeleft != null) { currNode = currNodeleft; } return currNodedata;
  • 206. Case 3: Deleting a node with two children Step1: Find the deletion node p (the node that we want to delete) Step 2: Find the successor node of p 2.1 Successor node is the node in the right subtree that has the minimum value (Or) 2.1 Successor node is the node in the left subtree that has the maximum value Step 3: Replace the content of node p with the content of the successor node Step 4: Delete the successor node
  • 207. Deleting a node with 2 children
  • 208. Recursive Tree Traversals  InOrder  PreOrder  PostOrder
  • 209. 209 Preoder, Inorder, Postorder  In Preorder, the root is visited before (pre) the subtrees traversals  In Inorder, the root is visited in-between left and right subtree traversal  In Postorder, the root is visited after (post) Preorder Traversal: 1. Visit the root 2. Traverse left subtree 3. Traverse right subtree Inorder Traversal: 1. Traverse left subtree 2. Visit the root 3. Traverse right subtree Postorder Traversal: 1. Traverse left subtree 2. Traverse right subtree 3. Visit the root
  • 210. InOrder Tree Traversal void InOrder (node *ptr) { if(ptr == NULL) return; else { InOrder(ptrleft); Print ptr  value InOrder (ptr  right); } }
  • 212. Pre Order Traversal void PreOrder(node *ptr) { if(ptr == NULL) return; else { Print ptr  value; PreOrder (ptr  left); PreOrder (ptr  right); } }