The document discusses various data structures and their operations. It begins with an introduction to linear data structures like arrays, linked lists, stacks and queues. It describes array implementation using sequential storage and linked list implementation using pointers. Common operations on these structures like traversal, insertion, deletion and searching are discussed. The document also covers non-linear data structures like trees and graphs and basic tree traversals. It provides examples of applications of different data structures and concludes with definitions of key terms.
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
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)
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
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
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
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
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;
}
}
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
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));
onedata=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",&pno,pname);
if(first==NULL)
{
plink=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 = firstlink;
while(ptr !=NULL && ptrno < pno)
{
save = ptr;
ptr = ptr->link;
}
savelink = p;
plink = 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 = firstlink;
while(ptr !=NULL && ptrno < pno)
{
save = ptr;
ptr = ptr->link;
}
savelink = p;
plink = 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"); } }
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");
}
}
}
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;
} } }
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"
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”
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)
newNodenext = NULL;
else
newNode next = top;
top = newNode;
printf("nInsertion is Success!!!n");
}
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)
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 plink=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 plink=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 plink=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=frontlink;
4. if(front==NULL)
a. rear=NULL;
5. Print ptrno;
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=frontlink;
4. if(front==NULL)
a. rear=NULL;
5. Print ptrno;
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=frontlink;
4. if(front==NULL)
a. rear=NULL;
5. Print ptrno;
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=frontlink;
4. if(front==NULL)
a. rear=NULL;
5. Print ptrno;
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=frontlink;
4. if(front==NULL)
a. rear=NULL;
5. Print ptrno;
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=frontlink;
4. if(front==NULL)
a. rear=NULL;
5. Print ptrno;
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=frontlink;
4. if(front==NULL)
a. rear=NULL;
5. Print ptrno;
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=frontlink;
4. if(front==NULL)
a. rear=NULL;
5. Print ptrno;
6. free(ptr);
front = NULL
rear = NULL
ptr = (240)
front
rear
(240)
30 NULL
ptr
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
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.
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
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 */
Onedata = 1;
two data = 2;
three data = 3;
/* Connect nodes */
oneleft = 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
199. Insert value in Binary Search Tree(BST)
Algorithm
1. If (node == NULL) return createNode(data)
2. if (data < nodedata)
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(currNoderight != null)
{
currNode = currNoderight;
}
return currNodedata;
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.
205. Find the smallest element in BST
if ( root == null ) return NULL;
struct node *currNode = root;
while(currNodeleft != null)
{
currNode = currNodeleft;
}
return currNodedata;
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
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