0% found this document useful (0 votes)
11 views66 pages

DS Lab Manual For Students

manual

Uploaded by

chaitanya
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)
11 views66 pages

DS Lab Manual For Students

manual

Uploaded by

chaitanya
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/ 66

S.NO.

LIST OF EXPERIMENTS PAGE NO


Write a program that uses functions to perform the following
1. 2
operations on singly linked list
i)Creation ii) Insertion iii) Deletion iv)Traversal
Write a program that uses functions to perform the following
2. 10
operations on doubly linked list
i)Creation ii) Insertion iii) Deletion iv)Traversal

Write a program that uses functions to perform the following


3. 17
operations on circular linked list
i)Creation ii) Insertion iii) Deletion iv)Traversal

Write a program that implement stack(its operations)using


4. 20
i)Arrays ii)Pointers

Write a program that implement Queue(its operations)using 28


5. i)Arrays ii)Pointers

Write a program that implements the following sorting methods 35


6.
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 methods.


7. 39
Write a program to implement i. Binary Search Tree ii. B Trees iii. AVL
8. 42
Trees iv. Red- Black Trees
Write a program to implement the graph traversal methods.
9. 56
Implement a Pattern matching algorithm using Boyer- Moore, Knuth-
10. 60
Morris-Pratt

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

Aim: To write a c program to implement Singly Linked List.

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;
}

printf("Enter position to delete:");


scanf("%d",&pos);
q=start; for(i=1;i<pos-1;i++)
{
if(q->next==NULL)
{
printf("There are less elements!!");
return 0;
}
q=q->next;
}
t=q->next;
q->next=t->next;
printf("Deleted element is %d",t->data);
free(t);
return 0;
5
}

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

---- 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 List is empty!!

---- 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):4 The list is empty!!

---- 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):5 The list is empty!!

---- 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):6 List is empty!!

---- 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):1 Enter data:10

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->

---- 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):1 Enter data:5

---- 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 positionDisplay 8.Exit
Enter your choice(1-8):7 The linked list is:
5->10->

---- 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):2 Enter data:50

---- 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:
5->10->50->

---- 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):3 Enter data:25
Enter position to insert:3

---- Singly Linked List(SLL) Menu ----


7
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:
5->10->25->50->

---- 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):3 Enter data:15
Enter position to insert:2

---- 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:
5->15->10->25->50->

---- 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):4 Deleted element is 5

---- 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:
15->10->25->50->

---- 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):5 Deleted element is 50

---- 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
8
6.Delete from specified position 7.Display
8.Exit
Enter your choice(1-8):7 The linked list is:
15->10->25->

---- 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):6 Enter position to delete:2 Deleted element is 10

---- 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:
15->25->

---- 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):8

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

Aim: To write a c program to implement doubly linked list.

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:

-------DOUBLY LINKED LIST-------


1. INSERT INTO LIST
2. DELETE FROM LIST
3. DISPLAY THE LIST
4. EXIT
Enter your choice : 1

Enter the element you want to insert : 10 Node Cretaed. !!!!


List was Empty Item inserted at first position !!!
14
Do you want to insert another node (1/0) ??1 Enter the element you want to insert : 20

Node Cretaed. !!!!


At which position you want to insert the item ??? 1.Begining
2. Ending
3. At specific position Enter your choice : 2
4. Node inserted at the end...!!!
Do you want to insert another node (1/0) ??1 Enter the element you want to insert : 30

Node Cretaed...!!!!
At which position you want to insert the item ??? 1.Begining
2. Ending
3. At specific position Enter your choice : 2

Node inserted at the end...!!!


Do you want to insert another node (1/0) ??1

Enter the element you want to insert : 15 Node Cretaed...!!!!


At which position you want to insert the item ??? 1.Begining
2. Ending
3. At specific position Enter your choice : 3

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

Do you want to perform any function again (1/0)???1

-------DOUBLY LINKED LIST-------


1. INSERT INTO LIST
2. DELETE FROM LIST
3. DISPLAY THE LIST
4. EXIT
Enter your choice : 3 10 -> 15 -> 20 -> 30
Do you want to perform any function again (1/0)???1

-------DOUBLY LINKED LIST-------


1. INSERT INTO LIST
2. DELETE FROM LIST
3. DISPLAY THE LIST
4. EXIT
Enter your choice : 2 sh: 1: cls: not found

From which position you want to delete the node ?? 1.Begining


2. Ending
3. At specific position
4. Enter your choice : 1

Node deleted from head is : 10


Do you want to delete another node (1/0)??0
15
Do you want to perform any function again (1/0)???1

-------DOUBLY LINKED LIST-------


1. INSERT INTO LIST
2. DELETE FROM LIST
3. DISPLAY THE LIST
4. EXIT
Enter your choice :
3
15 -> 20 -> 30
Do you want to perform any function again (1/0)???1

-------DOUBLY LINKED LIST-------


1. INSERT INTO LIST
2. DELETE FROM LIST
3. DISPLAY THE LIST
4. EXIT
Enter your choice : 2 sh: 1: cls: not found

From which position you want to delete the node ?? 1.Begining


2. Ending
3. At specific position Enter your choice : 2

Node deleted from end is : 30


Do you want to delete another node (1/0)??0

Do you want to perform any function again (1/0)???1

-------DOUBLY LINKED LIST-------


1. INSERT INTO LIST
2. DELETE FROM LIST
3. DISPLAY THE LIST
4. EXIT
Enter your choice : 3 15 -> 20
Do you want to perform any function again (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

Aim: To write a c program to implement circular linked list.

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;

default: printf("\nInvalid choice :");


}
void create()
{
node *newnode; newnode=(node*)malloc(sizeof(node));
printf("\nEnter the node value : ");
scanf("%d",&newnode->info);
17
newnode->next=NULL;
if(rear==NULL) front=rear=newnode;
else
{
rear->next=newnode;
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:
-------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

Node deleted from end is : 30


Do you want to delete another node (1/0)??0

Do you want to perform any function again (1/0)???1

-------CIRCULARLINKED LIST -------


5. INSERT INTO LIST
6. DELETE FROM LIST
7. DISPLAY THE LIST
8. EXIT
Enter your choice : 3 15 -> 20
Do you want to perform any function again (1/0)???0

19
4. Write a program that implement stack (its operations) using
i) Arrays ii) Pointers

Aim: To write a c program to implement Stack Operations.

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

Enter your choice(1-5):4 Stack is empty!!


*** Stack opeartions ***

1.Push 2.Pop 3.Display


4.top element 5.Exit

Enter your choice(1-5):3 Stack is empty!!


*** Stack opeartions ***

1.Push 2.Pop 3.Display


4.top element 5.Exit

Enter your choice(1-5):1 Enter element to push:10

*** Stack opeartions ***

1.Push 2.Pop 3.Display


4.top element 5.Exit

Enter your choice(1-5):1 Enter element to push:20

*** Stack opeartions ***

1.Push 2.Pop 3.Display


4.top element 5.Exit

Enter your choice(1-5):1


Enter element to push:30

*** Stack opeartions *** 1.Push


2.Pop 3.Display 4.top element 5.Exit

Enter your choice(1-5):1 Enter element to push:40

*** Stack opeartions ***

1.Push 2.Pop 3.Display


4.top element 5.Exit

Enter your choice(1-5):1 Enter element to push:50

22
*** Stack opeartions ***

1.Push 2.Pop 3.Display


4.top element 5.Exit

Enter your choice(1-5):3 Stack is...


50
40
30
20
10

*** Stack opeartions *** 1.Push


2. Pop
3. Display 4.top element 5.Exit

Enter your choice(1-5):2


Deleted element is 50
*** Stack opeartions ***

1.Push 2.Pop 3.Display


4.top element 5.Exit

Enter your choice(1-5):2 Deleted element is 40


*** Stack opeartions ***

1.Push 2.Pop 3.Display


4.top element 5.Exit

Enter your choice(1-5):4 topelement is 30


*** Stack opeartions ***

1.Push 2.Pop 3.Display


4.top element 5.Exit

Enter your choice(1-5):5 Enter Stack Size :5

STACK USING POINTERS:

PROGRAM:

#include<stdio.h>
#include<stdlib.h>
#define MAX 50 int size;
// Defining the stack structure struct stack
{
int arr[MAX];
23
int top;
};

// Initializing the stack(i.e., top=-1)


void init_stk(struct stack *st)
{
st->top = -1;
}// Entering the elements into stack
void push(struct stack *st, int num)
{
if (st->top == size - 1)
{
printf("\nStack overflow(i.e., stack full).");
return;
}
st->top++;
st->arr[st->top] = num;
}

//Deleting an element from the stack. int pop(struct stack *st)


{
int num;
if (st->top == -1)
{
printf("\nStack underflow(i.e., stack empty).");
return 0;
}
num = st->arr[st->top];
st->top--;
return num;
}

void display(struct stack *st)


{
if (st->top == -1)
{
printf("\nStack underflow(i.e., stack empty).");
}
else
{
int i;
printf("\nThe current stack elements are:");
for (i = st->top; i >= 0; i--)
printf("\n%d", st->arr[i]);
}
}

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:

STACK OPERATIONS 1.PUSH


2. POP
3. DISPLAY
4. QUIT

Enter your option : 3

Stack underflow(i.e., stack empty). STACK OPERATIONS


1. PUSH
2. POP
3. DISPLAY

25
4. QUIT

Enter your option : 2

Stack underflow(i.e., stack empty). The element popped from stack is : 0

STACK OPERATIONS 1.PUSH


2. POP
3. DISPLAY
4. QUIT

Enter your option : 1


Enter the element into stack:20

STACK OPERATIONS 1.PUSH


2. POP
3. DISPLAY
4. QUIT

Enter your option : 1

Enter the element into stack:30

STACK OPERATIONS 1.PUSH


2. POP
3. DISPLAY
4. QUIT

Enter your option : 1

Enter the element into stack:40

STACK OPERATIONS 1.PUSH


2. POP
3. DISPLAY
4. QUIT

Enter your option : 1

Enter the element into stack:50

STACK OPERATIONS 1.PUSH


2. POP
3. DISPLAY

26
4. QUIT

Enter your option : 1

Enter the element into stack:60

STACK OPERATIONS 1.PUSH


2. POP
3. DISPLAY
4. QUITEnter your option : 1

Enter the element into stack:70 Stack overflow(i.e., stack full).

STACK OPERATIONS 1.PUSH


2. POP
3. DISPLAY
4. QUIT

Enter your option : 2

The element popped from stack is : 60 STACK OPERATIONS


1. PUSH
2. POP
3. DISPLAY
4. QUIT

Enter your option : 3

The current stack elements are:


50
40
30
20

STACK OPERATIONS 1.PUSH


2. POP
3. DISPLAY
4. QUIT

Enter your option : 4

27
5. Write a program that implement Queue (its operations) using
i) Arrays ii) Pointers

Queue using Arrays:

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:

****IMPLEMENTATION OF QUEUE USING POINTERS****


==============================================
MENU
==============================================
[1] To insert an element
[2] To remove an element
[3] To display all the elements
31
[4] Exit

Enter your choice:3 QUEUE is Empty.

****IMPLEMENTATION OF QUEUE USING POINTERS****


==============================================
MENU
==============================================
[1] To insert an element
[2] To remove an element
[3] To display all the elements
[4] Exit

Enter your choice:2 Queue is Empty.

****IMPLEMENTATION OF QUEUE USING POINTERS****


==============================================
MENU
==============================================
[1] To insert an element
[2] To remove an element
[3] To display all the elements
[4] Exit

Enter your choice:1 Element to be inserted:10

****IMPLEMENTATION OF QUEUE USING POINTERS****


==============================================
MENU
==============================================
[1] To insert an element
[2] To remove an element
[3] To display all the elements
[4] Exit

Enter your choice:1


Element to be inserted:20

****IMPLEMENTATION OF QUEUE USING POINTERS****


==============================================
MENU
==============================================
[1] To insert an element
[2] To remove an element
[3] To display all the elements
[4] Exit

32
Enter your choice:1 Element to be inserted:30

****IMPLEMENTATION OF QUEUE USING POINTERS****


==============================================
MENU
==============================================
[1] To insert an element
[2] To remove an element
[3] To display all the elements
[4] Exit

Enter your choice:1 Element to be inserted:40

****IMPLEMENTATION OF QUEUE USING POINTERS****


==============================================
MENU
==============================================
[1] To insert an element
[2] To remove an element
[3] To display all the elements
[4] Exit

Enter your choice:1 Element to be inserted:50

****IMPLEMENTATION OF QUEUE USING POINTERS****


==============================================
MENU
==============================================
[1] To insert an element
[2] To remove an element
[3] To display all the elements
[4] Exit

Enter your choice:3

Elements present in Queue are:


10 20 30 40 50

****IMPLEMENTATION OF QUEUE USING POINTERS****


==============================================
MENU
==============================================
[1] To insert an element
[2] To remove an element
[3] To display all the elements
[4] Exit
33
Enter your choice:2

10 is removed from the queue

****IMPLEMENTATION OF QUEUE USING POINTERS****


==============================================
MENU
==============================================
[1] To insert an element
[2] To remove an element
[3] To display all the elements
[4] Exit

Enter your choice:3

Elements present in Queue are:


20 30 40 50

****IMPLEMENTATION OF QUEUE USING POINTERS****


==============================================
MENU
==============================================
[1] To insert an element
[2] To remove an element
[3] To display all the elements
[4] Exit

Enter your choice:4

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

Aim: To implement Sorting methods.

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

ii) HEAP SORT


PROGRAM:

#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:

enter the max no. of elements u wanna sort


5
enter the elements u want to sort
10 20 15 6 40
6 10 15 20 40

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

7. Write a program to implement the tree traversal methods.

Aim: To write a C program to implement tree traversal methods.

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:

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 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;

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);
47
else
insertNode(val, pos - median, *newNode, child);

*pval = node->val[node->count];
(*newNode)->link[0] = node->link[node->count];
node->count--;
}

// Set value in node


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 not allowed\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 value
void insert(int val) {
int flag, i;
struct BTreeNode *child;

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


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

// Print the tree


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

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

iii. AVL TREES

PROGRAM:

#include <stdio.h>
#include <stdlib.h>
// Node structure
struct Node {
int key;
struct Node *left;
struct Node *right;
int height;
};

// Function to get the height of the tree


int height(struct Node *N) {
if (N == NULL)
return 0;
return N->height;
}

// Function to get the maximum of two integers


int max(int a, int b) {
return (a > b) ? a : b;
}

// Function to create a new node


struct Node* newNode(int key) {
struct Node* node = (struct Node*)malloc(sizeof(struct Node));
node->key = key;
50
node->left = NULL;
node->right = NULL;
node->height = 1; // New node is initially added at leaf
return(node);
}

// Right rotate subtree rooted with y


struct Node *rightRotate(struct Node *y) {
struct Node *x = y->left;
struct Node *T2 = x->right;

// 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;

// Return new root


return x;
}

// Left rotate subtree rooted with x


struct Node *leftRotate(struct Node *x) {
struct Node *y = x->right;
struct Node *T2 = y->left;

// 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;

// Return new root


return y;
}

// Get balance factor of node N


int getBalance(struct Node *N) {
if (N == NULL)
return 0;
return height(N->left) - height(N->right);
}

// 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));

if (key < node->key)


node->left = insert(node->left, key);
else if (key > node->key)
node->right = insert(node->right, key);
else // Equal keys are not allowed in BST
return node;

// 2. Update height of this ancestor node


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

// 3. Get the balance factor of this ancestor node to check whether this node became unbalanced
int balance = getBalance(node);

// If this node becomes unbalanced, then there are 4 cases

// Left Left Case


if (balance > 1 && key < node->left->key)
return rightRotate(node);

// Right Right Case


if (balance < -1 && key > node->right->key)
return leftRotate(node);

// Left Right Case


if (balance > 1 && key > node->left->key) {
node->left = leftRotate(node->left);
return rightRotate(node);
}

// Right Left Case


if (balance < -1 && key < node->right->key) {
node->right = rightRotate(node->right);
return leftRotate(node);
}

// Return the (unchanged) node pointer


return node;
}

// Function to print preorder traversal of the tree


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

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);

// Print preorder traversal of the AVL tree


printf("Preorder traversal of the constructed AVL tree is \n");
preOrder(root);

return 0;
}

OUTPUT:

Preorder traversal of the constructed AVL tree is


30 20 10 25 40 50

iv. RED-BL:ACK TREES

PROGRAM:

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

// Node structure
typedef struct Node {
int data;
char color;
struct Node *left, *right, *parent;
} Node;

// Function to create a new node


Node* createNode(int data) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
53
newNode->color = 'R'; // New nodes are always red
newNode->left = newNode->right = newNode->parent = NULL;
return newNode;
}

// Function to perform a left rotation


void leftRotate(Node **root, Node *x) {
Node *y = x->right;
x->right = y->left;
if (y->left != NULL)
y->left->parent = x;
y->parent = x->parent;
if (x->parent == NULL)
*root = y;
else if (x == x->parent->left)
x->parent->left = y;
else
x->parent->right = y;
y->left = x;
x->parent = y;
}

// Function to perform a right rotation


void rightRotate(Node **root, Node *y) {
Node *x = y->left;
y->left = x->right;
if (x->right != NULL)
x->right->parent = y;
x->parent = y->parent;
if (y->parent == NULL)
*root = x;
else if (y == y->parent->left)
y->parent->left = x;
else
y->parent->right = x;
x->right = y;
y->parent = x;
}

// Function to fix violations after insertion


void fixViolation(Node **root, Node *z) {
while (z != *root && z->parent->color == 'R') {
if (z->parent == z->parent->parent->left) {
Node *y = z->parent->parent->right;
if (y != NULL && y->color == 'R') {
z->parent->color = 'B';
y->color = 'B';
z->parent->parent->color = 'R';
54
z = z->parent->parent;
} else {
if (z == z->parent->right) {
z = z->parent;
leftRotate(root, z);
}
z->parent->color = 'B';
z->parent->parent->color = 'R';
rightRotate(root, z->parent->parent);
}
} else {
Node *y = z->parent->parent->left;
if (y != NULL && y->color == 'R') {
z->parent->color = 'B';
y->color = 'B';
z->parent->parent->color = 'R';
z = z->parent->parent;
} else {
if (z == z->parent->left) {
z = z->parent;
rightRotate(root, z);
}
z->parent->color = 'B';
z->parent->parent->color = 'R';
leftRotate(root, z->parent->parent);
}
}
}
(*root)->color = 'B';
}

// Function to insert a new node


void insert(Node **root, int data) {
Node *z = createNode(data);
Node *y = NULL;
Node *x = *root;
while (x != NULL) {
y = x;
if (z->data < x->data)
x = x->left;
else
x = x->right;
}
z->parent = y;
if (y == NULL)
*root = z;
else if (z->data < y->data)
y->left = z;
55
else
y->right = z;
fixViolation(root, z);
}

// Function to print the tree (in-order traversal)


void inorder(Node *root) {
if (root == NULL)
return;
inorder(root->left);
printf("%d ", root->data);
inorder(root->right);
}

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:

In-order traversal of the Red-Black Tree: 10 15 20 25 30

9. Write a program to implement the graph traversal methods.

Aim: To write a c program to implement graph traversal methods.

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'));
}

void bfs(int s,int n)


{
int p,i;
add(s);
vis[s]=1;
p=delete();
if(p!=0)
57
printf(" %d",p);
while(p!=0)
{
for(i=1;i<=n;i++)
if((a[p][i]!=0)&&(vis[i]==0))
{
add(i);
vis[i]=1;
}
p=delete();
if(p!=0)
printf(" %d ",p);
}
for(i=1;i<=n;i++)
if(vis[i]==0)
bfs(i,n);
}

void add(int item)


{
if(rear==19)
printf("QUEUE FULL");
else
{
if(rear==-1)
{
q[++rear]=item;
front++;
}
else
q[++rear]=item;
}
}
int delete()
{
int k;
if((front>rear)||(front==-1))
return(0);
else
{
k=q[front++];
return(k);
}
}

void dfs(int s,int n)


{
int i,k;
58
push(s);
vis[s]=1;
k=pop();
if(k!=0)
printf(" %d ",k);
while(k!=0)
{
for(i=1;i<=n;i++)
if((a[k][i]!=0)&&(vis[i]==0))
push(i);
vis[i]=1;
}
k=pop();
if(k!=0)
printf(" %d ",k);
}
for(i=1;i<=n;i++)
if(vis[i]==0)
dfs(i,n);
}
void push(int item)
{
if(top==19)
printf("Stack overflow ");
else
stack[++top]=item;
}
int pop()
{
int k;
if(top==-1)
return(0);
else
{
k=stack[top--];
return(k);
}
}

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

ENTER YOUR CHOICE1


ENTER THE SOURCE VERTEX :2
2 1 3

DO U WANT TO CONTINUE(Y/N) ? y

MENU:
1.B.F.S
2.D.F.S

ENTER YOUR CHOICE2


ENTER THE SOURCE VERTEX :2
2 3 1

DO U WANT TO CONTINUE(Y/N) ? n

10. Implement a Pattern matching algorithm using Boyer- Moore, Knuth-Morris-Pratt

AIM: To implement a Pattern matching algorithm using Boyer- Moore, Knuth-Morris-Pratt

i. Boyer- Moore
PROGRAM:
#include <stdio.h>
60
#include <string.h>

#define NO_OF_CHARS 256

// A utility function to get the 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;
}

// 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];

// Fill the bad character array by calling the preprocessing function


badCharHeuristic(pat, m, badchar);

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


while (s <= (n - m)) {
int j = m - 1;

// 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>

// Function to create the longest prefix suffix (LPS) array


void computeLPSArray(char* pat, int M, int* lps) {
int length = 0;
lps[0] = 0; // lps[0] is always 0
int i = 1;
while (i < M) {
if (pat[i] == pat[length]) {
length++;
lps[i] = length;
i++;
} else {
if (length != 0) {
length = lps[length - 1];
} else {
lps[i] = 0;
i++;
}
}
}
}

// KMP algorithm for pattern searching


void KMPSearch(char* pat, char* txt) {
int M = strlen(pat);
int N = strlen(txt);
int lps[M];
computeLPSArray(pat, M, lps);
int i = 0; // index for txt[]
int j = 0; // index for pat[]
while (i < N) {
if (pat[j] == txt[i]) {
j++;
i++;
}
if (j == M) {
62
printf("Found pattern at index %d\n", i - j);
j = lps[j - 1];
} else if (i < N && pat[j] != txt[i]) {
if (j != 0) {
j = lps[j - 1];
} else {
i = i + 1;
}
}
}
}

int main() {
char txt[] = "ABABDABACDABABCABAB";
char pat[] = "ABABCABAB";
KMPSearch(pat, txt);
return 0;
}

OUTPUT:

Found pattern at index 10

ADDITIONAL PROGRAMS

1. IMPLEMENTATION OF HASH FUNCTIONS AND COLLISION RESOLUTION


TECHNIQUE
63
Aim: To implement hashing technique and collision resolution technique.

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

You might also like