DS Lab Manual For Students
DS Lab Manual For Students
1
1. Write a program that uses functions to perform the following operations on singly linked list.:
i) Creation ii) Insertion iii) Deletion iv) Traversal
Program:
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
}*start=NULL,*q,*t;
int main()
{
int ch;
void insert_beg();
void insert_end();
int insert_pos();
void display();
void delete_beg();
void delete_end();
int delete_pos();
while(1)
{
printf("\n\n---- Singly Linked List(SLL) Menu ");
printf("\n1.Insert at beginning\n2.Insert at end\n3.Insert at specified position\n4.Delete from beginning\
n5.Delete from end\n6.Delete from specified position\n7.Display\n8.Exit");
printf("\nEnter your choice(1-8):"); scanf("%d",&ch);
}
switch(ch)
{
case 1: insert_beg(); break;
case 2: insert_end(); break;
case 3: insert_pos(); break;
case 4: delete_beg();break;
case 5: delete_end(); break;
case 6: delete_pos(); break;
case 7: display(); break;
case 8: exit(0);
break;
default: printf("Wrong Choice!!");
}
}
return 0;
2
}
void insert_beg()
{
int num;
t=(struct node*)malloc(sizeof(struct node));
printf("Enter data:");
scanf("%d",&num);
t->data=num;
if(start==NULL) //If list is empty
{
t->next=NULL;
start=t;
}
else
{
t->next=start;
start=t;
}
}
void insert_end()
{
int num;
t=(struct node*)malloc(sizeof(struct node));
printf("Enter data:");
scanf("%d",&num);
t->data=num;
t->next=NULL;
if(start==NULL) //If list is empty
{
start=t;
}
else
{
q=start;
while(q->next!=NULL) q=q->next;
q->next=t;
}
}
int insert_pos()
{
int pos,i,num;
if(start==NULL)
{
printf("List is empty!!");
return 0;
}
3
t=(struct node*)malloc(sizeof(struct node));
printf("Enter data:");
scanf("%d",&num);
printf("Enter position to insert:");
scanf("%d",&pos);
t->data=num;
q=start;
for(i=1;i<pos-1;i++)
{
if(q->next==NULL)
{
printf("There are less elements!!");
return 0;
}
q=q->next;
}
t->next=q->next;
q->next=t;
return 0;
}
void display()
{
if(start==NULL)
{
printf("List is empty!!");
}
else
{
q=start;
printf("The linked list is:\n");
while(q!=NULL)
{
printf("%d->",q->data);
q=q->next;
}
}
}
void delete_beg()
{
if(start==NULL)
{
printf("The list is empty!!");
}
else
{
4
q=start;
start=start->next;
printf("Deleted element is %d",q->data);
free(q);
}
}
void delete_end()
{
if(start==NULL)
{
printf("The list is empty!!");
}
else
{
q=start;
while(q->next->next!=NULL) q=q->next;
t=q->next;
q->next=NULL;
printf("Deleted element is %d",t->data);
free(t);
}
}
int delete_pos()
{
int pos,i;
if(start==NULL)
{
printf("List is empty!!");
return 0;
}
OUTPUT:
---- Singly Linked List(SLL) Menu ---
1.Insert at beginning 2.Insert at end
3.Insert at specified position 4.Delete from beginning 5.Delete from end
6.Delete from specified position 7.Display
8.ExitEnter your choice(1-8):8
root@cse-ThinkCentre-M71e:~# gcc singlelinked.c root@cse-ThinkCentre-M71e:~# ./a.out
6
---- Singly Linked List(SLL) Menu ----
1.Insert at beginning 2.Insert at end
3.Insert at specified position 4.Delete from beginning 5.Delete from end
6.Delete from specified position 7.Display
8.Exit
Enter your choice(1-8):7 The linked list is:
10->
9
2. Write a program that uses functions to perform the following operations on doubly linked list.
i) Creation ii) Insertion iii) Deletion iv) Traversal
Program:
#include<stdio.h>
#include<stdlib.h>
typedef struct node1
{
int info;
struct node1* next;
struct node1* prev;
}node;
node *head=NULL;
node *tail=NULL;
node* create(int i)
{
node* tmp=(node*)malloc(sizeof(node));
tmp->info=i;
tmp->next=NULL;
tmp->prev=NULL;
printf("\nNode Cretaed...!!!!");
return tmp;
}
void addtohead(node *tmp)
{
node *t;
t=head;
t->prev=tmp;
tmp->next=t;
head=tmp;
printf("\nNode inserted at the start...!!");
}
void addtoend(node *tmp)
{
if(head==tail)
{
head->next=tmp;
tmp->prev=head;
tail=tmp;
}
else
{
tail->next=tmp;
tmp->prev=tail;
tail=tmp;
}
10
printf("\nNode inserted at the end...!!!");
}
void atpos(node *newnode)
{
node *nextp,*curr,*tmp;
int i,pos;
printf("\nEnter the position at which you want to insert the node ?? ");
scanf("%d",&pos);
if(pos==1)
{
addtohead(newnode);
}
else
{
curr=head;
nextp=head->next;
for(i=1;i<pos-1;i++)
{
nextp=nextp->next;
curr=curr->next;
}
tmp=nextp;
curr->next=newnode;
newnode->prev=curr;
newnode->next=tmp;
tmp->prev=newnode;
printf("\nNode inserted at position %d !!!",pos);
}
}
void insert()
{
int data,i,p,ch; do{
printf("\nEnter the element you want to insert : ");
scanf("%d",&data);
node* tmp=create(data);
if(head==NULL)
{
head=tail=tmp;
printf("\nList was Empty....Item inserted at first position !!!");
}
else
{
printf("\nAt which position you want to insert the item ??? ");
printf("\n1.Begining");
printf("\n2.Ending");
printf("\n3.At specific position");
printf("\nEnter your choice : ");
scanf("%d",&p);
switch(p)
11
{
case 1: addtohead(tmp); break;
case 2: addtoend(tmp); break;
case 3: atpos(tmp); break;
default: printf("\nWrong choice ...Enter again...!!!");
}
}
printf("\nDo you want to insert another node (1/0) ??");
scanf("%d",&ch);
}
while(ch==1);
}
void deletefromhead()
{
node *tmp=head;
head=head->next;
head->prev=NULL;
printf("\nNode deleted from head is : %d",tmp->info);
free(tmp);
}
void deletefromend()
{
node *tmp=tail;
tail=tail->prev;
printf("\nNode deleted from end is : %d",tmp->info);
free(tmp);
tail->next=NULL;
}
void deletepos()
{
int pos,i,c;
node *pre,*curr;
pre=head;
curr=head->next;
printf("\nEnter the position of node you want to delete : ");
scanf("%d",&pos);
if(pos==1)
deletefromhead();
else
{
for(i=1;i<pos-1;i++)
{
curr=curr->next;
pre=pre->next;
}
12
printf("\nNode deleted from %d is : %d",pos,curr->info);
pre->next=curr->next;
curr->next->prev=pre;
free(curr);
}
}
void deleten()
{
int p,ch;
do
{
if(head==NULL)
{
printf("\nList is empty...!!!!");
}
else if(head==tail)
{
printf("\nOnly one element in the list.. delelted node is : %d ",head->info);
free(head);
head=NULL;
tail==NULL;
}
else
{
system("cls");
printf("\nFrom which position you want to delete the node ?? ");
printf("\n1.Begining");
printf("\n2.Ending");
printf("\n3.At specific position");
printf("\nEnter your choice : ");
scanf("%d",&p);
switch(p){
case 1: deletefromhead(); break;
case 2: deletefromend(); break;
case 3: deletepos(); break;
default: printf("\nWrong choice ...Enter again...!!!");
}
}
printf("\nDo you want to delete another node (1/0)??");
scanf("%d",&ch);
}
while(ch==1);
}
void display()
{
node *tmp=head;
if(head==NULL)
printf("\nList is empty..!!!");
13
else
{
for(;tmp!=NULL;tmp=tmp->next)
{
if(tmp->next==NULL)
printf("%d",tmp->info);
else
printf("%d -> ",tmp->info);
}
}
}
int main()
{
int c,ch;
do
{
printf("\n-------DOUBLY LINKED LIST ");
printf("\n1.INSERT INTO LIST");
printf("\n2.DELETE FROM LIST");
printf("\n3.DISPLAY THE LIST");
printf("\n4.EXIT");
printf("\nEnter your choice : ");
scanf("%d",&c);
switch(c)
{
case 1: insert(); break;
case 2: deleten(); break;
case 3: display(); break;
case 4: exit(0);
}
printf("\nDo you want to perform any function again (1/0)???");
scanf("%d",&ch);
}while(ch==1);
return 0;
}
OUTPUT:
Node Cretaed...!!!!
At which position you want to insert the item ??? 1.Begining
2. Ending
3. At specific position Enter your choice : 2
Enter the position at which you want to insert the node ?? 2 Node inserted at position 2 !!!
Do you want to insert another node (1/0) ??0
16
3. Write a program that uses functions to perform the following operations on circular linked list.
i) Creation ii) Insertion iii) Deletion iv) Traversal
Program:
#include<stdio.h>
#include<stdlib.h>
typedef struct Node{
int info;
struct Node *next;
}node;
node *front=NULL,*rear=NULL,*temp;
void create();
void del();
void display();
int main()
{
int chc;
do
{
printf("\nMenu\n\t 1 to create the element : ");
printf("\n\t 2 to delete the element : ");
printf("\n\t 3 to display : ");
printf("\n\t 4 to exit from main : ");
printf("\nEnter your choice : ");
scanf("%d",&chc);
switch(chc)
{
case 1: create(); break;
case 2: del(); break;
case 3: display(); break;
case 4: return 1;
}
}
return 0;
if(front==rear)
{
}
else
{
}
printf("\n%d",front->info);
front=rear=NULL;
printf("\n%d",front->info);
front=front->next;
rear->next=front;
temp->next=NULL; free(temp);
}
}
void display()
{
temp=front; if(front==NULL)
printf("\nEmpty");
else
{}
printf("\n");
for(;temp!=rear;temp=temp->next)
printf("\n%d \t",temp->info);
printf("\n%d \t",temp->info);
}
OUTPUT:
-------CIRCULAR LINKEDLIST -------
5. INSERT INTO LIST
6. DELETE FROM LIST
18
7. DISPLAY THE LIST
8. EXIT
Enter your choice : 2 sh: 1: cls: not found
From which position you want to delete the node ?? 1.Begining
4. Ending
5. At specific position Enter your choice : 2
19
4. Write a program that implement stack (its operations) using
i) Arrays ii) Pointers
Program:
STACK USING ARRAYS:
#include<stdio.h>
#include<stdlib.h>
#define MAX 5 //Maximum number of elements that can be stored
int top=-1,stack[MAX];
void push();
void pop();
void display();
void topelement();
void main()
{
int ch;
while(1) //infinite loop, will end when choice will be 4
{
printf("\n*** Stack opeartions ***");
printf("\n\n1.Push\n2.Pop\n3.Display\n4.top element\n5.Exit");
printf("\n\nEnter your choice(1-5):");
scanf("%d",&ch);
switch(ch)
{
case 1: push();break;
case 2: pop();break;
case 3: display();
case4 :topelement()();
case 5: exit(0);
break;
default: printf("\
nWrongChoice!!
");
}
}
}
void push()
{
int val;
if(top==MAX-1)
{
printf("\nStack is
full!!");
20
else
{
printf("\nEnter element to push:"); scanf("%d",&val);
top=top+1; stack[top]=val;
void pop()
{
if(top==-1)
{
printf("\nStack is empty!!");
}
else
{
printf("\nDeleted element is %d",stack[top]); top=top-1;
}
}
void topelement()
{
if(top==-1)
{
printf("\nStack is empty!!");
}
else
{
printf("\ntopelement is %d",stack[top]);
}
}
void display()
{
int i;
if(top==-1)
{
}
else
{Printf("\nStack is empty!!");
printf("\nStack is...\n");
for(i=top;i>=0;--i)
printf("%d\n",stack[i]);
}
}
21
OUTPUT:
*** Stack opeartions ***
1.Push 2.Pop 3.Display
4.top element 5.Exit
22
*** Stack opeartions ***
PROGRAM:
#include<stdio.h>
#include<stdlib.h>
#define MAX 50 int size;
// Defining the stack structure struct stack
{
int arr[MAX];
23
int top;
};
24
int main()
{
int element, opt, val; struct stack ptr;
init_stk(&ptr);
printf("\nEnter Stack Size :");
scanf("%d", &size);
while (1) {
printf("\n\nSTACK OPERATIONS");
printf("\n1.PUSH");
printf("\n2.POP");
printf("\n3.DISPLAY");
printf("\n4.QUIT");
printf("\n");
printf("\nEnter your option : ");
scanf("%d", &opt);
switch (opt)
{
case 1:
printf("\nEnter the element into stack:");
scanf("%d", &val);
push(&ptr, val);
break;
case 2:
element = pop(&ptr);
printf("\nThe element popped from stack is : %d", element); break;
case 3:
display(&ptr); break;
case 4:
exit(0); default:
printf("\nEnter correct option!Try again.");
}
}
return (0);
}
OUTPUT:
25
4. QUIT
26
4. QUIT
27
5. Write a program that implement Queue (its operations) using
i) Arrays ii) Pointers
PROGRAM:
#include <stdio.h>
#include<stdlib.h>
#define MAX 50
void insert();
void delete();
void display();
int queue_array[MAX];
int rear = - 1;
int front = - 1;
main()
{
int choice;
while (1)
{
printf("QUEUE OPERATIONS");
printf("\n 1.Insert element to queue \n2.Delete element from queue \n3.Display elements of queue \n4.Quit \
n");
printf("Enter your choice : ");
scanf("%d", &choice);
switch (choice)
{
case 1:
insert(); break; case 2:
delete(); break; case 3:
display(); break; case 4:
exit(1); default:
printf("Wrong choice \n");
}
}
}
void insert()
{
int element;
if (rear == MAX - 1)
printf("Queue Overflow \n");
else
{
if (front == - 1)
/*If queue is initially empty */ front = 0;
printf("Inset the element in queue : ");
scanf("%d", &element);
rear = rear + 1; queue_array[rear] = element;
}
28
} /* End of insert() */ void delete()
{
if (front == - 1 || front > rear)
{
printf("Queue Underflow \n");
return ;
}
else
{
printf("Element deleted from queue is : %d\n", queue_array[front]);
front = front + 1;
}
} /* End of delete() */ void display()
{
int i;
if (front == - 1)
printf("Queue is empty \n");
else
{
printf("Queue is : \n");
for (i = front; i <= rear; i++)
printf("%d ", queue_array[i]);
printf("\n");
}
}
OUTPUT:
1.Insert element to queue 2.Delete element from queue 3.Display elements of queue 4.Quit
Enter your choice : 3 Queue is empty QUEUE OPERATIONS
1.Insert element to queue 2.Delete element from queue 3.Display elements of queue 4.Quit
Enter your choice : 2 Queue Underflow QUEUE OPERATIONS
1.Insert element to queue 2.Delete element from queue 3.Display elements of queue 4.Quit
Enter your choice : 1
Inset the element in queue : 20 QUEUE OPERATIONS
1.Insert element to queue 2.Delete element from queue 3.Display elements of queue 4.Quit
Enter your choice : 1
Inset the element in queue : 30 QUEUE OPERATIONS
1.Insert element to queue 2.Delete element from queue 3.Display elements of queue 4.Quit
Enter your choice : 1
Inset the element in queue : 40 QUEUE OPERATIONS
1.Insert element to queue 2.Delete element from queue 3.Display elements of queue 4.Quit
Enter your choice : 1
Inset the element in queue : 50
29
Queue using Pointers:
PROGRAM:
#include<stdio.h>
#include<stdlib.h>
typedef struct Node
{
}node;
int info;
struct Node *next;
node *front=NULL,*rear=NULL,*temp;
void create();
void del();
void display();
int main()
{
int chc;
do
{
printf("\nMenu\n\t 1 to create the element : ");
printf("\n\t 2 to delete the element : ");
printf("\n\t 3 to display : ");
printf("\n\t 4 to exit from main : ");
printf("\nEnter your choice : ");
scanf("%d",&chc);
switch(chc)
{
case 1: create(); break;
case 2: del(); break;
case 3: display(); break;
case 4:return 1;
default:printf("\nInvalid choice :");
}
}while(1);
return 0;
}
void create()
{
node *newnode; newnode=(node*)malloc(sizeof(node));
printf("\nEnter the node value : ");
scanf("%d",&newnode->info);
newnode->next=NULL;
if(rear==NULL) front=rear=newnode;
else
{
rear->next=newnode;
30
rear=newnode;
}
rear->next=front;
}
void del()
{
temp=front;
if(front==NULL)
printf("\nUnderflow :");
else
{
if(front==rear)
}
else
{
}
printf("\n%d",front->info);
front=rear=NULL;
printf("\n%d",front->info);
front=front->next;
rear->next=front;
temp->next=NULL;
free(temp);
}
}
void display()
{
temp=front;
if(front==NULL)
printf("\nEmpty");
else
{
printf("\n");
for(;temp!=rear;temp=temp->next)
printf("\n%d \t",temp->info);
printf("\n%d \t",temp->info);
}
}
OUTPUT:
32
Enter your choice:1 Element to be inserted:30
34
7. 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
i) QUICK SORT
PROGRAM:
#include<stdio.h>
main()
{
int a[10],i,left,right,n;
int min,loc;
clear();
printf("\n enter the max no.of elements u want to sort \n");
scanf("%d",&n);
printf("\n enter the elements u want to sort \n");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
left=0;
right=n-1;
quicksort(a,left,right);
display(a,n);
}
quicksort(int a[],int left,intright)
{
int temp,flag=1,i,j,p;
i=left;
j=right;
p=a[left];
if(right>left)
{
while(flag)
{
do
{
i++;
}
while(a[i]<p && i<=right);
while((a[i]>p) && j>left)
j--;
35
if(j<i)
flag=0;
else
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
temp=a[lest];
a[left]=a[j];
a[j]=temp;
quicksort[a,left,j-1];
quicksort[a,i,right];
}
}
display(int a[],int n)
{
int i;
for(i=0;i<n;i++)
{
printf("%d\t",a[i]);
}
getch();
}
OUTPUT:
enter the max no. of elements u want to sort
5
enter the elements u want to sort
10 20 15 6 40
6 10 15 20 40
#include<stdio.h>
main()
{
int a[10],i,j,n;
int min,loc;
clear();
printf("\n enter the max no.of elements u wanna sort \n");
scanf("%d",&n);
printf("\n enter the elements u want to sort \n");
for(i=0;i<n;i++)
36
{
scanf("%d",&a[i]);
}
heapsort(a,n);
display(a,n);
}
heapsort(inta[],int n)
{
int temp,i,key,q;
create heap(a,n);
for(q=n;q>2;q--)
{
temp=a[i];
a[i]=a[q];
a[q]=temp;
i=1;
key=a[1];
j=2;
if((j+1)<q)
if(a[j+1]>a[j])
j++;
while(j<=(q-1) && a[j]<key))
{
a[i]=a[j];
i=j;
j=2*i;
if((j+1)<q)
if(a[j+1]>a[j])
j++;
else
if(j>n)
j=n;
a[i]=key;
}
}}
OUTPUT:
37
iii) MERGE SORT
PROGRAM:
#include<stdio.h>
#include<conio.h>
#define MAX 20
int array[MAX];
void merge(int low, int mid, int high )
{
int temp[MAX];
int i = low;
int j = mid +1 ;
int k = low ;
while( (i <= mid) && (j <=high) )
{
if (array[i] <= array[ j])
temp[k++] = array[i++] ;
else
temp[k++] = array[ j++] ;
}
while( i <= mid )
temp[k++]=array[i++];
while( j <= high )
temp[k++]=array[j++];
for (i= low; i <= high ; i++)
array[i]=temp[i];
}
void merge_sort(int low, int high )
{
int mid;
if ( low != high )
{
mid = (low+high)/2;
merge_sort( low , mid );
merge_sort( mid+1, high );
merge(low, mid, high );
}
}
void main()
{
int i,n;
clrscr();
printf ("\nEnter the number of elements :");
38
scanf ("%d",&n);
for (i=0;i<n;i++)
{
printf ("\nEnter element %d :",i+1);
scanf ("%d",&array[i]);
}
printf ("\nUnsorted list is :\n");
for ( i = 0 ; i<n ; i++)
printf ("%d", array[i]);
merge_sort( 0, n-1);
printf ("\nSorted list is :\n");
for ( i = 0 ; i<n ; i++)
printf ("%d", array[i]);
getch();
}
OUTPUT:
Sorted array:
1 5 6 9 10 12
PROGRAM:
#include <stdio.h>
#include <stdlib.h>
typedef struct BST
{
int data;
struct BST *left;
struct BST *right;
} node;
node * create();
void insert(node *, node *);
void preorder(node *);
void postorder(node *);
void inorder(node *);
int main()
{
int ch;
node *root = NULL, *temp, *current;
printf("\nEnter the number of Nodes you want :\t");
scanf("%d", &ch);
printf("\nEnter %d Nodes data :\n", ch);
39
do
{
temp = create();
if (root == NULL)
root = temp;
else
insert(root, temp);
ch--;
} while (ch != 0);
printf("\nPreorder Traversal\n");
preorder(root);
printf("\nInorder Traversal\n");
inorder(root);
printf("\nPostorder Traversal\n");
postorder(root);
printf("\n");
return 0;
}
node *create()
{
node *temp;
temp = (node *)malloc(sizeof(node));
scanf("%d", &temp->data);
temp->left = temp->right = NULL;
return temp;
}
void insert(node *root, node *temp)
{
if (root == NULL)
{
root = temp;
}
else
{
if (temp->data < root->data)
{
if (root->left != NULL)
insert(root->left, temp);
else
root->left = temp;
}
if (temp->data > root->data)
{
if (root->right != NULL)
insert(root->right, temp);
else
root->right = temp;
40
}
}
}
void preorder(node *root)
{
if (root != NULL)
{
printf("%d \t", root->data);
preorder(root->left);
preorder(root->right);
}
}
void postorder(node *root)
{
if (root != NULL)
{
postorder(root->left);
postorder(root->right);
printf("%d \t", root->data);
}
}
void inorder(node *root)
{
if (root != NULL)
{
inorder(root->left);
printf("%d \t", root->data);
inorder(root->right);
}
}
OUTPUT:
Enter the number of Nodes you want: 8
Enter 8 Nodes data :
25
63
98
78
45
100
2
84
Preorder Traversal
25 2 63 45 98 78 84 100
Inorder Traversal
22545 63 78 84 98 100
41
Postorder Traversal
24584 78 100 98 63 25
8. Write a program to implement i. Binary Search Tree ii. B Trees iii. AVL Trees iv. Red- Black
Trees
Aim: Write a program to implement i. Binary Search Tree ii. B Trees iii. AVL Trees iv. Red- Black Trees
PROGRAM:
#include
<stdio.h>
#include
<stdlib.h>
struct btnode
{
int value;
struct
btnode *l;
struct
btnode *r;
}*root = NULL, *temp = NULL, *t2,
*t1; void insert();
void create();
void search( struct btnode
*root); void inorder(struct
btnode *t); void
preorder(struct btnode *t);
void postorder(struct btnode
*t); void main()
42
{
int ch; printf("\
nOPERATIONS ---");
printf("\n1 - Insert an element into tree\
n"); printf("2 - Inorder Traversal\n");
printf("3 - Preorder Traversal\
n"); printf("4 - Postorder
Traversal\n"); printf("5 - Exit\
n");
while(1)
{
printf("\nEnter your choice
: "); scanf("%d", &ch);
switch (ch)
{
case 1:
inse
rt();
bre
ak;
case 2:
inorder(r
oot);
break;
case 3:
preorder(root)
break;
case 4:
postorder(r
oot); break;
case 5:
exi
t(0);
defau
lt :
printf("Wrong choice, Please enter correct
choice "); break;
43
}
}
}
/* 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
44
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 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;
45
}
if (t->l != NULL)
postorder(t
->l); if (t->r !
= NULL)
postorder(t->r);
printf("%d -> ", t-
>value);
}
OUTPUT:
ii.
B Trees
PROGRAM:
#include <stdio.h>
#include <stdlib.h>
#define MAX 3
#define MIN 2
struct BTreeNode {
int val[MAX + 1], count;
struct BTreeNode *link[MAX + 1];
};
46
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;
*pval = node->val[node->count];
(*newNode)->link[0] = node->link[node->count];
node->count--;
}
// Insert value
void insert(int val) {
int flag, i;
struct BTreeNode *child;
int main() {
int val, ch;
while (1) {
printf("1. Insert\n");
printf("2. Traverse\n");
printf("3. Exit\n");
printf("Enter your choice: ");
scanf("%d", &ch);
switch (ch) {
case 1:
printf("Enter the value to insert: ");
scanf("%d", &val);
insert(val);
break;
case 2:
inorderTraversal(root);
printf("\n");
break;
case 3:
exit(0);
default:
printf("Invalid choice\n");
}
}
return 0;
}
OUTPUT:
1. Insert
2. Traverse
3. Exit
Enter your choice: 1
Enter the value to insert: 10
1. Insert
2. Traverse
3. Exit
Enter your choice: 1
49
Enter the value to insert: 20
1. Insert
2. Traverse
3. Exit
Enter your choice: 1
Enter the value to insert: 5
1. Insert
2. Traverse
3. Exit
Enter your choice: 2
5 10 20
1. Insert
2. Traverse
3. Exit
Enter your choice: 3
PROGRAM:
#include <stdio.h>
#include <stdlib.h>
// Node structure
struct Node {
int key;
struct Node *left;
struct Node *right;
int height;
};
// Perform rotation
x->right = y;
y->left = T2;
// Update heights
y->height = max(height(y->left), height(y->right)) + 1;
x->height = max(height(x->left), height(x->right)) + 1;
// Perform rotation
y->left = x;
x->right = T2;
// Update heights
x->height = max(height(x->left), height(x->right)) + 1;
y->height = max(height(y->left), height(y->right)) + 1;
// Recursive function to insert a key in the subtree rooted with node and returns the new root of the
51
subtree.
struct Node* insert(struct Node* node, int key) {
// 1. Perform the normal BST insertion
if (node == NULL)
return(newNode(key));
// 3. Get the balance factor of this ancestor node to check whether this node became unbalanced
int balance = getBalance(node);
int main() {
struct Node *root = NULL;
// Insert nodes
root = insert(root, 10);
root = insert(root, 20);
root = insert(root, 30);
root = insert(root, 40);
root = insert(root, 50);
root = insert(root, 25);
return 0;
}
OUTPUT:
PROGRAM:
#include <stdio.h>
#include <stdlib.h>
// Node structure
typedef struct Node {
int data;
char color;
struct Node *left, *right, *parent;
} Node;
int main() {
Node *root = NULL;
insert(&root, 10);
insert(&root, 20);
insert(&root, 30);
insert(&root, 15);
insert(&root, 25);
printf("In-order traversal of the Red-Black Tree: ");
inorder(root);
return 0;
}
OUTPUT:
PROGRAM:
#include<stdio.h>
int q[20],top=-1,front=-1,rear=-1,a[20][20],vis[20],stack[20];
int delete();
void add(int item);
void bfs(int s,int n);
void dfs(int s,int n);
void push(int item);
int pop();
void main()
{
int n,i,s,ch,j;
char c,dummy;
56
printf("ENTER THE NUMBER VERTICES ");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
printf("ENTER 1 IF %d HAS A NODE WITH %d ELSE 0 ",i,j);
scanf("%d",&a[i][j]);
}
}
printf("THE ADJACENCY MATRIX IS\n");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
printf(" %d",a[i][j]);
}
printf("\n");
}
do
{
for(i=1;i<=n;i++)
vis[i]=0;
printf("\nMENU");
printf("\n1.B.F.S");
printf("\n2.D.F.S");
printf("\nENTER YOUR CHOICE");
scanf("%d",&ch);
printf("ENTER THE SOURCE VERTEX :");
scanf("%d",&s);
switch(ch)
{
case 1:bfs(s,n); break;
case 2:dfs(s,n); break;
}
printf("DO U WANT TO CONTINUE(Y/N) ? ");
scanf("%c",&dummy);
scanf("%c",&c);
}while((c=='y')||(c=='Y'));
}
OUTPUT:
ENTER THE NUMBER VERTICES 3
ENTER 1 IF 1 HAS A NODE WITH 1 ELSE 0 0
ENTER 1 IF 1 HAS A NODE WITH 2 ELSE 0 1
ENTER 1 IF 1 HAS A NODE WITH 3 ELSE 0 1
ENTER 1 IF 2 HAS A NODE WITH 1 ELSE 0 1
ENTER 1 IF 2 HAS A NODE WITH 2 ELSE 0 1
59
ENTER 1 IF 2 HAS A NODE WITH 3 ELSE 0 1
ENTER 1 IF 3 HAS A NODE WITH 1 ELSE 0 0
ENTER 1 IF 3 HAS A NODE WITH 2 ELSE 0 1
ENTER 1 IF 3 HAS A NODE WITH 3 ELSE 0 0
THE ADJACENCY MATRIX IS
011
111
010
MENU:
1.B.F.S
2.D.F.S
DO U WANT TO CONTINUE(Y/N) ? y
MENU:
1.B.F.S
2.D.F.S
DO U WANT TO CONTINUE(Y/N) ? n
i. Boyer- Moore
PROGRAM:
#include <stdio.h>
60
#include <string.h>
// A function to search for a pattern in a given text using the Boyer-Moore algorithm
void search(char *txt, char *pat) {
int m = strlen(pat);
int n = strlen(txt);
int badchar[NO_OF_CHARS];
// Keep reducing index j of pattern while characters of pattern and text are matching at this shift s
while (j >= 0 && pat[j] == txt[s + j])
j--;
// If the pattern is present at the current shift, then index j will become -1 after the above loop
if (j < 0) {
printf("\nPattern 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";
61
char pat[] = "ABC";
search(txt, pat);
return 0;
}
OUTPUT:
Pattern occurs at shift = 4
ii. Knuth-Morris-Pratt
PROGRAM:
#include <stdio.h>
#include <string.h>
int main() {
char txt[] = "ABABDABACDABABCABAB";
char pat[] = "ABABCABAB";
KMPSearch(pat, txt);
return 0;
}
OUTPUT:
ADDITIONAL PROGRAMS
PROGRAM:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
#define SIZE 2
0 struct DataItem
{
int data;
int key;
};
struct DataItem* hashArray[SIZE];
struct DataItem* dummyItem;
struct DataItem* item;
int hashCode(int key)
{
return key % SIZE;
}
struct DataItem *search(int key)
{
int hashIndex = hashCode(key); //get the hash
while(hashArray[hashIndex] != NULL) //move in array until an empty
{
if(hashArray[hashIndex]->key == key)
return hashArray[hashIndex];
++hashIndex; //go to next cell
hashIndex %= SIZE; //wrap around the table
}
return NULL;
}
void insert(int key,int data)
{
struct DataItem *item = (struct DataItem*) malloc(sizeof(struct DataItem));
item->data = data;
item->key = key;
int hashIndex = hashCode(key); //get the hash
//move in array until an empty or deleted cell
while(hashArray[hashIndex] != NULL && hashArray[hashIndex]->key != -1)
{
++hashIndex; //go to next cell
hashIndex %= SIZE; //wrap around the table
}
hashArray[hashIndex] = item;
}
struct DataItem* delete(struct DataItem* item)
64
{
int key = item->key;
int hashIndex = hashCode(key); //get the hash
while(hashArray[hashIndex] != NULL) //move in array until an empty
{
if(hashArray[hashIndex]->key == key)
{
struct DataItem* temp = hashArray[hashIndex];
hashArray[hashIndex] = dummyItem; //assign a dummy item at deleted position
return temp;
}
++hashIndex; //go to next cell
hashIndex %= SIZE; //wrap around the table
}
return NULL;
}
void display()
{
int i = 0;
for(i = 0; i<SIZE; i++)
{
if(hashArray[i] != NULL)
printf(" (%d,%d)",hashArray[i]->key,hashArray[i]->data);
else
printf(" ~~ ");
}
printf("\n");
}
int main()
{
dummyItem = (struct DataItem*) malloc(sizeof(struct DataItem));
dummyItem->data = -1;
dummyItem->key = -1;
insert(1, 20);
insert(2, 70);
insert(42, 80);
insert(4, 25);
insert(12, 44);
insert(14, 32);
insert(17, 11);
insert(13, 78);
insert(37, 97);
display();
item = search(37);
if(item != NULL)
65
{
printf("Element found: %d\n", item->data);
}
else
{
printf("Element not found\n");
}
delete(item);
item = search(37);
if(item != NULL)
{
printf("Element found: %d\n", item->data);
}
else
{
printf("Element not found\n");
}
}
OUTPUT:
~~ (1,20) (2,70) (42,80) (4,25) ~~ ~~ ~~ ~~ ~~ ~~ ~~
(12,44) (13,78) (14,32) ~~
~~ (17,11) (37,97) ~~
Element found: 97
Element not found
66