CS3311 Data Structures Record R2021 - 240814 - 111421
CS3311 Data Structures Record R2021 - 240814 - 111421
CS 3311
NAME :
REGISTER NUMBER :
SEMESTER :
DEPARTMENT :
2
THOVALAI-629302
Affiliated to ANNA UNIVERSITY
University Register No
Certified that this Record has been submitted for the Practical Examination held
on .………….
ALGORITHM:
Step 1: Include all the header files and give the maximum size.
Step 2: Define a integer variable 'top' and initialize with '-1'. (int top = -1).
Step 4:Display the menu with list of operations and perform the operation selected by the
user on the stack.
Step 5:Operations:
PROGRAM:
#include<stdio.h>
void main()
{
int a[10]={0},i,top=-1,max=10,n,x;
printf("\n\tMENU\n1.PUSH\n2.POP\n3.DISPLAY\n4.EXIT\n");
do
{
printf("\nEnter your choice\n");
scanf("%d",&n);
switch(n)
{
case 1:
if(top==max-1)
printf("Stack is FULL\n");
5
else
{
printf("Enter the element\n");
scanf("%d",&x);
a[++top]=x;
}
break;
case 2:
if(top<0)
printf("Stack is Empty\n");
else
printf("The deleted item =%d",a[top--]); break;
case 3:
if(top<0)
printf("The stack is empty\n");
else
{
printf("The elements of the stack are :");
for(i=0;i<=top;i++)
printf("%d\n",a[i]);
}
break;
case 4:
break;
default:
printf("Invalid choice\n");
break;
}
}
while(n!=4);
}
6
OUTPUT:
MENU
1.PUSH
2.POP
3.DISPLAY
4.EXIT
Enter your choice
1
Enter the element
2
Enter your choice
1
Enter the element
3
Enter your choice
2
The deleted item =3
Enter your choice
3
The elements of the stack are :2
Enter your choice
4
RESULT:
Thus, the program to implement stack using array in C was executed successfully.
7
AIM:
To implement Queue using array in C.
ALGORITHM:
Step 1: Include all the header files and define the maximum size.
Step 3: Define the integer variables'rear'and ‘front’ and initialize them with '-1'.
Step 4:Display the menu with list of operations and perform the operation selected by the
user on the Queue.
Step 5: Operations:
PROGRAM:
#include <stdio.h>
#define MAX 50
int queue_array[MAX];
int rear = - 1;
int front = - 1;
void main()
{
int choice;
while (1)
{
printf("1.Insert element to queue \n");
printf("2.Delete element from queue \n");
printf("3.Display all elements of queue \n");
printf("4.Quit \n");
printf("Enter your choice : ");
scanf("%d", &choice);
switch (choice)
{
case 1:
insert();
8
break;
case 2:
delete();
break;
case 3:
display();
break;
case 4:
exit(1);
default:
printf("Wrong choice \n");
} /*End of switch*/
} /*End of while*/
} /*End of main()*/
insert()
{
int add_item;
if (rear == MAX - 1)
printf("Queue Overflow \n");
else
{
if (front == - 1)
/*If queue is initially empty */
front = 0;
printf("Insert the element in queue : ");
scanf("%d", &add_item);
rear = rear + 1;
queue_array[rear] = add_item;
}
} /*End of insert()*/
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() */
display()
{
int i;
if (front == - 1|| front > rear)
printf("Queue is empty \n");
else
9
{
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 all elements of queue
4.Quit
Enter your choice : 1
Inset the element in queue : 29
1.Insert element to queue
2.Delete element from queue
3.Display all elements of queue
4.Quit
Enter your choice : 1
Inset the element in queue : 16
1.Insert element to queue
2.Delete element from queue
3.Display all elements of queue
4.Quit
Enter your choice : 1
Inset the element in queue : 4
1.Insert element to queue
2.Delete element from queue
3.Display all elements of queue
4.Quit
Enter your choice : 3
Queue is :
29 16 4
1.Insert element to queue
2.Delete element from queue
3.Display all elements of queue
10
4.Quit
Enter your choice : 2
Element deleted from queue is : 29
1.Insert element to queue
2.Delete element from queue
3.Display all elements of queue
4.Quit
RESULT:
Thus, the program to implement Queue using array in C was executed successfully.
11
AIM:
To implement circular Queue using array in C.
ALGORITHM:
Data Structure: CQ is the array representation of circular queue structure; two pointers
FRONT and REAR of the queue CQ are known.
1. Start
2. Initialize the array of 10 elements name d as cqueue and variables CQ[10], FRONT=-1,
REAR=-1
3. Provide the choice to the users using switch for the different operations on circular
queue like Insert, Delete, Display and Exit Function insert()
4. Check for the overflow condition of the Queue IF (FRONT=(REAR+1)%N) THEN
Print “Queue is full”
5. If not overflow , increment the value of rear REAR = (REAR+1) % N
6. Get the element to be inserted into the queue from the user CQ[REAR] = ITEM
7. Assign it as the last value , CQ[REAR] Function delete()
8. Check for the underflow (empty) condition of the queue
9. If not empty ,Output the element to be deleted from the queue
10.Increment the value of front. FRONT = (FRONT+1) % N Function display()
11. Display the elements of the queue
PROGRAM:
#include <stdio.h>
#define size 5
int front = - 1;
int rear = - 1;
int main()
{
int n, ch;
int queue[size];
12
do
{
}
queue[rear] = item;
}
{
int i;
printf("\n");
if (front > rear)
{
for (i = front; i < size; i++)
{
printf("%d ", queue[i]);
}
for (i = 0; i <= rear; i++)
printf("%d ", queue[i]);
}
else
{
for (i = front; i <= rear; i++)
printf("%d ", queue[i]);
}
}
OUTPUT:
Circular Queue:
1. Insert
2. Delete
3. Display
0. Exit
Enter Choice 0-3? : 1
Enter number: 2
Circular Queue:
1. Insert
2. Delete
3. Display
0. Exit
Enter Choice 0-3? : 1
Enter number: 5
Circular Queue:
1. Insert
2. Delete
3. Display
0. Exit
Enter Choice 0-3? : 3
25
Circular Queue:
1. Insert
2. Delete
3. Display
0. Exit
Enter Choice 0-3? : 2
2 deleted
Circular Queue:
1. Insert
2. Delete
3. Display
0. Exit
Enter Choice 0-3? : 3
5
RESULT:
Thus, the program to implement circular Queue using array in C was executed
successfully.
15
AIM:
To implement Singly Linked List in C.
ALGORITHM:
Step 3:Declare all the functions with which operations are done on the linked list.
Step 4:Display the menu with list of operations and perform the operation selected by the
user on the linked List.
Step 5:Operations:
insert- to insert an element into the linked list in the chosen position.
deletion - to delete an element from the chosen position in the linked list
PROGRAM:
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<process.h>
#define NULL 0
typedefstruct list
{
int no;
struct list *next;
}LIST;
LIST *p,*t,*h,*y,*ptr,*pt;
intj,pos,k=1,count;
16
void main()
{
int n,i=1,opt;
clrscr();
p = NULL;
printf("%d",sizeof(LIST));
printf( "Enter the no of nodes :\n " );
scanf( "%d",&n );
count = n;
while( i <= n)
{
create();
i++;
}
printf("\nEnter your option:\n");
printf("1.Insert \t 2.Delete \t 3.Display \t 4.Exit\n");
do
{
scanf("%d",&opt);
switch( opt )
{
case 1:
insert();
count++;
break;
case 2:
delet();
count--;
if ( count == 0 )
{
printf("\n List is empty\n");
}
break;
case 3:
printf("List elements are:\n");
display();
break;
case 4:
exit(0);
break;
}
printf("\nEnter your option \n");
}while( opt != 4 );
getch();
}
void create ( )
{
if( p== NULL )
{
17
h = p;
}
else
{
t= ( LIST * ) malloc (sizeof( LIST ));
printf( "\nEnter the element" );
scanf( "%d",&t->no );
t->next = NULL;
p->next = t;
p = t;
}
display();
}
void insert()
{
t=h;
p = ( LIST * ) malloc ( sizeof(LIST) );
printf("Enter the element to be inserted:\n");
scanf("%d",&p->no);
printf("Enter the position to insert:\n");
scanf( "%d",&pos );
if( pos == 1 )
{
h = p;
h->next = t;
}
else
{
for(j=1;j<(pos-1);j++)
t = t->next;
p->next = t->next;
t->next = p;
t=p;
}
display();
}
void delet()
{
printf("Enter the position to delete:\n");
scanf( "%d",&pos );
if( pos == 1 )
{
h = h->next ;
18
}
else
{
t= h;
for(j=1;j<(pos-1);j++)
t = t->next;
pt=t->next->next;
free(t->next);
t->next= pt;
}
display();
}
void display()
{
t= h;
while( t->next != NULL )
{
printf("\t%d",t->no);
t = t->next;
}
printf( "\t %d\t",t->no );
}
OUTPUT:
4Enter the no of nodes :
3
Enter the element:
4
4
Enter the element5
4 5
Enter the element6
4 5 6
Enter your option:
1.Insert 2.Delete 3.Display 4.Exit
1
Enter the element to be inserted:
7
Enter the position to insert:
3
19
4 5 7 6
Enter your option
3
List elements are:
4 5 7 6
Enter your option
2
Enter the position to delete:
2
4 7 6
Enter your option
4
RESULT:
Thus, the program to implement List ADT using Linked list in C was executed
successfully.
20
AIM:
To implement stack using Linked List in C.
ALGORITHM:
Step 3:Declare all the functions with which operations are done on the linked list
implementation of stack.
Step 4:Display the menu with list of operations and perform the operation selected by the
user on the linked List implementation of stack.
Step 5:Operations:
PROGRAM:
#include "stdio.h"
#include "stdlib.h"
#include "conio.h"
void pop();
void push(int value);
void display();
struct node
{
int data;
struct node *link;
};
struct node *top=NULL,*temp;
void main()
{
int choice,data;
while(1)
{
21
printf("\n1.Push\n2.Pop\n3.Display\n4.Exit\n");
printf("\nEnterur choice:");
scanf("%d",&choice);
switch(choice)
{
case 1: //To push a new element into stack
}
}
void display()
{
temp=top;
if(temp==NULL)
{
printf("\nStack is empty\n");
}
printf("\n The Contents of the Stack are...");
while(temp!=NULL)
{
printf(" %d ->",temp->data);
temp=temp->link;
}
}
void push(int data)
{
temp=(struct node *)malloc(sizeof(struct node)); // creating a space for the new
element.
temp->data=data;
temp->link=top;
top=temp;
display();
22
void pop()
{
if(top!=NULL)
{
printf("The poped element is %d",top->data);
top=top->link;
}
else
{
printf("\nStack Underflow");
}
display();
}
OUTPUT:
1.Push
2.Pop
3.Display
4.Exit
Enter ur choice:1
1.Push
2.Pop
3.Display
4.Exit
Enter ur choice:1
1.Push
2.Pop
23
3.Display
4.Exit
Enter ur choice:1
Enter a new element :9
The Contents of the Stack are... 9 -> 5 -> 2 ->
1.Push
2.Pop
3.Display
4.Exit
Enter ur choice:3
The Contents of the Stack are... 9 -> 5 -> 2 ->
1.Push
2.Pop
3.Display
4.Exit
Enter ur choice:2
The poped element is 9
The Contents of the Stack are... 5 -> 2 ->
1.Push
2.Pop
3.Display
4.Exit
Enter ur choice:2
The poped element is 5
The Contents of the Stack are... 2 ->
1.Push
2.Pop
3.Display
4.Exit
Enter ur choice:4
RESULT:
Thus, the program to implement stack ADT using Linked list in C was executed
successfully.
24
AIM:
To implement queue using Linked List in C.
ALGORITHM:
Step 3:Declare all the functions with which operations are done on the linked list
implementation of Queue.
Step 4:Display the menu with list of operations and perform the operation selected by the
user on the linked List implementation of Queue.
Step 5:Operations:
PROGRAM:
#include <stdio.h>
#include <stdlib.h>
struct node
{
int info;
struct node *ptr;
}*front,*rear,*temp,*front1;
intfrontelement();
void enq(int data);
void deq();
void empty();
void display();
void create();
void queuesize();
25
int count = 0;
void main()
{
int no, ch, e;
clrscr();
printf("\n 1 - Enque");
printf("\n 2 - Deque");
printf("\n 3 - Front element");
printf("\n 4 - Empty");
printf("\n 5 - Queue size");
printf("\n 6 - Display");
printf("\n 7 - Exit");
create();
while (1)
{
printf("\n Enter choice : ");
scanf("%d", &ch);
switch (ch)
{
case 1:
printf("Enter data : ");
scanf("%d", &no);
enq(no);
break;
case 2:
deq();
break;
case 3:
e = frontelement();
if (e != 0)
printf("Front element : %d", e);
else
printf("\n No front element in Queue as queue is empty");
break;
case 4:
empty();
break;
case 5:
queuesize();
break;
case 6:
display();
break;
case 7:
exit(0);
default:
printf("Wrong choice, Please enter correct choice ");
break;
}
26
}
}
/* Create an empty queue */
void create()
{
front = rear = NULL;
}
void queuesize()
{
printf("\n Queue size : %d", count);
}
/* Enqueing the queue */
void enq(int data)
{
if (rear == NULL)
{
rear = (struct node *)malloc(1*sizeof(struct node));
rear->ptr = NULL;
rear->info = data;
front = rear;
}
else
{
temp=(struct node *)malloc(1*sizeof(struct node));
rear->ptr = temp;
temp->info = data;
temp->ptr = NULL;
rear = temp;
}
count++;
}
/* Displaying the queue elements */
void display()
{
front1 = front;
if ((front1 == NULL) && (rear == NULL))
{
printf("Queue is empty");
return;
}
while (front1 != rear)
{
printf("%d ", front1->info);
front1 = front1->ptr;
}
if (front1 == rear)
printf("%d", front1->info);
}
27
void deq()
{
front1 = front;
if (front1 == NULL)
{
printf("\n Error: Trying to display elements from empty queue");
return;
}
else
if (front1->ptr != NULL)
{
front1 = front1->ptr;
printf("\n Dequed value : %d", front->info);
free(front);
front = front1;
}
else
{
printf("\n Dequed value : %d", front->info);
free(front);
front = NULL;
rear = NULL;
}
count--;
}
/* Returns the front element of queue */
intfrontelement()
{
if ((front != NULL) && (rear != NULL))
return(front->info);
else
return 0;
}
/* Display if queue is empty or not */
void empty()
{
if ((front == NULL) && (rear == NULL))
printf("\n Queue empty");
else
printf("Queue not empty");
}
OUTPUT:
1 - Enque
2 – Deque
28
3 - Front element
4 - Empty
5 - Queue size
6 - Display
7 - Exit
Enter choice : 1
Enter data : 4
Enter choice : 1
Enter data : 5
Enter choice : 1
Enter data : 6
Enter choice : 1
Enter data : 7
Enter choice : 2
Dequed value : 4
Enter choice : 6
567
Enter choice : 3
Front element : 5
Enter choice : 4
Queue not empty
Enter choice : 5
Queue size : 3
Enter choice : 6
567
Enter choice : 7
RESULT:
Thus, the program to implement Queue ADT using Linked list in C was executed
successfully.
29
AIM:
To implement polynomial addition using Linked List in C.
ALGORITHM:
3.If any list is null insert the remaining node of another list in the resultant list.
PROGRAM:
#include<stdio.h>
#include<stdlib.h>
typedef struct link
{
int coeff;
int pow;
struct link * next;
} my_poly;
void my_create_poly(my_poly **);
void my_show_poly(my_poly *);
void my_add_poly(my_poly **, my_poly *, my_poly *);
int main(void)
{
int ch;
do
{
my_poly * poly1, * poly2, * poly3;
printf("\nCreate 1st expression\n");
my_create_poly(&poly1);
printf("\nStored the 1st expression");
my_show_poly(poly1);
}
void my_add_poly(my_poly ** result, my_poly * poly1, my_poly * poly2)
{
my_poly * tmp_node;
}
while(poly1 || poly2)
{
if(poly2)
{
tmp_node->pow = poly2->pow;
tmp_node->coeff = poly2->coeff;
poly2 = poly2->next;
}
}
printf("\nAddition Complete");
OUTPUT:
Create 1st expression
Enter Coeff:2
Enter Pow:3
Continue adding more terms to the polynomial list?(Y = 1/N = 0): 1
Enter Coeff:4
Enter Pow:2
Continue adding more terms to the polynomial list?(Y = 1/N = 0): 0
Stored the 1st expression
The polynomial expression is:
2x^3 + 4x^2
Create 2nd expression
Enter Coeff:4
Enter Pow:3
Continue adding more terms to the polynomial list?(Y = 1/N = 0): 1
Enter Coeff:2
Enter Pow:1
Continue adding more terms to the polynomial list?(Y = 1/N = 0): 0
Stored the 2nd expression
The polynomial expression is:
4x^3 + 2x^1
Addition Complete
The polynomial expression is:
6x^3 + 0x^0 + 2x^1
Add two more expressions? (Y = 1/N = 0):
RESULT:
Thus, the program to implement adding two polynomials using Linked list in C was
executed successfully.
33
ALGORITHM
1. Start the program
2. Define a array stack of size max = 20
3. Initialize top = -1
4. Read the infix expression character-by-character
5. If character is an operand print it
6. If character is an operator
7. Compare the operator’s priority with the stack[top] operator.
8. If the stack [top] operator has higher or equal priority than the input operator,
9. Pop it from the stack and print it.
Else
10. Push the input operator onto the stack
11. If character is a left parenthesis, then push it onto the stack.
12. If the character is a right parenthesis, pop all the operators from the stack and
print it.until a left parenthesis is encountered. Do not print the parenthesis.
PROGRAM:
#include <stdio.h>
#include <conio.h>
#include <string.h>
#define MAX 20
int top = -1;
char stack[MAX];
char pop();
void push(char item);
int prcd(char symbol)
{
switch(symbol)
{
case '+':
case '-':
return 2;
break;
case '*':
case '/':
return 4;
break;
case '^':
case '$':
return 6;
break;
case '(':
case ')':
case '#':
return 1;
34
break;
}
postfix[j] = pop();
j++;
}
push(symbol);
}
}
}
}
while(stack[top] != '#')
{
postfix[j] = pop();
j++;
}
postfix[j] = '\0';
}
main()
{
char infix[20],postfix[20];
clrscr();
printf("Enter the valid infix string: ");
gets(infix);
convertip(infix, postfix);
printf("The corresponding postfix string is: ");
puts(postfix);
getch();
}
void push(char item)
{
top++;
stack[top] = item;
}
char pop()
{
char a;
a = stack[top];
top--;
return a;
}
36
OUTPUT:
RESULT:
Thus the given infix expression was converted into postfix form using stack.
37
AIM
To evaluate the given postfix expression using stack operations.
ALGORITHM
1. Start
2. Define a array stack of size max = 20
3. Initialize top = -1
4. Read the postfix expression character-by-character
If character is an operand push it onto the
stack If character is an operator
Pop topmost two elements from stack.
Apply operator on the elements and push the result onto the
stack,
5. Eventually only result will be in the stack at end of the expression.
6. Pop the result and print it.
7. Stop
PROGRAM:
#include <stdio.h>
#include<conio.h>
struct stack
{
int top; float
a[50];
}s;
38
main()
{
char pf[50]; float
d1,d2,d3; int i;
clrscr();
s.top = -1;
printf("\n\n Enter the postfix expression: "); gets(pf);
for(i=0; pf[i]!='\0'; i++)
{
switch(pf[i])
{
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
s.a[++s.top] =pf[i]-'0'; break;
case '+':
d1 = s.a[s.top--];
d2 = s.a[s.top--]; s.a[++s.top]
= d1 +d2; break;
case '-':
d2 =s.a[s.top--];
d1 =s.a[s.top--];
s.a[++s.top] = d1 -d2;
break;
case '*':
d2 = s.a[s.top--];
d1 = s.a[s.top--];
s.a[++s.top] =d1*d2; break;
case '/':
d2 = s.a[s.top--];
d1 = s.a[s.top--]; s.a[++s.top]
= d1 /d2; break;
}
}
39
OUTPUT:
RESULT:
Ex. No. 6
IMPLEMENTATAION OF BINARY SEARCH TREE
AIM
To insert and delete nodes in a binary search tree.
ALGORITHM
1. Create a structure with key and 2 pointer variable left and right.
2. Read the node to be inserted.
If (root==NULL)
root=node
else if (root->key<node-
>key) root-
>right=NULL
else
Root->left=node
3. For Deletion
if it is a leaf node
Remove immediately
Remove pointer between del node &
child if it is having one child
Remove link between del node&child
Link delnode is child with delnodes
parent
If it is a node with a children
Find min value in right subtree Copy min value to delnode
place Delete the duplicate.
4.Stop.
41
PROGRAM
#include <stdio.h>
#include<stdlib.h>
struct node
{
int key;
struct node *left; struct
node*right;
};
main()
{
struct node *root =NULL; root =
insert(root, 50); root =
insert(root, 30); root =
insert(root, 20); root =
insert(root, 40); root =
insert(root, 70); root =
insert(root, 60); root =
insert(root,80);
printf("Inorder traversal of the given tree \n"); inorder(root);
printf("\nDelete 20\n"); root =
deleteNode(root,20);
printf("Inorder traversal of the modified tree \n"); inorder(root);
printf("\nDelete 30\n"); root =
deleteNode(root,30);
printf("Inorder traversal of the modified tree \n"); inorder(root);
printf("\nDelete 50\n");
43
RESULT:
Thus, the program to implement the operations in Binary Search Tree in C was executed
successfully.
44
AIM:
To implement the operations in AVL Tree using C.
ALGORITHM:
Step 1:Create the AVL tree.
Step 2:Declare all the functions with which operations are done on the AVLtree.
Step 3:Display the menu with list of operations and perform the operation selected by the user on
theAVL tree.
Step 4:Operations
PROGRAM:
#include<stdio.h>
typedefstruct node
{
int data;
struct node *left,*right;
intht;
}node;
int main()
{
node *root=NULL;
45
intx,n,i,op;
do
{
printf("\n1)Create:");
printf("\n2)Insert:");
printf("\n3)Delete:");
printf("\n4)Print:");
printf("\n5)Quit:");
printf("\n\nEnter Your Choice:");
scanf("%d",&op);
switch(op)
{
case 1: printf("\nEnter no. of elements:");
scanf("%d",&n);
printf("\nEnter tree data:");
root=NULL;
for(i=0;i<n;i++)
{
scanf("%d",&x);
root=insert(root,x);
}
break;
return 0;
}
T=(node*)malloc(sizeof(node));
T->data=x;
T->left=NULL;
T->right=NULL;
}
else
if(x > T->data) // insert in right subtree
{
T->right=insert(T->right,x);
if(BF(T)==-2)
if(x>T->right->data)
T=RR(T);
else
T=RL(T);
}
else
if(x<T->data)
{
T->left=insert(T->left,x);
if(BF(T)==2)
if(x < T->left->data)
T=LL(T);
else
T=LR(T);
}
T->ht=height(T);
return(T);
}
if(T==NULL)
{
return NULL;
}
else
if(x > T->data) // insert in right subtree
{
T->right=Delete(T->right,x);
if(BF(T)==2)
if(BF(T->left)>=0)
T=LL(T);
else
T=LR(T);
}
else
if(x<T->data)
{
47
T->left=Delete(T->left,x);
if(BF(T)==-2) //Rebalance during windup
if(BF(T->right)<=0)
T=RR(T);
else
T=RL(T);
}
else
{
//data to be deleted is found
if(T->right!=NULL)
{ //delete its inordersuccesor
p=T->right;
while(p->left!= NULL)
p=p->left;
T->data=p->data;
T->right=Delete(T->right,p->data);
if(T->left==NULL)
lh=0;
else
lh=1+T->left->ht;
if(T->right==NULL)
rh=0;
else
rh=1+T->right->ht;
if(lh>rh)
return(lh);
48
return(rh);
}
return(y);
}
return(T);
}
node * RL(node *T)
{
T->right=rotateright(T->right);
T=rotateleft(T);
return(T);
}
49
if(T->left==NULL)
lh=0;
else
lh=1+T->left->ht;
if(T->right==NULL)
rh=0;
else
rh=1+T->right->ht;
return(lh-rh);
}
OUTPUT
1)Create:
2)Insert:
3)Delete:
4)Print:
5)Quit:
Enter Your Choice:1
Enter no. of elements:4
1)Create:
2)Insert:
3)Delete:
4)Print:
5)Quit:
Enter Your Choice:4
Preorder sequence:
7(Bf=-1)4(Bf=0)12(Bf=1)9(Bf=0)
Inorder sequence:
4(Bf=0)7(Bf=-1)9(Bf=0)12(Bf=1)
1)Create:
2)Insert:
3)Delete:
4)Print:
5)Quit:
Enter a data:7
1)Create:
2)Insert:
3)Delete:
4)Print:
5)Quit:
Preorder sequence:
9(Bf=0)4(Bf=0)12(Bf=0)
Inorder sequence:
4(Bf=0)9(Bf=0)12(Bf=0)
1)Create:
2)Insert:
3)Delete:
4)Print:
5)Quit:
RESULT:
Thus, the program to implement the operations in AVL Tree in C was executed
successfully.
51
AIM:
To implement the Heap using Priority Queue in C.
ALGORITHM:
Step 1:Create the heap using Priority Queue.
Step 2:Declare all the functions with which operations are done on the Priority Queue.
Step 3:Display the menu with list of operations and perform the operation selected by the user on
thePriority Queue.
Step 4:Operations
PROGRAM:
#include<stdio.h>
#include<malloc.h>
void insert();
voiddel();
void display();
struct node
{
int priority;
int info;
struct node *next;
}*start=NULL,*q,*temp,*new;
typedefstruct node N;
void main()
{
intch;
clrscr();
do
{
printf("\n[1] INSERTION\t[2] DELETION\t[3] DISPLAY [4] EXIT\t:");
scanf("%d",&ch);
switch(ch)
{
52
case1:insert();
break;
case2:del();
break;
case3:display();
break;
case4:
break;
}
}
while(ch<4);
}
void insert()
{
intitem,itprio;
new=(N*)malloc(sizeof(N));
printf("ENTER THE ELT.TO BE INSERTED :\t");
scanf("%d",&item);
printf("ENTER ITS PRIORITY :\t");
scanf("%d",&itprio);
new->info=item;
new->priority=itprio;
new->next=NULL;
if(start==NULL )
{
//new->next=start;
start=new;
}
elseif(start!=NULL&&itprio<=start->priority)
{new->next=start;
start=new;
}
else
{
q=start;
while(q->next!= NULL && q->next->priority<=itprio)
{q=q->next;}
new->next=q->next;
q->next=new;
}
}
Void del()
{
if(start==NULL)
{
printf("\nQUEUE UNDERFLOW\n");
}
else
53
{
new=start;
printf("\nDELETED ITEM IS %d\n",new->info);
start=start->next;
//free(start);
}
}
void display()
{
temp=start;
if(start==NULL)
printf("QUEUE IS EMPTY\n");
else
{
printf("QUEUE IS:\n");
if(temp!=NULL)
for(temp=start;temp!=NULL;temp=temp->next)
{
printf("\n%d priority =%d\n",temp->info,temp->priority);
//temp=temp->next;
}
}
}
OUTPUT:
[1] INSERTION [2] DELETION [3] DISPLAY [4] EXIT :1
ENTER THE ELT.TO BE INSERTED : 2
ENTER ITS PRIORITY : 1
[1] INSERTION [2] DELETION [3] DISPLAY [4] EXIT :1
ENTER THE ELT.TO BE INSERTED : 3
ENTER ITS PRIORITY : 2
[1] INSERTION [2] DELETION [3] DISPLAY [4] EXIT :3
QUEUE IS:
2 priority =1
3 priority =2
DELETED ITEM IS 2
3 priority =2
RESULT:
Thus, the program to implement the Heap using Priority Queue in C was executed
successfully.
54
AIM:
To implement the Dijikstras Algorithm to find the shortest path in C.
ALGORITHM:
1. Create cost matrix C[ ][ ] from adjacency matrix adj[ ][ ]. C[i][j] is the cost of going from
vertex i to vertex j. If there is no edge between vertices i and j then C[i][j] is infinity.
4. Create the distance matrix, by storing the cost of vertices from vertex no. 0 to n-1 from the
source vertex 0.
for(i=1;i<n;i++)
distance[i]=cost[0][i];
Initially, distance of source vertex is taken as 0. i.e. distance[0]=0;
5. for(i=1;i<n;i++)
Choose a vertex w, such that distance[w] is minimum and visited[w] is 0. Mark visited[w] as 1.
Recalculate the shortest distance of remaining vertices from the source.
Only, the vertices not marked as 1 in array visited[ ] should be considered for recalculation of
distance. i.e. for each vertex v
if(visited[v]==0)
distance[v]=min(distance[v],
distance[w]+cost[w][v])
PROGRAM:
#include<stdio.h>
#define INFINITY 9999
#define MAX 10
void dijkstra(int G[MAX][MAX],int n,int startnode);
int main()
{
int G[MAX][MAX],i,j,n,u;
scanf("%d",&n);
for(i=0;i<n;i++)
55
for(j=0;j<n;j++)
scanf("%d",&G[i][j]);
scanf("%d",&u);
dijkstra(G,n,u);
return 0;
int cost[MAX][MAX],distance[MAX],pred[MAX];
int visited[MAX],count,mindistance,nextnode,i,j;
for(i=0;i<n;i++)
for(j=0;j<n;j++)
{ if(G[i][j]==0)
cost[i][j]=INFINITY;
else
cost[i][j]=G[i][j];
for(i=0;i<n;i++)
distance[i]=cost[startnode][i];
pred[i]=startnode;
visited[i]=0;
}
56
distance[startnode]=0;
visited[startnode]=1;
count=1;
while(count<n-1)
mindistance=INFINITY;
for(i=0;i<n;i++)
if(distance[i]<mindistance&&!visited[i])
mindistance=distance[i];
nextnode=i;
visited[nextnode]=1;
for(i=0;i<n;i++)
if(!visited[i])
if(mindistance+cost[nextnode][i]<distance[i])
distance[i]=mindistance+cost[nextnode][i];
pred[i]=nextnode;
count++;
for(i=0;i<n;i++)
if(i!=startnode)
{
57
printf("\nDistance of node%d=%d",i,distance[i]);
printf("\nPath=%d",i);
j=i;
do
j=pred[j];
printf("<-%d",j);
}while(j!=startnode);
OUTPUT:
Enter no. of vertices:5
Enter the adjacency matrix:
0 10 0 30 100
10 0 50 0 0
0 50 0 20 10
30 0 20 0 60
100 0 10 60 0
Enter the starting node:0
Distance of node1=10
Path=1<-0
Distance of node2=50
Path=2<-3<-0
Distance of node3=30
Path=3<-0
Distance of node4=60
Path=4<-2<-3<-0
RESULT:
Thus the Shortest path using Dijikstra Algorithm was found successfully.
58
AIM: To write a C program to find minimum spanning tree using Prim’s Algorithm.
ALGORITHM:
Get the number of vertices in the graph and the adjacency matrix.
Choose the edge with minimum distance.
Add it to the minimum spanning tree.
Check the other nodes in the graph which are adjacent to any one of the node in the
minimum spanning tree.
Include the edge which has the minimum cost in the minimum spanning tree it does not
make cycle.
Repeat steps 4 & 5 until all the nodes included in the minimum spanning tree.
PROGRAM:
#include<stdio.h>
int a,b,u,v,n,i,j,ne=1;
int visited[10]={0},min,mincost=0,cost[10][10];
void main()
{
scanf("%d",&n);
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
{
scanf("%d",&cost[i][j]);
if(cost[i][j]==0)
cost[i][j]=999;
}
visited[1]=1;
printf("\n");
while(ne < n)
{
for(i=1,min=999;i<=n;i++)
59
for(j=1;j<=n;j++)
if(cost[i][j]< min)
if(visited[i]!=0)
{
min=cost[i][j];
a=u=i;
b=v=j;
}
if(visited[u]==0 || visited[v]==0)
{
printf("\n Edge %d:(%d %d) cost:%d",ne++,a,b,min);
mincost+=min;
visited[b]=1;
}
cost[a][b]=cost[b][a]=999;
}
printf("\n Minimun cost=%d",mincost);
}
OUTPUT:
Enter the number of nodes:6
Enter the adjacency matrix:
0 3 1 6 00
3 0 5 0 3 0
1 5 0 5 6 4
6 0 5 0 0 2
0 3 6 0 0 6
0 0 4 2 6 0
Edge 1:(1 3) cost:1
Edge 2:(1 2) cost:3
Edge 3:(2 5) cost:3
Edge 4:(3 6) cost:4
Edge 5:(6 4) cost:2
Minimun cost=13
RESULT:
Thus the minimum spanning tree was found using Prim’s Algorithm.
60
ALGORITHM:
Step 2: Compare, the search element with the first element in the list.
Step 3: If both are matching, then display "Given element found!!!" and terminate the
function
Step 4: If both are not matching, then compare search element with the next element in the
list.
Step 5: Repeat steps 3 and 4 until the search element is compared with the last element in
the list.
Step 6: If the last element in the list is also doesn't match, then display "Element not
found!!!" and terminate the function.
PROGRAM:
#include<stdio.h>
void main()
{
int a[10],i,n,c;
printf("Enter the n value:");
scanf("%d",&n);
printf("enter the elements of an array:");
for(i=0;i<=n;i++)
{
scanf("%d",&a[i]);
}
printf("\n Enter the value to search");
scanf("%d",&c);
for(i=0;i<=n;i++)
{
if(c==a[i])
{
printf("\n Element found"); break;
}
}
if(c!=a[i])
printf("\n Element not found");
getch();
}
61
OUTPUT:
RESULT:
Thus, the program toimplement the Linear Search algorithmin C was executed
successfully.
62
AIM
To write a C program to implement the concept of binary search.
ALGORITHM
Step 1: Set the list to be the whole list
Step 2: Find the middle value of the list
Step 3: If the middle value is equal to the target then we declare victory and stop.
Step 4: If the middle item is less than the target, then we set the new list to be the upper half of the
old list and we repeat from step 2 using the new list.
Step 5: If the middle value is greater than the target, then we set the new list to be the bottom half
of the list, and we repeat from step 2 with the new list.
Step 6: Stop
PROGRAM
#include<stdio.h>
void main()
{
int n,i,search,f=0,low,high,mid,a[20];
printf("Enter the n value:");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
printf("Enter the number in ascending order a[%d]=",i);
scanf("%d",&a[i]);
}
printf("Enter the search element:");
scanf("%d",&search);
low=1;
high=n;
while(low<=high)
{
mid=(low+high)/2;
if(search<a[mid])
{
high=mid-1;
}
elseif(search>a[mid])
{
low=mid+1;
}
else{
f=1;
printf("obtained in the position %d:",mid); getch();
exit();
}
}
if(f==0)
printf("not present");
63
OUTPUT
Enter the n value:5
Enter the number in ascending order a[1]=10
Enter the number in ascending order a[2]=8
Enter the number in ascending order a[3]=9
Enter the number in ascending order a[4]=24
Enter the number in ascending order a[5]=1
Enter the search element:9
obtained in the position 3:
RESULT:
Thus, the program to implement the Binary Search algorithm in C was executed
successfully.
64
AIM:
ALGORITHM :
PROGRAM:
#include<stdio.h>
int main()
{
int counter1,counter2,chk,temp_val,val[100];
printf("Please enter the total count of the elements that you want to sort: \n");
scanf("%d",&chk);
printf("Please input the elements that has to be sorted:\n");
for(counter1=0;counter1<chk;counter1++)
{
scanf("%d",&val[counter1]);
}
for(counter1=1;counter1<=chk-1;counter1++)
{
temp_val=val[counter1];
counter2=counter1-1;
while((temp_val<val[counter2])&&(counter2>=0))
{
val[counter2+1]=val[counter2];
counter2=counter2-1;
}
val[counter2+1]=temp_val;
}
printf("\n Output generated after using insertion sort \n");
for(counter1=0;counter1<chk;counter1++)
{
printf("%d ",val[counter1]);
}
65
return 0;
}
Output
RESULT:
Thus, the program to implement the Insertion Sort algorithm in C was executed
successfully.
66
ALGORITHM
ALGORITHM:
Step 1: Get the elements to be sorted as input.
Step 2:Divide the list recursively into two halves until it can no more be divided.
Step 3:Merge the smaller lists into new list in sorted order.
Step 4: Display the sorted list.
PROGRAM:
#include<stdio.h>
#include<conio.h>
void mergesort(int a[],inti,int j);
void merge(int a[],int i1,int j1,int i2,int j2);
int main()
{
int a[30],n,i;
printf("Enter no of elements:");
scanf("%d",&n);
printf("Enter array elements:");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
mergesort(a,0,n-1);
printf("\nSorted array is :");
for(i=0;i<n;i++)
printf("%d ",a[i]);
getch();
return 0;
}
void mergesort(int a[],inti,int j)
{
int mid;
if(i<j)
{
mid=(i+j)/2;
mergesort(a,i,mid); //left recursion
mergesort(a,mid+1,j); //right recursion
merge(a,i,mid,mid+1,j); //merging of two sorted sub-arrays
}
}
void merge(int a[],int i1,int j1,int i2,int j2)
{
int temp[50]; //array used for merging
inti,j,k;
i=i1; //beginning of the first list
68
RESULT:
Thus, the program to implement the Merge Sort algorithm in C was executed successfully.
69
ALGORITHM:
1.Create an array of structure (i.e a hash table).
2. Take a key and a value to be stored in hash table as input.
3. Corresponding to the key, an index will be generated i.e every key is stored in a particular array
index.
4. Using the generated index, access the data located in that array index.
5. In case of absence of data, create one and insert the data item (key and value) into it and
increment the size of hash table.
6. In case the data exists, probe through the subsequent elements (looping back if necessary) for
free space to insert new data item.
Note: This probing will continue until we reach the same element again (from where we began
probing)
7. To display all the elements of hash table, element at each index is accessed (via for loop).
8. To remove a key from hash table, we will first calculate its index and delete it if key matches,
else probe through elements until we find key or an empty space where not a single data has been
entered (means data does not exist in the hash table).
9. Exit
PROGRAM:
#include <stdio.h>
#include<conio.h>
#include<stdlib.h>
#define TABLE_SIZE 10
int h[TABLE_SIZE]={NULL};
void insert()
{
int key,index,i,flag=0,hkey;
printf("Enter a value to insert into hash table: ");
scanf("%d",&key);
hkey=key%TABLE_SIZE;
for(i=0;i<TABLE_SIZE;i++)
{
index=(hkey+i)%TABLE_SIZE;
if(h[index] == NULL)
{
h[index]=key;
break;
}
}
if(i == TABLE_SIZE)
printf("\nElement cannot be inserted!\n");
}
void search()
{
70
int key,index,i,flag=0,hkey;
printf("Enter search element: ");
scanf("%d",&key);
hkey=key%TABLE_SIZE;
for(i=0;i<TABLE_SIZE; i++)
{
index=(hkey+i)%TABLE_SIZE;
if(h[index]==key)
{
printf("Value is found at index: %d",index);
break;
}
}
if(i == TABLE_SIZE)
printf("Value is not found!");
}
void display()
{
int i;
printf("\nElements in the hash table are:");
for(i=0;i< TABLE_SIZE; i++)
printf("\nAt Index: %d \t Value: %d",i,h[i]);
}
main()
{
clrscr();
int opt,i;
while(1)
{
printf("\n1.Insert\n2.Display\n3.Search\n4.Exit\nEnter the choice: ");
scanf("%d",&opt);
switch(opt)
{
case 1:
insert();
break;
case 2:
display();
break;
case 3:
search();
break;
case 4:exit(0);
}
}
}
OUTPUT:
1.Insert
2.Display
3.Search
71
4.Exit
Enter the choice: 1
Enter a value to insert into hash table: 34
1.Insert
2.Display
3.Search
4.Exit
Enter the choice: 1
Enter a value to insert into hash table: 76
1.Insert
2.Display
3.Search
4.Exit
Enter the choice: 1
Enter a value to insert into hash table: 12
1.Insert
2.Display
3.Search
4.Exit
Enter the choice: 2
Elements in the hash table are:
At Index: 0 Value: 0
At Index: 1 Value: 0
At Index: 2 Value: 12
At Index: 3 Value: 0
At Index: 4 Value: 34
At Index: 5 Value: 0
At Index: 6 Value: 76
At Index: 7 Value: 0
At Index: 8 Value: 0
At Index: 9 Value: 0
1.Insert
2.Display
3.Search
4.Exit
Enter the choice: 1
Enter a value to insert into hash table: 50
1.Insert
2.Display
3.Search
4.Exit
Enter the choice: 1
72
RESULT:
Thus the Hashing using Open Addressing with Linear Probing was implemented Successfully.