0% found this document useful (0 votes)
13 views137 pages

DS Lab Manual (2023-2024)

The document outlines the laboratory record for a Data Structures course in the II B.Tech - I Semester, detailing the vision and mission of the institution and department, program educational objectives, outcomes, and specific outcomes. It includes course objectives, outcomes, instructions for students, a list of experiments to be conducted, and evaluation criteria. Additionally, it provides a sample program for linked list operations in C programming.

Uploaded by

jayart.9949
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views137 pages

DS Lab Manual (2023-2024)

The document outlines the laboratory record for a Data Structures course in the II B.Tech - I Semester, detailing the vision and mission of the institution and department, program educational objectives, outcomes, and specific outcomes. It includes course objectives, outcomes, instructions for students, a list of experiments to be conducted, and evaluation criteria. Additionally, it provides a sample program for linked list operations in C programming.

Uploaded by

jayart.9949
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 137

DATA STRUCTURES

Laboratory Record
II B.Tech - I Semester
(A.Y. 2023-24)

Department of Information Technology

Student Name : ________________________________________________

Roll No : ________________________________________________
VISION & MISSION OF THE INSTITUTE & DEPARTMENT

VISION OF THE INSTITUTION

To empower female students with professional education using creative & innovative technical
practices of global competence and research aptitude to become competitive engineers with
ethical values and entrepreneurial skills.

MISSION OF THE INSTITUTION

1. To impart value based professional education through creative and innovative teaching
learning process to face the global challenges of the new era technology.

2. To inculcate research aptitude and to bring out creativity in students by imparting


engineering knowledge imbibing interpersonal skills to promote innovation, research and
entrepreneurship.

VISION OF THE DEPARTMENT OF IT

Debouch as a center of excellence for computer science engineering by imparting social, moral
and ethical values oriented education through advanced pedagogical techniques and produce
technologically and highly competent professionals of global standards with capabilities of
solving challenges of the time through innovative and creative solutions.

MISSION OF THE DEPARTMENT OF IT

M1: To envision inquisitive-driven advanced knowledge building among students to impart


foundational knowledge of computer science and its applications of all spheres using the
state-of-the-art facilities and software industry-institute interaction.

M2: To advance the department industry collaborations through interaction with professional
society through seminars/workshops/guest lectures and student internship programs.
M3: To nurture students with leadership qualities, communication skills and imbibe qualities
to work as a team member and a leader for the economic and technological development
in cutting edge technologies in national and global arena.

PROGRAM EDUCATIONAL OBJECTIVES (PEOs)

PEO-1: To provide graduates the foundational and essential knowledge in mathematics, science,
computer science and engineering and interdisciplinary engineering to emerge as
technocrats.

PEO-2: To inculcate the capabilities to analyze, design and develop innovative solutions of
computer support systems for benefits of the society, by diligence and teamwork.

PEO-3: To drive the graduates towards employment/purse higher studies/turn as


entrepreneurs.

PROGRAM OUTCOMES (POs)


Engineering Graduates will be able to:
1. Engineering Knowledge: Apply the knowledge of mathematics, science, engineering
fundamentals and an engineering specialization to the solution of complex
engineering problems
2. Problem analysis: Identify, formulate review research literature and analyze
complex engineering problems reaching substantiated conclusions using first
principle of mathematics, natural science and engineering science
3. Design/development of solutions: Design solutions for complex engineering
problems and design system components or processes that meet the specified needs
with appropriate consideration for the public health and safety, and the cultural,
societal, and environmental considerations
4. Conduct investigations of complex problems: Use research-based knowledge and
research methods including design of experiments, analysis and interpretation of data,
and synthesis of the information to provide valid conclusions
5. Modern tool usage: Create, select, and apply appropriate techniques, resources, and
modern engineering and IT tools including prediction and modeling to complex
engineering activities with an understanding of the limitations
6. The engineer and society: Apply reasoning informed by the contextual knowledge
to assess societal, health, safety, legal and cultural issues and the consequent
responsibilities relevant to the professional engineering practice
7. Environment and sustainability: Understand the impact of the professional
engineering solutions in societal and environmental contexts, and demonstrate the
knowledge of, and need for sustainable development
8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities
and norms of the engineering practice
9. Individual and team work: Function effectively as an individual, and as a member or
leader in diverse teams, and in multidisciplinary settings
10. Communication: Communicate effectively on complex engineering activities with
the engineering community and with society at large, such as, being able to
comprehend and write effective reports and design documentation, make effective
presentations, and give and receive clear instructions
11. Project management and finance: Demonstrate knowledge and understanding of the
engineering and management principles and apply these to one's own work, as a
member and leader in a team, to manage projects and in multidisciplinary
environments
12. Life-long learning: Recognize the need for, and have the preparation and ability to
engage in independent and life-long learning in the broadest context of technological
change
PROGRAM SPECIFIC OUTCOMES (PSOs)
A graduate of the Computer Science Engineering Program will be able to
1. Foundation on Software Development:
Ability to grasp the software development life cycle of software systems and possess
competent skills and knowledge of software design process.
2. Industrial Skills Ability:
Ability to interpret fundamental concepts and methodology of computer systems so
that students can understand the functionality of hardware and software aspects of
computer systems.
3. Ethical and Social Responsibility:
Communicate effectively in both verbal and written form, will have knowledge of
professional and ethical responsibilities and will show the understanding of impact of
engineering solutions on the society and also will be aware of contemporary issues.
DATA STRUCTURES

Course Objectives:
● It covers various concepts of C programming language
● It introduces searching and sorting algorithms
● It provides an understanding of data structures such as stacks and queues.

Course Outcomes:
● Ability to develop C programs for computing and real-life applications using basic elements
like control statements, arrays, functions, pointers and strings, and data structures like stacks,
queues and linked lists.
● Ability to Implement searching and sorting algorithms
INSTRUCTIONS TO STUDENTS

 All students must observe the Dress Code while in the laboratory.
 Sandals or open-toed shoes are NOT allowed.
 Foods, drinks and smoking are NOT allowed.
 All bags must be left at the indicated place.
 The lab timetable must be strictly followed.
 Be PUNCTUAL for your laboratory session.
 Noise must be kept to a minimum.
 Workspace must be kept clean and tidy at all time.
 All students are liable for any damage to the accessories due to their own negligence.
 All interfacing kits connecting cables must be RETURNED if you take from the lab
supervisor.
 Students are strictly PROHIBITED from taking out any items from the laboratory.
 Students are NOT allowed to work alone in the laboratory without the Lab Supervisor
 Report immediately to the Lab Supervisor if any malfunction of the accessories, is there.

Before leaving the lab


 Place the chairs properly.
 Please check the laboratory notice board regularly for updates.
DATA STRUCTURES

List of Experiments:
1. Write a program that uses functions to perform the following operations on singly
linked list.:
i) Creation ii) Insertion iii) Deletion iv) Traversal
2. Write a program that uses functions to perform the following operations on doubly
linked list.:
i) Creation ii) Insertion iii) Deletion iv) Traversal
3. Write a program that uses functions to perform the following operations on circular
linked list.:
i) Creation ii) Insertion iii) Deletion iv) Traversal
4. Write a program that implement stack (its operations) using
i) Arrays ii) Pointers
5. Write a program that implement Queue (its operations) using
i) Arrays ii) Pointers
6. Write a program that implements the following sorting methods to sort a given list of
integers in ascending order
i) Quick sort ii) Heap sort iii) Merge sort
7. Write a program to implement the tree traversal methods( Recursive and Non Recursive).
8. Write a program to implement
i) Binary Search tree ii) B Trees iii) B+ Trees iv) AVL
trees v) Red - Black trees
9. Write a program to implement the graph traversal methods.
10. Implement a Pattern matching algorithms using Boyer- Moore, Knuth-Morris-Pratt

TEXT BOOKS:
1. Fundamentals of Data Structures in C, 2nd Edition, E. Horowitz, S. Sahni and
Susan Anderson Freed, Universities Press.
2. Data Structures using C – A. S. Tanenbaum, Y. Langsam, and M. J. Augenstein,
PHI/Pearson Education.

REFERENCE BOOK:
1. Data Structures: A Pseudocode Approach with C, 2nd Edition, R. F. Gilberg
and B. A. Forouzan, Cengage Learning
Exp. No Experiment Name Page No

Write a program that uses functions to perform the following


1 operations on singly linked list i)Creation ii)
Insertion iii) Deletion iv) Traversal.
Write a program that uses functions to perform the following
2 operations on doubly linked list i)Creation ii)
Insertion iii) Deletion iv) Traversal.
Write a program that uses functions to perform the following
3 operations on circular linked List i)Creation ii)
Insertion iii) Deletion iv) Traversal.
Write a program that implement stack (its operations)
4
Using i)Arrays ii) Linked list(Pointers).
Write a program that implement Queue(its operations)
5
Using i) Arrays ii) Linked list(Pointers).
Write a program that implements the following
sorting methods to sort a given list of integers in
6 ascending order
i)quick sort ii) heap sort iii)merge sort

Write a program to implement the tree traversal


7
methods( Recursive and Non Recursive).

Write a program to implement


8
(i)Binary Search tree ii) B Trees iii) B+ Trees iv)AVL
trees v) Red - Black trees

Write a program to implement the graph traversal methods


9
Implement a Pattern matching algorithms using Boyer-
Moore, Knuth-Morris-Pratt
10

INDEX
EVALUATION SHEET
A-Regularity B – Record submission in-time C – Viva-Voce D - Experimentation

Cycle 1:

Exp A B C D Faculty
Experiment Name Date TOTAL
No 2 3 4 6 (T=A+B+C+D) Sign
Write a program that uses
functions to perform the
1
following operations on singly
linked list i)Creation ii)
Insertion iii) Deletion iv)
Traversal.
Write a program that uses
functions to perform the
following operations on doubly
2
linked list i)Creation ii)
Insertion iii) Deletion iv)
Traversal.
Write a program that uses
functions to perform the
3
following operations on circular
linked List i)Creation ii)
Insertion iii) Deletion iv)
Traversal.
Write a program that implement
4
stack (its operations)
Using i)Arrays ii) Linked
list(Pointers).
Write a program that implement
5
Queue(its operations)
Using i) Arrays ii) Linked
list(Pointers).
First Cycle Average Marks : Faculty Sign with Date

Cycle 2:

Exp A B C D TOTAL Faculty


Experiment Name Date
No 2 3 4 6 (T=A+B+C+D) Sign
Write a program that
implements the
following sorting
1 methods to sort a given
list of integers in
ascending order
i)quick sort ii) heap sort
iii)merge sort
Write a program to implement
the tree traversal
2 methods( Recursive and Non
Recursive).

Write a program to implement


(i)Binary Search tree ii)
B Trees iii) B+ Trees
3
iv)AVL trees v) Red -
Black trees

Write a program to implement


4
the graph traversal methods
Implement a Pattern matching
algorithms using Boyer- Moore,
5 Knuth-Morris-Pratt
Second Cycle Average Marks : Faculty Sign with Date

1. Write a program that uses functions to perform the following operations on singly linked list.:
i) Creation ii) Insertion iii) Deletion iv)Traversal
#include<stdio.h>

#include<stdlib.h>

struct Node;

typedef struct Node * PtrToNode;

typedef PtrToNode List;

typedef PtrToNode Position;

struct Node

int e;

Position next;

};

void Insert(int x, List l, Position p)

Position TmpCell;

TmpCell = (struct Node*) malloc(sizeof(struct Node));

if(TmpCell == NULL)

printf("Memory out of space\n");

else

TmpCell->e = x;
TmpCell->next = p->next;

p->next = TmpCell;

int isLast(Position p)

return (p->next == NULL);

Position FindPrevious(int x, List l)

Position p = l;

while(p->next != NULL && p->next->e != x)

p = p->next;

return p;

void Delete(int x, List l)

Position p, TmpCell;

p = FindPrevious(x, l);

if(!isLast(p))

TmpCell = p->next;

p->next = TmpCell->next;

free(TmpCell);

else

printf("Element does not exist!!!\n");

}
void Display(List l)

printf("The list element are :: ");

Position p = l->next;

while(p != NULL)

printf("%d -> ", p->e);

p = p->next;

void Merge(List l, List l1)

int i, n, x, j;

Position p;

printf("Enter the number of elements to be merged :: ");

scanf("%d",&n);

for(i = 1; i <= n; i++)

p = l1;

scanf("%d", &x);

for(j = 1; j < i; j++)

p = p->next;

Insert(x, l1, p);

printf("The new List :: ");

Display(l1);

printf("The merged List ::");

p = l;
while(p->next != NULL)

p = p->next;

p->next = l1->next;

Display(l);

int main()

int x, pos, ch, i;

List l, l1;

l = (struct Node *) malloc(sizeof(struct Node));

l->next = NULL;

List p = l;

printf("LINKED LIST IMPLEMENTATION OF LIST ADT\n\n");

do

printf("\n\n1. INSERT\t 2. DELETE\t 3. MERGE\t 4. PRINT\t 5. QUIT\n\nEnter the choice :: ");

scanf("%d", &ch);

switch(ch)

case 1:

p = l;

printf("Enter the element to be inserted :: ");

scanf("%d",&x);

printf("Enter the position of the element :: ");

scanf("%d",&pos);

for(i = 1; i < pos; i++)


{

p = p->next;

Insert(x,l,p);

break;

case 2:

p = l;

printf("Enter the element to be deleted :: ");

scanf("%d",&x);

Delete(x,p);

break;

case 3:

l1 = (struct Node *) malloc(sizeof(struct Node));

l1->next = NULL;

Merge(l, l1);

break;

case 4:

Display(l);

break;

while(ch<5);

return 0;

OUTPUT:

LINKED LIST IMPLEMENTATION OF LIST ADT


1. INSERT 2. DELETE 3. MERGE 4. PRINT 5. QUIT
Enter the choice :: 1
Enter the element to be inserted :: 10
Enter the position of the element :: 1
1. INSERT 2. DELETE 3. MERGE 4. PRINT 5. QUIT
Enter the choice :: 1
Enter the element to be inserted :: 20
Enter the position of the element :: 2
1. INSERT 2. DELETE 3. MERGE 4. PRINT 5. QUIT
Enter the choice :: 1
Enter the element to be inserted :: 30
Enter the position of the element :: 3
1. INSERT 2. DELETE 3. MERGE 4. PRINT 5. QUIT
Enter the choice :: 4
The list element are :: 10 -> 20 -> 30 ->
1. INSERT 2. DELETE 3. MERGE 4. PRINT 5. QUIT
Enter the choice :: 5

2. Write a program that uses functions to perform the following operations on doubly linked list:
i) Creation ii) Insertion iii) Deletion iv) Traversal
#include<stdio.h>
#include<stdlib.h>

struct node
{
struct node *prev;
int n;
struct node *next;
}*h,*temp,*temp1,*temp2,*temp4;

void insert1();
void insert2();
void insert3();
void traversebeg();
void traverseend(int);
void sort();
void search();
void update();
voiddelete();

int count = 0;

void main()
{
int ch;

h = NULL;
temp = temp1 = NULL;

printf("\n 1 - Insert at beginning");


printf("\n 2 - Insert at end");
printf("\n 3 - Insert at position i");
printf("\n 4 - Delete at i");
printf("\n 5 - Display from beginning");
printf("\n 6 - Display from end");
printf("\n 7 - Search for element");
printf("\n 8 - Sort the list");
printf("\n 9 - Update an element");
printf("\n 10 - Exit");

while (1)
{
printf("\n Enter choice : ");
scanf("%d", &ch);
switch (ch)
{
case1:
insert1();
break;
case2:
insert2();
break;
case3:
insert3();
break;
case4:
delete();
break;
case5:
traversebeg();
break;
case6:
temp2 = h;
if (temp2 == NULL)
printf("\n Error : List empty to display ");
else
{
printf("\n Reverse order of linked list is : ");
traverseend(temp2->n);
}
break;
case7:
search();
break;
case8:
sort();
break;
case9:
update();
break;
case10:
exit(0);
default:
printf("\n Wrong choice menu");
}
}
}

/* TO create an empty node */


void create()
{
int data;

temp =(struct node *)malloc(1*sizeof(struct node));


temp->prev = NULL;
temp->next = NULL;
printf("\n Enter value to node : ");
scanf("%d", &data);
temp->n = data;
count++;
}

/* TO insert at beginning */
void insert1()
{
if (h == NULL)
{
create();
h = temp;
temp1 = h;
}
else
{
create();
temp->next = h;
h->prev = temp;
h = temp;
}
}

/* To insert at end */
void insert2()
{
if (h == NULL)
{
create();
h = temp;
temp1 = h;
}
else
{
create();
temp1->next = temp;
temp->prev = temp1;
temp1 = temp;
}
}

/* To insert at any position */


void insert3()
{
int pos, i = 2;

printf("\n Enter position to be inserted : ");


scanf("%d", &pos);
temp2 = h;

if ((pos <1) || (pos >= count + 1))


{
printf("\n Position out of range to insert");
return;
}
if ((h == NULL) && (pos != 1))
{
printf("\n Empty list cannot insert other than 1st position");
return;
}
if ((h == NULL) && (pos == 1))
{
create();
h = temp;
temp1 = h;
return;
}
else
{
while (i < pos)
{
temp2 = temp2->next;
i++;
}
create();
temp->prev = temp2;
temp->next = temp2->next;
temp2->next->prev = temp;
temp2->next = temp;
}
}

/* To delete an element */
voiddelete()
{
int i = 1, pos;

printf("\n Enter position to be deleted : ");


scanf("%d", &pos);
temp2 = h;

if ((pos <1) || (pos >= count + 1))


{
printf("\n Error : Position out of range to delete");
return;
}
if (h == NULL)
{
printf("\n Error : Empty list no elements to delete");
return;
}
else
{
while (i < pos)
{
temp2 = temp2->next;
i++;
}
if (i == 1)
{
if (temp2->next == NULL)
{
printf("Node deleted from list");
free(temp2);
temp2 = h = NULL;
return;
}
}
if (temp2->next == NULL)
{
temp2->prev->next = NULL;
free(temp2);
printf("Node deleted from list");
return;
}
temp2->next->prev = temp2->prev;
if (i != 1)
temp2->prev->next = temp2->next; /* Might not need this statement if i == 1 check */
if (i == 1)
h = temp2->next;
printf("\n Node deleted");
free(temp2);
}
count--;
}

/* Traverse from beginning */


void traversebeg()
{
temp2 = h;

if (temp2 == NULL)
{
printf("List empty to display \n");
return;
}
printf("\n Linked list elements from begining : ");

while (temp2->next != NULL)


{
printf(" %d ", temp2->n);
temp2 = temp2->next;
}
printf(" %d ", temp2->n);
}

/* To traverse from end recursively */


void traverseend(int i)
{
if (temp2 != NULL)
{
i = temp2->n;
temp2 = temp2->next;
traverseend(i);
printf(" %d ", i);
}
}

/* To search for an element in the list */


void search()
{
int data, count = 0;
temp2 = h;

if (temp2 == NULL)
{
printf("\n Error : List empty to search for data");
return;
}
printf("\n Enter value to search : ");
scanf("%d", &data);
while (temp2 != NULL)
{
if (temp2->n == data)
{
printf("\n Data found in %d position",count + 1);
return;
}
else
temp2 = temp2->next;
count++;
}
printf("\n Error : %d not found in list", data);
}

/* To update a node value in the list */


void update()
{
int data, data1;

printf("\n Enter node data to be updated : ");


scanf("%d", &data);
printf("\n Enter new data : ");
scanf("%d", &data1);
temp2 = h;
if (temp2 == NULL)
{
printf("\n Error : List empty no node to update");
return;
}
while (temp2 != NULL)
{
if (temp2->n == data)
{

temp2->n = data1;
traversebeg();
return;
}
else
temp2 = temp2->next;
}

printf("\n Error : %d not found in list to update", data);


}

/* To sort the linked list */


void sort()
{
int i, j, x;

temp2 = h;
temp4 = h;

if (temp2 == NULL)
{
printf("\n List empty to sort");
return;
}

for (temp2 = h; temp2 != NULL; temp2 = temp2->next)


{
for (temp4 = temp2->next; temp4 != NULL; temp4 = temp4->next)
{
if (temp2->n > temp4->n)
{
x = temp2->n;
temp2->n = temp4->n;
temp4->n = x;
}
}
}
traversebeg();
}
OUTPUT
1 - Insert at beginning
2 - Insert at end
3 - Insert at position i
4 - Delete at i
5 - Display from beginning
6 - Display from end
7 - Search for element
8 - Sort the list
9 - Update an element
10 - Exit
Enter choice : 1
Enter value to node : 10
Enter choice : 2
Enter value to node : 50
Enter choice : 4
Enter position to be deleted : 1
Node deleted
Enter choice : 1
Enter value to node : 34
Enter choice : 3
Enter position to be inserted : 2
Enter value to node : 13
Enter choice : 4
Enter position to be deleted : 4
Error : Position out of range to delete
Enter choice : 1
Enter value to node : 15
Enter choice : 1
Enter value to node : 67
Enter choice : 3
Enter position to be inserted : 2
Enter value to node : 34
Enter choice : 4
Enter position to be deleted : 3
Node deleted
Enter choice : 7
Enter value to search : 15
Error : 15 not found in list
Enter choice : 8
Linked list elements from begining : 13 34 34 50 67
Enter choice : 9
Enter node data to be updated : 45
Enter new data : 89
Error : 45 not found in list to update
Enter choice : 9
Enter node data to be updated : 50
Enter new data : 90
Enter choice : 5
Linked list elements from begining : 13 34 34 90 67
Enter choice : 6
Reverse order of linked list is : 67 90 34 34 13
Enter choice : 7
Enter value to search : 90
Data found in 4 position
Enter choice : 8
Linked list elements from begining : 13 34 34 67 90
Enter choice : 7
Enter value to search : 90
Data found in 5 position
Enter choice : 9
Enter node data to be updated : 34
Enter new data : 56
Linked list elements from begining : 13 56 34 67 90
Enter choice : 10

3. write a program that uses functions to perform the following operations on circular linked list

i. creation, ii .insertion, iii. deletion, iv. traversal

#include <stdio.h>

#include <stdlib.h>

struct node

int data;

struct node *link;

};

struct node *head = NULL, *x, *y, *z;

void create();

void ins_at_beg();

void ins_at_pos();

void del_at_beg();

void del_at_pos();

void traverse();

void search();

void sort();

void update();

void rev_traverse(struct node *p);

void main()
{

int ch;

printf("\n 1.Creation \n 2.Insertion at beginning \n 3.Insertion at remaining");

printf("\n4.Deletion at beginning \n5.Deletion at remaining \n6.traverse");

printf("\n7.Search\n8.sort\n9.update\n10.Exit\n");

while (1)

printf("\n Enter your choice:");

scanf("%d", &ch);

switch(ch)

case 1:

create();

break;

case 2:

ins_at_beg();

break;

case 3:

ins_at_pos();

break;

case 4:

del_at_beg();

break;

case 5:

del_at_pos();

break;

case 6:
traverse();

break;

case 7:

search();

break;

case 8:

sort();

break;

case 9:

update();

break;

case 10:

rev_traverse(head);

break;

default:

exit(0);

/*Function to create a new circular linked list*/

void create()

int c;

x = (struct node*)malloc(sizeof(struct node));

printf("\n Enter the data:");

scanf("%d", &x->data);

x->link = x;

head = x;
printf("\n If you wish to continue press 1 otherwise 0:");

scanf("%d", &c);

while (c != 0)

y = (struct node*)malloc(sizeof(struct node));

printf("\n Enter the data:");

scanf("%d", &y->data);

x->link = y;

y->link = head;

x = y;

printf("\n If you wish to continue press 1 otherwise 0:");

scanf("%d", &c);

/*Function to insert an element at the begining of the list*/

void ins_at_beg()

x = head;

y = (struct node*)malloc(sizeof(struct node));

printf("\n Enter the data:");

scanf("%d", &y->data);

while (x->link != head)

x = x->link;

x->link = y;

y->link = head;

head = y;
}

/*Function to insert an element at any position the list*/

void ins_at_pos()

struct node *ptr;

int c = 1, pos, count = 1;

y = (struct node*)malloc(sizeof(struct node));

if (head == NULL)

printf("cannot enter an element at this place");

printf("\n Enter the data:");

scanf("%d", &y->data);

printf("\n Enter the position to be inserted:");

scanf("%d", &pos);

x = head;

ptr = head;

while (ptr->link != head)

count++;

ptr = ptr->link;

count++;

if (pos > count)

printf("OUT OF BOUND");

return;

}
while (c < pos)

z = x;

x = x->link;

c++;

y->link = x;

z->link = y;

/*Function to delete an element at any begining of the list*/

void del_at_beg()

if (head == NULL)

printf("\n List is empty");

else

x = head;

y = head;

while (x->link != head)

x = x->link;

head = y->link;

x->link = head;

free(y);

/*Function to delete an element at any position the list*/


void del_at_pos()

if (head == NULL)

printf("\n List is empty");

else

int c = 1, pos;

printf("\n Enter the position to be deleted:");

scanf("%d", &pos);

x = head;

while (c < pos)

y = x;

x = x->link;

c++;

y->link = x->link;

free(x);

/*Function to display the elements in the list*/

void traverse()

if (head == NULL)

printf("\n List is empty");

else

x = head;
while (x->link != head)

printf("%d->", x->data);

x = x->link;

printf("%d", x->data);

/*Function to search an element in the list*/

void search()

int search_val, count = 0, flag = 0;

printf("\nenter the element to search\n");

scanf("%d", &search_val);

if (head == NULL)

printf("\nList is empty nothing to search");

else

x = head;

while (x->link != head)

if (x->data == search_val)

printf("\nthe element is found at %d", count);

flag = 1;

break;

count++;
x = x->link;

if (x->data == search_val)

printf("element found at postion %d", count);

if (flag == 0)

printf("\nelement not found");

/*Function to sort the list in ascending order*/

void sort()

struct node *ptr, *nxt;

int temp;

if (head == NULL)

printf("empty linkedlist");

else

ptr = head;

while (ptr->link != head)

nxt = ptr->link;
while (nxt != head)

if (nxt != head)

if (ptr->data > nxt->data)

temp = ptr->data;

ptr->data = nxt->data;

nxt->data = temp;

else

break;

nxt = nxt->link;

ptr = ptr->link;

/*Function to update an element at any position the list*/

void update()

struct node *ptr;

int search_val;

int replace_val;

int flag = 0;
if (head == NULL)

printf("\n empty list");

else

printf("enter the value to be edited\n");

scanf("%d", &search_val);

fflush(stdin);

printf("enter the value to be replace\n");

scanf("%d", &replace_val);

ptr = head;

while (ptr->link != head)

if (ptr->data == search_val)

ptr->data = replace_val;

flag = 1;

break;

ptr = ptr->link;

if (ptr->data == search_val)

ptr->data = replace_val;

flag = 1;

}
if (flag == 1)

printf("\nUPdate sucessful");

else

printf("\n update not successful");

/*Function to display the elements of the list in reverse order*/

void rev_traverse(struct node *p)

int i = 0;

if (head == NULL)

printf("empty linked list");

else

if (p->link != head)

i = p->data;

rev_traverse(p->link);

printf(" %d", i);

if (p->link == head)

{
printf(" %d", p->data);

output

1.Creation
2.Insertion at beginning
3.Insertion at remaining
4.Deletion at beginning
5.Deletion at remaining
6.traverse
7.Search
8.sort
9.update
10.Exit
Enter your choice:6
List is empty
Enter your choice:5
List is empty
Enter your choice:9
empty list
Enter your choice:7
enter the element to search
12
List is empty nothing to search
Enter your choice:1
Enter the data:10
If you wish to continue press 1 otherwise 0:0
Enter your choice:3
Enter the data:20
Enter the position to be inserted:5
OUT OF BOUND
Enter your choice:2
Enter the data:12
Enter your choice:6
12->10
Enter your choice:3
Enter the data:13
Enter the position to be inserted:3
Enter your choice:3
Enter the data:14
Enter the position to be inserted:4
Enter your choice:6
12->10->13->14
Enter your choice:3
Enter the data:24
Enter the position to be inserted:4
Enter your choice:6
12->10->13->24->14
Enter your choice:3
Enter the data:10
Enter the position to be inserted:100
OUT OF BOUND
Enter your choice:4
Enter your choice:6
10->13->24->14
Enter your choice:5
Enter the position to be deleted:4
Enter your choice:6
10->13->24
Enter your choice:5
Enter the position to be deleted:2
Enter your choice:6
10->24
Enter your choice:9
enter the value to be edited
23
enter the value to be replace
24
update not successful
Enter your choice:9
enter the value to be edited
24
enter the value to be replace
26
UPdate sucessful
Enter your choice:6
10->26
Enter your choice:7
enter the element to search
26
element found at postion 1
element not found
Enter your choice:7
enter the element to search
27
element not found
Enter your choice:8
Enter your choice:6
10->26
Enter your choice:10
26 10
Enter your choice:11
4. write a program that implements stack using
i. arrays ii. Pointers
i. arrays
#include<stdio.h>

int stack[100],choice,n,top,x,i;

void push(void);

void pop(void);

void display(void);

int main()

//clrscr();

top=-1;

printf("\n Enter the size of STACK[MAX=100]:");

scanf("%d",&n);

printf("\n\t STACK OPERATIONS USING ARRAY");

printf("\n\t--------------------------------");

printf("\n\t 1.PUSH\n\t 2.POP\n\t 3.DISPLAY\n\t 4.EXIT");

do

printf("\n Enter the Choice:");

scanf("%d",&choice);
switch(choice)

case 1:

push();

break;

case 2:

pop();

break;

case 3:

display();

break;

case 4:

printf("\n\t EXIT POINT ");

break;

default:

printf ("\n\t Please Enter a Valid Choice(1/2/3/4)");

}
while(choice!=4);

return 0;

void push()

if(top>=n-1)

printf("\n\tSTACK is over flow");

else

printf(" Enter a value to be pushed:");

scanf("%d",&x);

top++;

stack[top]=x;

void pop()

if(top<=-1)

printf("\n\t Stack is under flow");

else

printf("\n\t The popped elements is %d",stack[top]);

top--;

}
}

void display()

if(top>=0)

printf("\n The elements in STACK \n");

for(i=top; i>=0; i--)

printf("\n%d",stack[i]);

printf("\n Press Next Choice");

else

printf("\n The STACK is empty");

OUTPUT:

Enter the size of STACK[MAX=100]:10

STACK OPERATIONS USING ARRAY

--------------------------------

1.PUSH

2.POP

3.DISPLAY

4.EXIT

Enter the Choice:1

Enter a value to be pushed:12

Enter the Choice:1

Enter a value to be pushed:24

Enter the Choice: 2


Enter a value to be pushed:98

Enter the Choice:3

The elements in STACK

98

24

12

Press Next Choice

Enter the Choice:2

The popped elements is 98

Enter the Choice:3

The elements in STACK 24

12

Press Next Choice

Enter the Choice:4

EXIT POINT

ii. using pointers

#include<stdio.h>

#include<stdlib.h>
#define MAX_SIZE 3
void push(int i);
void pop(void);
int choice, i;
int *tos, *p1, arr_stack[MAX_SIZE];
int exit_p = 1;
int main()
{
int value;
tos = arr_stack; /* tos points to the top of stack */
p1 = arr_stack; /* initialize p1 */
printf("\n Simple Stack Example - Pointers");
do {
printf("\nStack Pointer : Main Menu");
printf("\n1.Push \t2.Pop \tOthers to exit : Your Choice : ");
scanf("%d", &choice);
switch (choice) {
case1:
printf("Enter value: ");
scanf("%d", &value);
push(value);
break;
case2:
pop();
break;
default:
exit_p = 0;
break;
}
} while (exit_p);
return0;
}
void push(int i) {
if (p1 == (tos + MAX_SIZE)) {
printf("\nStatus : Stack Overflow.\n");
} else {
*p1 = i;
printf("\nPush Value : %d ", *(p1));
p1++;
}
}
void pop(void) {
if (p1 == tos) {
printf("\nStatus : Stack Underflow.\n");
//return 0;
} else {
p1--;
printf("\nPop Value : %d ", *(p1));
}
}
OUTPUT

Simple Stack Example - Pointers


Stack Pointer : Main Menu
1.Push 2.Pop Others to exit : Your Choice : 1
Enter value: 100
Push Value : 100
Stack Pointer : Main Menu
1.Push 2.Pop Others to exit : Your Choice : 1
Enter value: 200
Push Value : 200
Stack Pointer : Main Menu
1.Push 2.Pop Others to exit : Your Choice : 1
Enter value: 300
Push Value : 300
Stack Pointer : Main Menu
1.Push 2.Pop Others to exit : Your Choice : 1
Enter value: 400
Status : Stack Overflow.
Stack Pointer : Main Menu
1.Push 2.Pop Others to exit : Your Choice : 1
Enter value: 500
Status : Stack Overflow.
Stack Pointer : Main Menu
1.Push 2.Pop Others to exit : Your Choice : 1
Enter value: 2
Status : Stack Overflow.
Stack Pointer : Main Menu
1.Push 2.Pop Others to exit : Your Choice : 2
Pop Value : 300
Stack Pointer : Main Menu
1.Push 2.Pop Others to exit : Your Choice : 2
Pop Value : 200
Stack Pointer : Main Menu
1.Push 2.Pop Others to exit : Your Choice : 2
Pop Value : 100
Stack Pointer : Main Menu
1.Push 2.Pop Others to exit : Your Choice : 2
Status : Stack Underflow.
Stack Pointer : Main Menu
1.Push 2.Pop Others to exit : Your Choice : 3

5. write a program that implements queue using


i. arrays ii. Pointers
i. arrays
#include<stdio.h>

#define n 5
void main()
{
int queue[n],ch=1,front=0,rear=0,i,j=1,x=n;
//clrscr();
printf("Queue using Array");
printf("\n1.Insertion \n2.Deletion \n3.Display \n4.Exit");
while(ch)
{
printf("\nEnter the Choice:");
scanf("%d",&ch);
switch(ch)
{
case1:
if(rear==x)
printf("\n Queue is Full");
else
{
printf("\n Enter no %d:",j++);
scanf("%d",&queue[rear++]);
}
break;
case2:
if(front==rear)
{
printf("\n Queue is empty");
}
else
{
printf("\n Deleted Element is %d",queue[front++]);
x++;
}
break;
case3:
printf("\n Queue Elements are:\n ");
if(front==rear)
printf("\n Queue is Empty");
else
{
for(i=front; i<rear; i++)
{
printf("%d",queue[i]);
printf("\n");
}
break;
case4:
exit(0);
default:
printf("Wrong Choice: please see the options");
}
}
}

OUTPUT
Queue using Array
1.Insertion
2.Deletion
3.Display
4.Exit
Enter the Choice:1
Enter no 1:10
Enter the Choice:1
Enter no 2:54
Enter the Choice:1
Enter no 3:98
Enter the Choice:1
Enter no 4:234
Enter the Choice:3
Queue Elements are:10
54
98
234
Enter the Choice:2
Deleted Element is 10
Enter the Choice:3
Queue Elements are:
54
98
234
Enter the Choice:4

ii.Pointers

#include<stdio.h>
#include<stdlib.h>
#define max 10
int insertq ( int queue[max], int *rear , int *data)
{
if ( *rear == max -1 )
return(-1);
else
{
*rear = *rear + 1;
queue[*rear] = *data;
return(1);
}
}
int delq( int queue[max], int *front, int *rear , int *data)
{
if ( *front == *rear)
return(-1);
else
{
(*front)++;
*data = queue[*front];
return(1);
}
}
int main()
{
int queue[max],data;
int front,rear,reply,option;
//... init queue
front = rear = -1;
printf("\tMenu");
printf("\n----------------------------");
printf("\n 1. Insert element in queue");
printf("\n 2. Delete element from queue");
printf("\n 3. Exit");
printf("\n----------------------------");
while(1)
{
printf("\nChoose operation : ");
scanf("%d",&option);
switch(option)
{
case1 ://insert
printf("\nEnter Number : ");
scanf("%d",&data);
reply = insertq(queue,&rear,&data);
if ( reply == - 1)
printf("Queue is full");
else
printf("%d is inserted in queue.\n",data);
break;
case2 : //dele
reply = delq(queue,&front,&rear,&data);
if ( reply == -1 )
printf("Queue is empty ");
else
printf("\nDeleted number is : %d\n", data);
break;
case3 : exit(0);
}
}
}

OUTPUT
Menu
----------------------------
1. Insert element in queue
2. Delete element from queue
3. Exit
----------------------------
Choose operation : 1
Enter Number : 2
2 is inserted in queue.
Choose operation : 1
Enter Number : 34
34 is inserted in queue.
Choose operation : 2
Deleted number is : 2
Choose operation : 3

6. Write a program that implements the following sorting methods to sort a


given list of integers in ascending order
i) Quick sort ii) Heap sort iii) Merge sort
#include <stdio.h>
/ Function to swap two elements
void swap(int* a, int* b) {
int t = *a;
*a = *b;
*b = t;
}
int partition(int arr[], int low, int high) {
int pivot = arr[high];
int i = (low - 1);

for (int j = low; j <= high - 1; j++) {


if (arr[j] < pivot) {
i++;
swap(&arr[i], &arr[j]);
}
}
swap(&arr[i + 1], &arr[high]);
return (i + 1);
}
void quickSort(int arr[], int low, int high) {
if (low < high) {
int pi = partition(arr, low, high);
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}

// Function to print the array


void printArray(int arr[], int size) {
int i;
for (i = 0; i < size; i++)
printf("%d ", arr[i]);
printf("\n");
}

int main() {
int arr[] = { 12, 17, 6, 25, 1, 5 };
int n = sizeof(arr) / sizeof(arr[0]);
quickSort(arr, 0, n - 1);
printf("Sorted array: \n");
printArray(arr, n);
return 0;
}

Output:
Sorted array:
1 5 6 12 17 25

ii) Heap sort


#include <stdio.h>
void main()
{
int heap[10], num, i, j, c, rootElement, tempVar;
printf("\n Enter num of elements :");
scanf("%d", &num);
printf("\n Enter the nums : ");
for (i = 0; i < num; i++)
scanf("%d", &heap[i]);
for (i = 1; i < num; i++)
{
c = i;
do
{
rootElement = (c - 1) / 2;
if (heap[rootElement] < heap[c]) /* to create MAX heap
array */
{
tempVar = heap[rootElement];
heap[rootElement] = heap[c];
heap[c] = tempVar;
}
c = rootElement;
} while (c != 0);
}
printf("Heap array : ");
for (i = 0; i < num; i++)
printf("%d\t ", heap[i]);
for (j = num - 1; j >= 0; j--)
{
tempVar = heap[0];
heap[0] = heap[j];
heap[j] = tempVar;
rootElement = 0;
do
{
c = 2 * rootElement + 1;
if ((heap[c] < heap[c + 1]) && c < j-1)
c++;
if (heap[rootElement]<heap[c] && c<j) {
tempVar = heap[rootElement];
heap[rootElement] = heap[c];
heap[c] = tempVar;
}
rootElement = c;
} while (c < j);
}
printf("\n The sorted array is : ");
for (i = 0; i < num; i++)
printf("\t %d", heap[i]);
}
Enter num of elements :5
Enter the nums : 3
9
4
5
8
Heap array : 9 8 4 3 5
The sorted array is : 3 4 5 8

iii)Merge sort
#include <stdio.h>
#include <stdlib.h>

// merge function
void Merge(int arr[], int left, int mid, int right)
{
int i, j, k;
int size1 = mid - left + 1;
int size2 = right - mid;

// created temporary array


int Left[size1], Right[size2];

// copying the data from arr to temporary array


for (i = 0; i < size1; i++)
Left[i] = arr[left + i];

for (j = 0; j < size2; j++)


Right[j] = arr[mid + 1 + j];

// merging of the array


i = 0; // intital index of first subarray
j = 0; // inital index of second subarray
k = left; // initial index of parent array
while (i < size1 && j < size2)
{
if (Left[i] <= Right[j])
{
arr[k] = Left[i];
i++;
}
else
{
arr[k] = Right[j];
j++;
}
k++;
}
// copying the elements from Left[], if any
while (i < size1)
{
arr[k] = Left[i];
i++;
k++;
}

// copying the elements from Right[], if any


while (j < size2)
{
arr[k] = Right[j];
j++;
k++;
}
}

//merge sort function


void Merge_Sort(int arr[], int left, int right)
{
if (left < right)
{
int mid = left + (right - left) / 2;

// recursive calling of merge_sort


Merge_Sort(arr, left, mid);
Merge_Sort(arr, mid + 1, right);

Merge(arr, left, mid, right);


}
}

// driver code
int main()
{
int size;
printf("Enter the size: ");
scanf("%d", &size);

int arr[size];
printf("Enter the elements of array: ");
for (int i = 0; i < size; i++)
{
scanf("%d", &arr[i]);
}
Merge_Sort(arr, 0, size - 1);

printf("The sorted array is: ");


for (int i = 0; i < size; i++)
{
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
7.write a program to implement the tree traversal methods
#include <stdio.h>

#include <stdlib.h>

struct node {

int data;

struct node *leftChild;

struct node *rightChild;

};

struct node *root = NULL;

void insert(int data) {

struct node *tempNode = (struct node*) malloc(sizeof(struct node));

struct node *current;

struct node *parent;

tempNode->data = data;

tempNode->leftChild = NULL;

tempNode->rightChild = NULL;
//if tree is empty

if(root == NULL) {

root = tempNode;

} else {

current = root;

parent = NULL;

while(1)

parent = current;

//go to left of the tree

if(data < parent->data) {

current = current->leftChild;

//insert to the left

if(current == NULL) {

parent->leftChild = tempNode;

return;

} //go to right of the tree

else {

current = current->rightChild;

//insert to the right

if(current == NULL) {

parent->rightChild = tempNode;

return;

}
}

struct node* search(int data) {

struct node *current = root;

printf("Visiting elements: ");

while(current->data != data) {

if(current != NULL)

printf("%d ",current->data);

//go to left tree

if(current->data > data) {

current = current->leftChild;

//else go to right tree

else {

current = current->rightChild;

//not found

if(current == NULL) {

return NULL;

return current;

void pre_order_traversal(struct node* root) {

if(root != NULL) {

printf("%d ",root->data);

pre_order_traversal(root->leftChild);

pre_order_traversal(root->rightChild);

}
}

void inorder_traversal(struct node* root) {

if(root != NULL) {

inorder_traversal(root->leftChild);

printf("%d ",root->data);

inorder_traversal(root->rightChild);

void post_order_traversal(struct node* root) {

if(root != NULL) {

post_order_traversal(root->leftChild);

post_order_traversal(root->rightChild);

printf("%d ", root->data);

int main() {

int i;

int array[7] = { 27, 14, 35, 10, 19, 31, 42 };

for(i = 0; i < 7; i++)

insert(array[i]);

i = 31;

struct node * temp = search(i);

if(temp != NULL) {

printf("[%d] Element found.", temp->data);

printf("\n");

}else {

printf("[ x ] Element not found (%d).\n", i);

}
i = 15;

temp = search(i);

if(temp != NULL) {

printf("[%d] Element found.", temp->data);

printf("\n");

}else {

printf("[ x ] Element not found (%d).\n", i);

printf("\nPreorder traversal: ");

pre_order_traversal(root);

printf("\nInorder traversal: ");

inorder_traversal(root);

printf("\nPost order traversal: ");

post_order_traversal(root);

return 0;

Output

Visiting elements: 27 35 [31] Element found.

Visiting elements: 27 14 19 [ x ] Element not found (15).

Preorder traversal: 27 14 10 19 35 31 42

Inorder traversal: 10 14 19 27 31 35 42

Post order traversal: 10 19 14 31 42 35 27

Write a program to implement


(i)Binary Search tree ii) B Trees iii) B+ Trees iv)AVL trees v) Red - Black
trees
(i)Binary Search tree
#include <stdio.h>

#include <stdlib.h>
struct btnode

int value;

struct btnode *l;

struct btnode *r;

}*root = NULL, *temp = NULL, *t2, *t1;

void delete1();

void insert();

void delete();

void inorder(struct btnode *t);

void create();

void search(struct btnode *t);

void preorder(struct btnode *t);

void postorder(struct btnode *t);

void search1(struct btnode *t,int data);

int smallest(struct btnode *t);

int largest(struct btnode *t);

int flag = 1;

void main()

int ch;

printf("\nOPERATIONS ---");

printf("\n1 - Insert an element into tree\n");


printf("2 - Delete an element from the tree\n");

printf("3 - Inorder Traversal\n");

printf("4 - Preorder Traversal\n");

printf("5 - Postorder Traversal\n");

printf("6 - Exit\n");

while(1)

printf("\nEnter your choice : ");

scanf("%d", &ch);

switch (ch)

case 1:

insert();

break;

case 2:

delete();

break;

case 3:

inorder(root);

break;

case 4:

preorder(root);

break;

case 5:

postorder(root);

break;

case 6:

exit(0);
default :

printf("Wrong choice, Please enter correct choice ");

break;

/* To insert a node in the tree */

void insert()

create();

if (root == NULL)

root = temp;

else

search(root);

/* To create a node */

void create()

int data;

printf("Enter data of node to be inserted : ");

scanf("%d", &data);

temp = (struct btnode *)malloc(1*sizeof(struct btnode));

temp->value = data;

temp->l = temp->r = NULL;

}
/* Function to search the appropriate position to insert the new node */

void search(struct btnode *t)

if ((temp->value > t->value) && (t->r != NULL)) /* value more than root node value insert at right */

search(t->r);

else if ((temp->value > t->value) && (t->r == NULL))

t->r = temp;

else if ((temp->value < t->value) && (t->l != NULL)) /* value less than root node value insert at left */

search(t->l);

else if ((temp->value < t->value) && (t->l == NULL))

t->l = temp;

/* recursive function to perform inorder traversal of tree */

void inorder(struct btnode *t)

if (root == NULL)

printf("No elements in a tree to display");

return;

if (t->l != NULL)

inorder(t->l);

printf("%d -> ", t->value);

if (t->r != NULL)

inorder(t->r);

}
/* To check for the deleted node */

void delete()

int data;

if (root == NULL)

printf("No elements in a tree to delete");

return;

printf("Enter the data to be deleted : ");

scanf("%d", &data);

t1 = root;

t2 = root;

search1(root, data);

/* To find the preorder traversal */

void preorder(struct btnode *t)

if (root == NULL)

printf("No elements in a tree to display");

return;

printf("%d -> ", t->value);

if (t->l != NULL)
preorder(t->l);

if (t->r != NULL)

preorder(t->r);

/* To find the postorder traversal */

void postorder(struct btnode *t)

if (root == NULL)

printf("No elements in a tree to display ");

return;

if (t->l != NULL)

postorder(t->l);

if (t->r != NULL)

postorder(t->r);

printf("%d -> ", t->value);

/* Search for the appropriate position to insert the new node */

void search1(struct btnode *t, int data)

if ((data>t->value))

t1 = t;

search1(t->r, data);

}
else if ((data < t->value))

t1 = t;

search1(t->l, data);

else if ((data==t->value))

delete1(t);

/* To delete a node */

void delete1(struct btnode *t)

int k;

/* To delete leaf node */

if ((t->l == NULL) && (t->r == NULL))

if (t1->l == t)

t1->l = NULL;

else

t1->r = NULL;

t = NULL;
free(t);

return;

/* To delete node having one left hand child */

else if ((t->r == NULL))

if (t1 == t)

root = t->l;

t1 = root;

else if (t1->l == t)

t1->l = t->l;

else

t1->r = t->l;

t = NULL;

free(t);

return;

/* To delete node having right hand child */

else if (t->l == NULL)


{

if (t1 == t)

root = t->r;

t1 = root;

else if (t1->r == t)

t1->r = t->r;

else

t1->l = t->r;

t == NULL;

free(t);

return;

/* To delete node having two child */

else if ((t->l != NULL) && (t->r != NULL))

t2 = root;

if (t->r != NULL)

k = smallest(t->r);

flag = 1;

else

k =largest(t->l);

flag = 2;
}

search1(root, k);

t->value = k;

/* To find the smallest element in the right sub tree */

int smallest(struct btnode *t)

t2 = t;

if (t->l != NULL)

t2 = t;

return(smallest(t->l));

else

return (t->value);

/* To find the largest element in the left sub tree */

int largest(struct btnode *t)

if (t->r != NULL)

t2 = t;

return(largest(t->r));

}
else

return(t->value);

$ cc tree43.c

$ a.out

OPERATIONS ---

1 - Insert an element into tree

2 - Delete an element from the tree

3 - Inorder Traversal

4 - Preorder Traversal

5 - Postorder Traversal

6 - Exit

Enter your choice : 1

Enter data of node to be inserted : 40

Enter your choice : 1

Enter data of node to be inserted : 20

Enter your choice : 1

Enter data of node to be inserted : 10

Enter your choice : 1

Enter data of node to be inserted : 30

Enter your choice : 1

Enter data of node to be inserted : 60


Enter your choice : 1

Enter data of node to be inserted : 80

Enter your choice : 1

Enter data of node to be inserted : 90

Enter your choice : 3

10 -> 20 -> 30 -> 40 -> 60 -> 80 -> 90 ->

40

/\

/ \

20 60

/\ \

10 30 80

90

ii)B Trees
// Searching a key on a B-tree in C

#include <stdio.h>
#include <stdlib.h>

#define MAX 3
#define MIN 2
struct BTreeNode {
int val[MAX + 1], count;
struct BTreeNode *link[MAX + 1];
};

struct BTreeNode *root;

// Create a node
struct BTreeNode *createNode(int val, struct BTreeNode *child) {
struct BTreeNode *newNode;
newNode = (struct BTreeNode *)malloc(sizeof(struct BTreeNode));
newNode->val[1] = val;
newNode->count = 1;
newNode->link[0] = root;
newNode->link[1] = child;
return newNode;
}

// Insert node
void insertNode(int val, int pos, struct BTreeNode *node,
struct BTreeNode *child) {
int j = node->count;
while (j > pos) {
node->val[j + 1] = node->val[j];
node->link[j + 1] = node->link[j];
j--;
}
node->val[j + 1] = val;
node->link[j + 1] = child;
node->count++;
}

// Split node
void splitNode(int val, int *pval, int pos, struct BTreeNode *node,
struct BTreeNode *child, struct BTreeNode **newNode) {
int median, j;

if (pos > MIN)


median = MIN + 1;
else
median = MIN;

*newNode = (struct BTreeNode *)malloc(sizeof(struct BTreeNode));


j = median + 1;
while (j <= MAX) {
(*newNode)->val[j - median] = node->val[j];
(*newNode)->link[j - median] = node->link[j];
j++;
}
node->count = median;
(*newNode)->count = MAX - median;

if (pos <= MIN) {


insertNode(val, pos, node, child);
} else {
insertNode(val, pos - median, *newNode, child);
}
*pval = node->val[node->count];
(*newNode)->link[0] = node->link[node->count];
node->count--;
}

// Set the value


int setValue(int val, int *pval,
struct BTreeNode *node, struct BTreeNode **child) {
int pos;
if (!node) {
*pval = val;
*child = NULL;
return 1;
}
if (val < node->val[1]) {
pos = 0;
} else {
for (pos = node->count;
(val < node->val[pos] && pos > 1); pos--)
;
if (val == node->val[pos]) {
printf("Duplicates are not permitted\n");
return 0;
}
}
if (setValue(val, pval, node->link[pos], child)) {
if (node->count < MAX) {
insertNode(*pval, pos, node, *child);
} else {
splitNode(*pval, pval, pos, node, *child, child);
return 1;
}
}
return 0;
}

// Insert the value


void insert(int val) {
int flag, i;
struct BTreeNode *child;

flag = setValue(val, &i, root, &child);


if (flag)
root = createNode(i, child);
}

// Search node
void search(int val, int *pos, struct BTreeNode *myNode) {
if (!myNode) {
return;
}

if (val < myNode->val[1]) {


*pos = 0;
} else {
for (*pos = myNode->count;
(val < myNode->val[*pos] && *pos > 1); (*pos)--)
;
if (val == myNode->val[*pos]) {
printf("%d is found", val);
return;
}
}
search(val, pos, myNode->link[*pos]);

return;
}

// Traverse then nodes


void traversal(struct BTreeNode *myNode) {
int i;
if (myNode) {
for (i = 0; i < myNode->count; i++) {
traversal(myNode->link[i]);
printf("%d ", myNode->val[i + 1]);
}
traversal(myNode->link[i]);
}
}

int main() {
int val, ch;

insert(8);
insert(9);
insert(10);
insert(11);
insert(15);
insert(16);
insert(17);
insert(18);
insert(20);
insert(23);

traversal(root);

printf("\n");
search(11, &ch, root);
}
Output:
8 9 10 11 15 16 17 18 20 23
11 is found
ii)B+tree
// Searching on a B+ Tree in C

#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// Default order
#define ORDER 3

typedef struct record {


int value;
} record;

// Node
typedef struct node {
void **pointers;
int *keys;
struct node *parent;
bool is_leaf;
int num_keys;
struct node *next;
} node;

int order = ORDER;


node *queue = NULL;
bool verbose_output = false;

// Enqueue
void enqueue(node *new_node);
// Dequeue
node *dequeue(void);
int height(node *const root);
int pathToLeaves(node *const root, node *child);
void printLeaves(node *const root);
void printTree(node *const root);
void findAndPrint(node *const root, int key, bool verbose);
void findAndPrintRange(node *const root, int range1, int range2, bool verbose);
int findRange(node *const root, int key_start, int key_end, bool verbose,
int returned_keys[], void *returned_pointers[]);
node *findLeaf(node *const root, int key, bool verbose);
record *find(node *root, int key, bool verbose, node **leaf_out);
int cut(int length);

record *makeRecord(int value);


node *makeNode(void);
node *makeLeaf(void);
int getLeftIndex(node *parent, node *left);
node *insertIntoLeaf(node *leaf, int key, record *pointer);
node *insertIntoLeafAfterSplitting(node *root, node *leaf, int key,
record *pointer);
node *insertIntoNode(node *root, node *parent,
int left_index, int key, node *right);
node *insertIntoNodeAfterSplitting(node *root, node *parent,
int left_index,
int key, node *right);
node *insertIntoParent(node *root, node *left, int key, node *right);
node *insertIntoNewRoot(node *left, int key, node *right);
node *startNewTree(int key, record *pointer);
node *insert(node *root, int key, int value);

// Enqueue
void enqueue(node *new_node) {
node *c;
if (queue == NULL) {
queue = new_node;
queue->next = NULL;
} else {
c = queue;
while (c->next != NULL) {
c = c->next;
}
c->next = new_node;
new_node->next = NULL;
}
}

// Dequeue
node *dequeue(void) {
node *n = queue;
queue = queue->next;
n->next = NULL;
return n;
}

// Print the leaves


void printLeaves(node *const root) {
if (root == NULL) {
printf("Empty tree.\n");
return;
}
int i;
node *c = root;
while (!c->is_leaf)
c = c->pointers[0];
while (true) {
for (i = 0; i < c->num_keys; i++) {
if (verbose_output)
printf("%p ", c->pointers[i]);
printf("%d ", c->keys[i]);
}
if (verbose_output)
printf("%p ", c->pointers[order - 1]);
if (c->pointers[order - 1] != NULL) {
printf(" | ");
c = c->pointers[order - 1];
} else
break;
}
printf("\n");
}

// Calculate height
int height(node *const root) {
int h = 0;
node *c = root;
while (!c->is_leaf) {
c = c->pointers[0];
h++;
}
return h;
}

// Get path to root


int pathToLeaves(node *const root, node *child) {
int length = 0;
node *c = child;
while (c != root) {
c = c->parent;
length++;
}
return length;
}

// Print the tree


void printTree(node *const root) {
node *n = NULL;
int i = 0;
int rank = 0;
int new_rank = 0;

if (root == NULL) {
printf("Empty tree.\n");
return;
}
queue = NULL;
enqueue(root);
while (queue != NULL) {
n = dequeue();
if (n->parent != NULL && n == n->parent->pointers[0]) {
new_rank = pathToLeaves(root, n);
if (new_rank != rank) {
rank = new_rank;
printf("\n");
}
}
if (verbose_output)
printf("(%p)", n);
for (i = 0; i < n->num_keys; i++) {
if (verbose_output)
printf("%p ", n->pointers[i]);
printf("%d ", n->keys[i]);
}
if (!n->is_leaf)
for (i = 0; i <= n->num_keys; i++)
enqueue(n->pointers[i]);
if (verbose_output) {
if (n->is_leaf)
printf("%p ", n->pointers[order - 1]);
else
printf("%p ", n->pointers[n->num_keys]);
}
printf("| ");
}
printf("\n");
}

// Find the node and print it


void findAndPrint(node *const root, int key, bool verbose) {
node *leaf = NULL;
record *r = find(root, key, verbose, NULL);
if (r == NULL)
printf("Record not found under key %d.\n", key);
else
printf("Record at %p -- key %d, value %d.\n",
r, key, r->value);
}

// Find and print the range


void findAndPrintRange(node *const root, int key_start, int key_end,
bool verbose) {
int i;
int array_size = key_end - key_start + 1;
int returned_keys[array_size];
void *returned_pointers[array_size];
int num_found = findRange(root, key_start, key_end, verbose,
returned_keys, returned_pointers);
if (!num_found)
printf("None found.\n");
else {
for (i = 0; i < num_found; i++)
printf("Key: %d Location: %p Value: %d\n",
returned_keys[i],
returned_pointers[i],
((record *)
returned_pointers[i])
->value);
}
}

// Find the range


int findRange(node *const root, int key_start, int key_end, bool verbose,
int returned_keys[], void *returned_pointers[]) {
int i, num_found;
num_found = 0;
node *n = findLeaf(root, key_start, verbose);
if (n == NULL)
return 0;
for (i = 0; i < n->num_keys && n->keys[i] < key_start; i++)
;
if (i == n->num_keys)
return 0;
while (n != NULL) {
for (; i < n->num_keys && n->keys[i] <= key_end; i++) {
returned_keys[num_found] = n->keys[i];
returned_pointers[num_found] = n->pointers[i];
num_found++;
}
n = n->pointers[order - 1];
i = 0;
}
return num_found;
}

// Find the leaf


node *findLeaf(node *const root, int key, bool verbose) {
if (root == NULL) {
if (verbose)
printf("Empty tree.\n");
return root;
}
int i = 0;
node *c = root;
while (!c->is_leaf) {
if (verbose) {
printf("[");
for (i = 0; i < c->num_keys - 1; i++)
printf("%d ", c->keys[i]);
printf("%d] ", c->keys[i]);
}
i = 0;
while (i < c->num_keys) {
if (key >= c->keys[i])
i++;
else
break;
}
if (verbose)
printf("%d ->\n", i);
c = (node *)c->pointers[i];
}
if (verbose) {
printf("Leaf [");
for (i = 0; i < c->num_keys - 1; i++)
printf("%d ", c->keys[i]);
printf("%d] ->\n", c->keys[i]);
}
return c;
}
record *find(node *root, int key, bool verbose, node **leaf_out) {
if (root == NULL) {
if (leaf_out != NULL) {
*leaf_out = NULL;
}
return NULL;
}

int i = 0;
node *leaf = NULL;

leaf = findLeaf(root, key, verbose);

for (i = 0; i < leaf->num_keys; i++)


if (leaf->keys[i] == key)
break;
if (leaf_out != NULL) {
*leaf_out = leaf;
}
if (i == leaf->num_keys)
return NULL;
else
return (record *)leaf->pointers[i];
}
int cut(int length) {
if (length % 2 == 0)
return length / 2;
else
return length / 2 + 1;
}

record *makeRecord(int value) {


record *new_record = (record *)malloc(sizeof(record));
if (new_record == NULL) {
perror("Record creation.");
exit(EXIT_FAILURE);
} else {
new_record->value = value;
}
return new_record;
}

node *makeNode(void) {
node *new_node;
new_node = malloc(sizeof(node));
if (new_node == NULL) {
perror("Node creation.");
exit(EXIT_FAILURE);
}
new_node->keys = malloc((order - 1) * sizeof(int));
if (new_node->keys == NULL) {
perror("New node keys array.");
exit(EXIT_FAILURE);
}
new_node->pointers = malloc(order * sizeof(void *));
if (new_node->pointers == NULL) {
perror("New node pointers array.");
exit(EXIT_FAILURE);
}
new_node->is_leaf = false;
new_node->num_keys = 0;
new_node->parent = NULL;
new_node->next = NULL;
return new_node;
}

node *makeLeaf(void) {
node *leaf = makeNode();
leaf->is_leaf = true;
return leaf;
}
int getLeftIndex(node *parent, node *left) {
int left_index = 0;
while (left_index <= parent->num_keys &&
parent->pointers[left_index] != left)
left_index++;
return left_index;
}

node *insertIntoLeaf(node *leaf, int key, record *pointer) {


int i, insertion_point;

insertion_point = 0;
while (insertion_point < leaf->num_keys && leaf->keys[insertion_point] < key)
insertion_point++;

for (i = leaf->num_keys; i > insertion_point; i--) {


leaf->keys[i] = leaf->keys[i - 1];
leaf->pointers[i] = leaf->pointers[i - 1];
}
leaf->keys[insertion_point] = key;
leaf->pointers[insertion_point] = pointer;
leaf->num_keys++;
return leaf;
}

node *insertIntoLeafAfterSplitting(node *root, node *leaf, int key, record *pointer) {


node *new_leaf;
int *temp_keys;
void **temp_pointers;
int insertion_index, split, new_key, i, j;

new_leaf = makeLeaf();

temp_keys = malloc(order * sizeof(int));


if (temp_keys == NULL) {
perror("Temporary keys array.");
exit(EXIT_FAILURE);
}

temp_pointers = malloc(order * sizeof(void *));


if (temp_pointers == NULL) {
perror("Temporary pointers array.");
exit(EXIT_FAILURE);
}

insertion_index = 0;
while (insertion_index < order - 1 && leaf->keys[insertion_index] < key)
insertion_index++;

for (i = 0, j = 0; i < leaf->num_keys; i++, j++) {


if (j == insertion_index)
j++;
temp_keys[j] = leaf->keys[i];
temp_pointers[j] = leaf->pointers[i];
}

temp_keys[insertion_index] = key;
temp_pointers[insertion_index] = pointer;

leaf->num_keys = 0;

split = cut(order - 1);

for (i = 0; i < split; i++) {


leaf->pointers[i] = temp_pointers[i];
leaf->keys[i] = temp_keys[i];
leaf->num_keys++;
}

for (i = split, j = 0; i < order; i++, j++) {


new_leaf->pointers[j] = temp_pointers[i];
new_leaf->keys[j] = temp_keys[i];
new_leaf->num_keys++;
}

free(temp_pointers);
free(temp_keys);

new_leaf->pointers[order - 1] = leaf->pointers[order - 1];


leaf->pointers[order - 1] = new_leaf;

for (i = leaf->num_keys; i < order - 1; i++)


leaf->pointers[i] = NULL;
for (i = new_leaf->num_keys; i < order - 1; i++)
new_leaf->pointers[i] = NULL;

new_leaf->parent = leaf->parent;
new_key = new_leaf->keys[0];

return insertIntoParent(root, leaf, new_key, new_leaf);


}

node *insertIntoNode(node *root, node *n,


int left_index, int key, node *right) {
int i;
for (i = n->num_keys; i > left_index; i--) {
n->pointers[i + 1] = n->pointers[i];
n->keys[i] = n->keys[i - 1];
}
n->pointers[left_index + 1] = right;
n->keys[left_index] = key;
n->num_keys++;
return root;
}

node *insertIntoNodeAfterSplitting(node *root, node *old_node, int left_index,


int key, node *right) {
int i, j, split, k_prime;
node *new_node, *child;
int *temp_keys;
node **temp_pointers;

temp_pointers = malloc((order + 1) * sizeof(node *));


if (temp_pointers == NULL) {
exit(EXIT_FAILURE);
}
temp_keys = malloc(order * sizeof(int));
if (temp_keys == NULL) {
exit(EXIT_FAILURE);
}

for (i = 0, j = 0; i < old_node->num_keys + 1; i++, j++) {


if (j == left_index + 1)
j++;
temp_pointers[j] = old_node->pointers[i];
}

for (i = 0, j = 0; i < old_node->num_keys; i++, j++) {


if (j == left_index)
j++;
temp_keys[j] = old_node->keys[i];
}

temp_pointers[left_index + 1] = right;
temp_keys[left_index] = key;

split = cut(order);
new_node = makeNode();
old_node->num_keys = 0;
for (i = 0; i < split - 1; i++) {
old_node->pointers[i] = temp_pointers[i];
old_node->keys[i] = temp_keys[i];
old_node->num_keys++;
}
old_node->pointers[i] = temp_pointers[i];
k_prime = temp_keys[split - 1];
for (++i, j = 0; i < order; i++, j++) {
new_node->pointers[j] = temp_pointers[i];
new_node->keys[j] = temp_keys[i];
new_node->num_keys++;
}
new_node->pointers[j] = temp_pointers[i];
free(temp_pointers);
free(temp_keys);
new_node->parent = old_node->parent;
for (i = 0; i <= new_node->num_keys; i++) {
child = new_node->pointers[i];
child->parent = new_node;
}

return insertIntoParent(root, old_node, k_prime, new_node);


}

node *insertIntoParent(node *root, node *left, int key, node *right) {


int left_index;
node *parent;
parent = left->parent;

if (parent == NULL)
return insertIntoNewRoot(left, key, right);

left_index = getLeftIndex(parent, left);

if (parent->num_keys < order - 1)


return insertIntoNode(root, parent, left_index, key, right);

return insertIntoNodeAfterSplitting(root, parent, left_index, key, right);


}

node *insertIntoNewRoot(node *left, int key, node *right) {


node *root = makeNode();
root->keys[0] = key;
root->pointers[0] = left;
root->pointers[1] = right;
root->num_keys++;
root->parent = NULL;
left->parent = root;
right->parent = root;
return root;
}

node *startNewTree(int key, record *pointer) {


node *root = makeLeaf();
root->keys[0] = key;
root->pointers[0] = pointer;
root->pointers[order - 1] = NULL;
root->parent = NULL;
root->num_keys++;
return root;
}

node *insert(node *root, int key, int value) {


record *record_pointer = NULL;
node *leaf = NULL;

record_pointer = find(root, key, false, NULL);


if (record_pointer != NULL) {
record_pointer->value = value;
return root;
}

record_pointer = makeRecord(value);
if (root == NULL)
return startNewTree(key, record_pointer);

leaf = findLeaf(root, key, false);

if (leaf->num_keys < order - 1) {


leaf = insertIntoLeaf(leaf, key, record_pointer);
return root;
}

return insertIntoLeafAfterSplitting(root, leaf, key, record_pointer);


}

int main() {
node *root;
char instruction;

root = NULL;

root = insert(root, 5, 33);


root = insert(root, 15, 21);
root = insert(root, 25, 31);
root = insert(root, 35, 41);
root = insert(root, 45, 10);
printTree(root);

findAndPrint(root, 15, instruction = 'a');


}
Output:
25 |
15 | 35 |
5 | 15 | 25 | 35 45 |
[25] 0 ->
[15] 1 ->
Leaf [15] ->
Record at 0x7da330 -- key 15, value 21
iii)AVL TREE
#include <stdio.h>
#include <stdlib.h>

struct Node
{
int key;
struct Node *left;
struct Node *right;
int height;
};
int getHeight(struct Node *n){
if(n==NULL)
return 0;
return n->height;
}

struct Node *createNode(int key){


struct Node* node = (struct Node *) malloc(sizeof(struct Node));
node->key = key;
node->left = NULL;
node->right = NULL;
node->height = 1;
return node;
}

int max (int a, int b){


return (a>b)?a:b;
}

int getBalanceFactor(struct Node * n){


if(n==NULL){
return 0;
}
return getHeight(n->left) - getHeight(n->right);
}

struct Node* rightRotate(struct Node* y){


struct Node* x = y->left;
struct Node* T2 = x->right;

x->right = y;
y->left = T2;

x->height = max(getHeight(x->right), getHeight(x->left)) + 1;


y->height = max(getHeight(y->right), getHeight(y->left)) + 1;

return x;
}

struct Node* leftRotate(struct Node* x){


struct Node* y = x->right;
struct Node* T2 = y->left;

y->left = x;
x->right = T2;

x->height = max(getHeight(x->right), getHeight(x->left)) + 1;


y->height = max(getHeight(y->right), getHeight(y->left)) + 1;
return y;
}

struct Node *insert(struct Node* node, int key){


if (node == NULL)
return createNode(key);

if (key < node->key)


node->left = insert(node->left, key);
else if (key > node->key)
node->right = insert(node->right, key);

node->height = 1 + max(getHeight(node->left), getHeight(node->right));


int bf = getBalanceFactor(node);

// Left Left Case


if(bf>1 && key < node->left->key){
return rightRotate(node);
}
// Right Right Case
if(bf<-1 && key > node->right->key){
return leftRotate(node);
}
// Left Right Case
if(bf>1 && key > node->left->key){
node->left = leftRotate(node->left);
return rightRotate(node);
}
// Right Left Case
if(bf<-1 && key < node->right->key){
node->right = rightRotate(node->right);
return leftRotate(node);
}
return node;
}

void preOrder(struct Node *root)


{
if(root != NULL)
{
printf("%d ", root->key);
preOrder(root->left);
preOrder(root->right);
}
}

int main(){
struct Node * root = NULL;

root = insert(root, 1);


root = insert(root, 2);
root = insert(root, 4);
root = insert(root, 5);
root = insert(root, 6);
root = insert(root, 3);
preOrder(root);
return 0;
}
Output: 4 2 1 3 5 6
iv) RED BLACK TREE
// Implementing Red-Black Tree in C

#include <stdio.h>
#include <stdlib.h>

enum nodeColor {
RED,
BLACK
};
struct rbNode {
int data, color;
struct rbNode *link[2];
};

struct rbNode *root = NULL;

// Create a red-black tree


struct rbNode *createNode(int data) {
struct rbNode *newnode;
newnode = (struct rbNode *)malloc(sizeof(struct rbNode));
newnode->data = data;
newnode->color = RED;
newnode->link[0] = newnode->link[1] = NULL;
return newnode;
}

// Insert an node
void insertion(int data) {
struct rbNode *stack[98], *ptr, *newnode, *xPtr, *yPtr;
int dir[98], ht = 0, index;
ptr = root;
if (!root) {
root = createNode(data);
return;
}

stack[ht] = root;
dir[ht++] = 0;
while (ptr != NULL) {
if (ptr->data == data) {
printf("Duplicates Not Allowed!!\n");
return;
}
index = (data - ptr->data) > 0 ? 1 : 0;
stack[ht] = ptr;
ptr = ptr->link[index];
dir[ht++] = index;
}
stack[ht - 1]->link[index] = newnode = createNode(data);
while ((ht >= 3) && (stack[ht - 1]->color == RED)) {
if (dir[ht - 2] == 0) {
yPtr = stack[ht - 2]->link[1];
if (yPtr != NULL && yPtr->color == RED) {
stack[ht - 2]->color = RED;
stack[ht - 1]->color = yPtr->color = BLACK;
ht = ht - 2;
} else {
if (dir[ht - 1] == 0) {
yPtr = stack[ht - 1];
} else {
xPtr = stack[ht - 1];
yPtr = xPtr->link[1];
xPtr->link[1] = yPtr->link[0];
yPtr->link[0] = xPtr;
stack[ht - 2]->link[0] = yPtr;
}
xPtr = stack[ht - 2];
xPtr->color = RED;
yPtr->color = BLACK;
xPtr->link[0] = yPtr->link[1];
yPtr->link[1] = xPtr;
if (xPtr == root) {
root = yPtr;
} else {
stack[ht - 3]->link[dir[ht - 3]] = yPtr;
}
break;
}
} else {
yPtr = stack[ht - 2]->link[0];
if ((yPtr != NULL) && (yPtr->color == RED)) {
stack[ht - 2]->color = RED;
stack[ht - 1]->color = yPtr->color = BLACK;
ht = ht - 2;
} else {
if (dir[ht - 1] == 1) {
yPtr = stack[ht - 1];
} else {
xPtr = stack[ht - 1];
yPtr = xPtr->link[0];
xPtr->link[0] = yPtr->link[1];
yPtr->link[1] = xPtr;
stack[ht - 2]->link[1] = yPtr;
}
xPtr = stack[ht - 2];
yPtr->color = BLACK;
xPtr->color = RED;
xPtr->link[1] = yPtr->link[0];
yPtr->link[0] = xPtr;
if (xPtr == root) {
root = yPtr;
} else {
stack[ht - 3]->link[dir[ht - 3]] = yPtr;
}
break;
}
}
}
root->color = BLACK;
}

// Delete a node
void deletion(int data) {
struct rbNode *stack[98], *ptr, *xPtr, *yPtr;
struct rbNode *pPtr, *qPtr, *rPtr;
int dir[98], ht = 0, diff, i;
enum nodeColor color;

if (!root) {
printf("Tree not available\n");
return;
}

ptr = root;
while (ptr != NULL) {
if ((data - ptr->data) == 0)
break;
diff = (data - ptr->data) > 0 ? 1 : 0;
stack[ht] = ptr;
dir[ht++] = diff;
ptr = ptr->link[diff];
}

if (ptr->link[1] == NULL) {
if ((ptr == root) && (ptr->link[0] == NULL)) {
free(ptr);
root = NULL;
} else if (ptr == root) {
root = ptr->link[0];
free(ptr);
} else {
stack[ht - 1]->link[dir[ht - 1]] = ptr->link[0];
}
} else {
xPtr = ptr->link[1];
if (xPtr->link[0] == NULL) {
xPtr->link[0] = ptr->link[0];
color = xPtr->color;
xPtr->color = ptr->color;
ptr->color = color;

if (ptr == root) {
root = xPtr;
} else {
stack[ht - 1]->link[dir[ht - 1]] = xPtr;
}

dir[ht] = 1;
stack[ht++] = xPtr;
} else {
i = ht++;
while (1) {
dir[ht] = 0;
stack[ht++] = xPtr;
yPtr = xPtr->link[0];
if (!yPtr->link[0])
break;
xPtr = yPtr;
}

dir[i] = 1;
stack[i] = yPtr;
if (i > 0)
stack[i - 1]->link[dir[i - 1]] = yPtr;

yPtr->link[0] = ptr->link[0];
xPtr->link[0] = yPtr->link[1];
yPtr->link[1] = ptr->link[1];

if (ptr == root) {
root = yPtr;
}

color = yPtr->color;
yPtr->color = ptr->color;
ptr->color = color;
}
}

if (ht < 1)
return;

if (ptr->color == BLACK) {
while (1) {
pPtr = stack[ht - 1]->link[dir[ht - 1]];
if (pPtr && pPtr->color == RED) {
pPtr->color = BLACK;
break;
}
if (ht < 2)
break;

if (dir[ht - 2] == 0) {
rPtr = stack[ht - 1]->link[1];

if (!rPtr)
break;

if (rPtr->color == RED) {
stack[ht - 1]->color = RED;
rPtr->color = BLACK;
stack[ht - 1]->link[1] = rPtr->link[0];
rPtr->link[0] = stack[ht - 1];

if (stack[ht - 1] == root) {
root = rPtr;
} else {
stack[ht - 2]->link[dir[ht - 2]] = rPtr;
}
dir[ht] = 0;
stack[ht] = stack[ht - 1];
stack[ht - 1] = rPtr;
ht++;
rPtr = stack[ht - 1]->link[1];
}

if ((!rPtr->link[0] || rPtr->link[0]->color == BLACK) &&


(!rPtr->link[1] || rPtr->link[1]->color == BLACK)) {
rPtr->color = RED;
} else {
if (!rPtr->link[1] || rPtr->link[1]->color == BLACK) {
qPtr = rPtr->link[0];
rPtr->color = RED;
qPtr->color = BLACK;
rPtr->link[0] = qPtr->link[1];
qPtr->link[1] = rPtr;
rPtr = stack[ht - 1]->link[1] = qPtr;
}
rPtr->color = stack[ht - 1]->color;
stack[ht - 1]->color = BLACK;
rPtr->link[1]->color = BLACK;
stack[ht - 1]->link[1] = rPtr->link[0];
rPtr->link[0] = stack[ht - 1];
if (stack[ht - 1] == root) {
root = rPtr;
} else {
stack[ht - 2]->link[dir[ht - 2]] = rPtr;
}
break;
}
} else {
rPtr = stack[ht - 1]->link[0];
if (!rPtr)
break;

if (rPtr->color == RED) {
stack[ht - 1]->color = RED;
rPtr->color = BLACK;
stack[ht - 1]->link[0] = rPtr->link[1];
rPtr->link[1] = stack[ht - 1];

if (stack[ht - 1] == root) {
root = rPtr;
} else {
stack[ht - 2]->link[dir[ht - 2]] = rPtr;
}
dir[ht] = 1;
stack[ht] = stack[ht - 1];
stack[ht - 1] = rPtr;
ht++;
rPtr = stack[ht - 1]->link[0];
}
if ((!rPtr->link[0] || rPtr->link[0]->color == BLACK) &&
(!rPtr->link[1] || rPtr->link[1]->color == BLACK)) {
rPtr->color = RED;
} else {
if (!rPtr->link[0] || rPtr->link[0]->color == BLACK) {
qPtr = rPtr->link[1];
rPtr->color = RED;
qPtr->color = BLACK;
rPtr->link[1] = qPtr->link[0];
qPtr->link[0] = rPtr;
rPtr = stack[ht - 1]->link[0] = qPtr;
}
rPtr->color = stack[ht - 1]->color;
stack[ht - 1]->color = BLACK;
rPtr->link[0]->color = BLACK;
stack[ht - 1]->link[0] = rPtr->link[1];
rPtr->link[1] = stack[ht - 1];
if (stack[ht - 1] == root) {
root = rPtr;
} else {
stack[ht - 2]->link[dir[ht - 2]] = rPtr;
}
break;
}
}
ht--;
}
}
}

// Print the inorder traversal of the tree


void inorderTraversal(struct rbNode *node) {
if (node) {
inorderTraversal(node->link[0]);
printf("%d ", node->data);
inorderTraversal(node->link[1]);
}
return;
}

// Driver code
int main() {
int ch, data;
while (1) {
printf("1. Insertion\t2. Deletion\n");
printf("3. Traverse\t4. Exit");
printf("\nEnter your choice:");
scanf("%d", &ch);
switch (ch) {
case 1:
printf("Enter the element to insert:");
scanf("%d", &data);
insertion(data);
break;
case 2:
printf("Enter the element to delete:");
scanf("%d", &data);
deletion(data);
break;
case 3:
inorderTraversal(root);
printf("\n");
break;
case 4:
exit(0);
default:
printf("Not available\n");
break;
}
printf("\n");
}
return 0;
}
OUTPUT:
1. Insertion 2. Deletion
3. Traverse 4. Exit
Enter your choice:1
Enter the element to insert:22

1. Insertion 2. Deletion
3. Traverse 4. Exit
Enter your choice:1
Enter the element to insert:33

1. Insertion 2. Deletion
3. Traverse 4. Exit
Enter your choice:3
22 33

1. Insertion 2. Deletion
3. Traverse 4. Exit
Enter your choice:
9. Write a program to implement the Graph Traversal methods

(a) Breadth first traversal

#include<stdio.h>
#include<stdlib.h>
#define MAX 100
#define initial 1
#define waiting 2
#define visited 3
int n;
int adj[MAX][MAX];
int state[MAX];
void create_graph();
void BF_Traversal();
void BFS(int v);
int queue[MAX], front = -1,rear = -1;
void insert_queue(int vertex);
int delete_queue();
int isEmpty_queue();
int main()
{
create_graph();
BF_Traversal();
return0;
}
void BF_Traversal()
{
int v;
for(v=0; v<n; v++)
state[v] = initial;
printf("Enter Start Vertex for BFS: \n");
scanf("%d", &v);
BFS(v);
}

void BFS(int v)
{
int i;
insert_queue(v);
state[v] = waiting;

while(!isEmpty_queue())
{
v = delete_queue( );
printf("%d ",v);
state[v] = visited;

for(i=0; i<n; i++)


{
if(adj[v][i] == 1&& state[i] == initial)
{
insert_queue(i);
state[i] = waiting;
}
}
}
printf("\n");
}

void insert_queue(int vertex)


{
if(rear == MAX-1)
printf("Queue Overflow\n");
else
{
if(front == -1)
front = 0;
rear = rear+1;
queue[rear] = vertex ;
}
}

int isEmpty_queue()
{
if(front == -1 || front > rear)
return1;
else
return0;
}

int delete_queue()
{
int delete_item;
if(front == -1 || front > rear)
{
printf("Queue Underflow\n");
exit(1);
}

delete_item = queue[front];
front = front+1;
return delete_item;
}

void create_graph()
{
int count,max_edge,origin,destin;

printf("Enter number of vertices : ");


scanf("%d",&n);
max_edge = n*(n-1);

for(count=1; count<=max_edge; count++)


{
printf("Enter edge %d( -1 -1 to quit ) : ",count);
scanf("%d %d",&origin,&destin);

if((origin == -1) && (destin == -1))


break;

if(origin>=n || destin>=n || origin<0 || destin<0)


{
printf("Invalid edge!\n");
count--;
}
else
{
adj[origin][destin] = 1;
}
}
}
OUTPUT

Enter number of vertices : 9


Enter edge 1( -1 -1 to quit ) : 0
1
Enter edge 2( -1 -1 to quit ) : 0
3
Enter edge 3( -1 -1 to quit ) : 0
4
Enter edge 4( -1 -1 to quit ) : 1
2
Enter edge 5( -1 -1 to quit ) : 3
6
Enter edge 6( -1 -1 to quit ) : 4
7
Enter edge 7( -1 -1 to quit ) : 6
4
Enter edge 8( -1 -1 to quit ) : 6
7
Enter edge 9( -1 -1 to quit ) : 2
5
Enter edge 10( -1 -1 to quit ) : 4
5
Enter edge 11( -1 -1 to quit ) : 7
5
Enter edge 12( -1 -1 to quit ) : 7
8
Enter edge 13( -1 -1 to quit ) : -1
-1
Enter Start Vertex for BFS:
0
013426578

(b) Depth first traversal

#include<stdio.h>
#include<stdlib.h>

typedefstruct node
{
struct node *next;
int vertex;
}node;

node *G[20];
//heads of linked list
int visited[20];
int n;
void read_graph();
//create adjacency list
void insert(int,int);
//insert an edge (vi,vj) in te adjacency list
void DFS(int);

void main()
{
int i;
read_graph();
//initialised visited to 0
for(i=0;i<n;i++)
visited[i]=0;

DFS(0);
}

void DFS(int i)
{
node *p;

printf("\n%d",i);
p=G[i];
visited[i]=1;
while(p!=NULL)
{
i=p->vertex;

if(!visited[i])
DFS(i);
p=p->next;
}
}

void read_graph()
{
int i,vi,vj,no_of_edges;
printf("Enter number of vertices:");

scanf("%d",&n);

//initialise G[] with a null

for(i=0;i<n;i++)
{
G[i]=NULL;
//read edges and insert them in G[]

printf("Enter number of edges:");


scanf("%d",&no_of_edges);
for(i=0;i<no_of_edges;i++)
{
printf("Enter an edge(u,v):");
scanf("%d%d",&vi,&vj);
insert(vi,vj);
}
}
}
void insert(int vi,int vj)
{
node *p,*q;

//acquire memory for the new node


q=(node*)malloc(sizeof(node));
q->vertex=vj;
q->next=NULL;

//insert the node in the linked list number vi


if(G[vi]==NULL)
G[vi]=q;
else
{
//go to end of the linked list
p=G[vi];

while(p->next!=NULL)
p=p->next;
p->next=q;
}
}
OUTPUT

Enter number of vertices:8


Enter number of edges:10
Enter an edge(u,v):0 1
Enter an edge(u,v):0 2
Enter an edge(u,v):0 3
Enter an edge(u,v):0 4
Enter an edge(u,v):1 5
Enter an edge(u,v):2 5
Enter an edge(u,v):3 6
Enter an edge(u,v):3 6
Enter an edge(u,v):4 7
Enter an edge(u,v):5 7

0
1
5
7
2
3
6
4
10.Implement a Pattern matching algorithms using Boyer- Moore, Knuth-Morris-
Pratt

# include <limits.h>
# include <string.h>

# include <stdio.h>

# define NO_OF_CHARS 256

// A utility function to get maximum of two integers

int max(int a, int b) {

return (a > b) ? a : b;

// The preprocessing function for Boyer Moore's bad character heuristic

void badCharHeuristic(char *str, int size, int badchar[NO_OF_CHARS]) {

int i;

// Initialize all occurrences as -1

for (i = 0; i < NO_OF_CHARS; i++)

badchar[i] = -1;

// Fill the actual value of last occurrence of a character

for (i = 0; i < size; i++)

badchar[(int) str[i]] = i;

void search(char *txt, char *pat) {


int m = strlen(pat);

int n = strlen(txt);

int badchar[NO_OF_CHARS];

badCharHeuristic(pat, m, badchar);

int s = 0; // s is shift of the pattern with respect to text

while (s <= (n - m)) {

int j = m - 1;

while (j >= 0 && pat[j] == txt[s + j])

j--;

if (j < 0) {

printf("\n pattern occurs at shift = %d", s);

s += (s + m < n) ? m - badchar[txt[s + m]] : 1;

else

s += max(1, j - badchar[txt[s + j]]);

}
}

int main() {

char txt[] = "ABAAABCD";

char pat[] = "ABC";

search(txt, pat);

return 0;

Output:

pattern occurs at shift = 4

#include<stdio.h>

#include<string.h>

#include<stdlib.h>

void computeLPSArray(char *pat, int M, int *lps);

void KMPSearch(char *pat, char *txt) {

int M = strlen(pat);

int N = strlen(txt);

// create lps[] that will hold the longest prefix suffix values for pattern

int *lps = (int *) malloc(sizeof(int) * M);

int j = 0; // index for pat[]


// Preprocess the pattern (calculate lps[] array)

computeLPSArray(pat, M, lps);

int i = 0; // index for txt[]

while (i < N) {

if (pat[j] == txt[i]) {

j++;

i++;

if (j == M) {

printf("Found pattern at index %d \n", i - j);

j = lps[j - 1];

// mismatch after j matches

else if (i < N && pat[j] != txt[i]) {

// Do not match lps[0..lps[j-1]] characters,

// they will match anyway

if (j != 0)

j = lps[j - 1];

else

i = i + 1;
}

free(lps); // to avoid memory leak

void computeLPSArray(char *pat, int M, int *lps) {

int len = 0; // lenght of the previous longest prefix suffix

int i;

lps[0] = 0; // lps[0] is always 0

i = 1;

// the loop calculates lps[i] for i = 1 to M-1

while (i < M) {

if (pat[i] == pat[len]) {

len++;

lps[i] = len;

i++;

} else // (pat[i] != pat[len])

if (len != 0) {

// This is tricky. Consider the example AAACAAAA and i = 7.

len = lps[len - 1];


// Also, note that we do not increment i here

} else // if (len == 0)

lps[i] = 0;

i++;

// Driver program to test above function

int main() {

char *txt = "ABABDABACDABABCABAB";

char *pat = "ABABCABAB";

KMPSearch(pat, txt);

return 0;

OUTPUT:

Found pattern at index 10

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy