You are on page 1of 62

Ex.

No: 1a Sorting Using Array

Aim:
To write a C program to sort the given set of numbers using array.
Algorithm:

1. Start the program.


2. Get the number of elements and elements to be sorted in an array.
3. Repeat thru step 7 a total of n-1 times.
4. Record the position of the vector already sorted.
5. Repeat step 6 for the elements in the unsorted portion of the vector.
6. Record location of smallest element in unsorted vector.
7. Exchange first element in unsorted vector with smallest element.
8. Stop the program.

Program:

#include<stdio.h>
#include<conio.h>
void main()
{
int t,a[50],i,j,n;
clrscr();
printf("Enter the limit ");
scanf("%d",&n);
printf("Enter the array elements");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
if(a[i]>a[j])
{
t=a[i];
a[i]=a[j];
a[j]=t;
}
}
}
printf("The sorted array is");
for(i=0;i<n;i++)
printf(" \n %d ",a[i]);
getch();
}

OUTPUT

Enter the limit


5
Enter the array elements
6
1
8
3
7
The sorted array is
1
3
6
7
8

Result:
Thus the program to sort given set of numbers using array was executed and verified.

Ex. No: 1b Linear Search

Aim:
To write a C program to implement linear search.
Algorithm:

1. Start the program.


1. Get the number of elements and elements in an array.
2. Repeat thru step 3 a total of n-1 times.
3. Get the element to be searched
4. Display the position of the element in the array else display element not found
5. Stop the program.
Program:

#include<stdio.h>
#include<conio.h>
void main()
{
int i,c,a[30],n,k;
clrscr();
printf("Enter the no.of elements:\n");
scanf("%d",&n);
printf("Enter the elements:\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("Enter the number to be searched:\n");
scanf("%d",&k);
for(i=0;i<n;i++)
{
if(a[i]==k)
{
c=1;
printf("\n The number was found & its position is %d ", k,i+1);
}

if(c!=1)
printf("\n The number was not found\n");
getch();
}

SAMPLE OUTPUT:

Enter the no.of elements


4
Enter the elements
32
43
54
90
Enter the number to be searched
43

The number was found and its position is 2

Result:
Thus the program to implement linear search was executed and verified.

Ex. No:1c Array Implementation of List

Aim:
To write a C program to implement list using array.

Algorithm:
1. Start the program.
2. Create a structure with required data fields.
3. Get the choice of operations either insertion, deletion or modification
4. For insertion get the element to be inserted with required data and insert the element in the
array.
5. For deletion get the element to be deleted and move all the elements above it one step down.
6. For modification get the element to be modified and replace that with the new element in the
same position.
7. Using display option, list the elements of the list.
8. Stop the program.

Program:
#include<stdio.h>
#include<conio.h>
static top=0;
const max=50;
struct stack
{
int no;
}st[50];
void push()
{
int num;
if(top>=max)
printf("Stack is full\n");
else
{
printf("Enter the number\n");
scanf("%d",&num);
st[to p].no=num;
top=top+1;
}
}
void pop()
{
int num,x;
if(top!=NULL)
{
top=top-1;
x=1;
if(x==1)
printf("%d is poped",st[top].no);
}
else
printf("The stack is empty\n");
}
void disp()
{
int i;
if(top!=NULL)
{
for(i=0;i<top;i++)
printf("%d\t",st[i].no);
}
else
printf("The stack is empty\n");
}
void main()
{
int ch;
char a='y';
clrscr();
do
{
printf("\n1.push\t2.pop\t3.display\t4.exit");
printf("\nEnter your choice\n");
scanf("%d",&ch);
switch(ch)
{
case 1:
push();
break;
case 2:
pop();
break;
case 3:
disp();
break;
case 4:
exit();
break;
default:
printf("Enter correct choice\n");
break;
}
printf("\n Do you want to continue(y/n):");
a=getch();
}while(a=='y');
getch();
}

Output:

1.push 2.pop 3.display 4.exit


Enter your choice
1
Enter the number
11

Do you want to continue(y/n):


1.push 2.pop 3.display 4.exit
Enter your choice
1
Enter the number
22

Do you want to continue(y/n):


1.push 2.pop 3.display 4.exit
Enter your choice
1
Enter the number
33

Do you want to continue(y/n):


1.push 2.pop 3.display 4.exit
Enter your choice
3
11 22 33
Do you want to continue(y/n):
1.push 2.pop 3.display 4.exit
Enter your choice

2
33 is poped
Do you want to continue(y/n):
1.push 2.pop 3.display 4.exit
Enter your choice
3
11 22
Do you want to continue(y/n):
1.push 2.pop 3.display 4.exit
Enter your choice
2
22 is poped
Do you want to continue(y/n):
1.push 2.pop 3.display 4.exit
Enter your choice
3
11
Do you want to continue(y/n):
1.push 2.pop 3.display 4.exit
Enter your choice
2
11 is poped
Do you want to continue(y/n):
1.push 2.pop 3.display 4.exit
Enter your choice
2
The stack is empty

Do you want to continue(y/n):

Result:
Thus the program to implement list using array was executed and verified.
Ex. No:2 Singly Linked List

Aim:
To write a C program to implement a singly linked list.

Algorithm:
1. Start the program.
2. Create a node with two fields’ data and link field.
 Allocate space for the node dynamically.
 Create link between the created nodes and let the last node be with NULL Link
 Insert the input data in the data field and press –1 to stop the same.
3. Get the choice of operations either insertion or deletion.
4. For insertion get the position in which insertion is to be done and the element to be inserted.
Check for the start, middle or end position of insertion. Insert the node and change its link
accordingly.
5. For deletion get the position in which deletion is to be done. Delete the node and then link it
to the next node. Before deletion check whether there is data in the list to be deleted.
6. Using display option list the elements of the list.
7. Stop the program.

Program:

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
};
struct node *head,*temp;
void display();
void add()
{
struct node *add;
add=(struct node*)malloc(sizeof(struct node));
printf("Enter the data\n");
scanf("%d",&add->data);
if(head==NULL)
{
head=add;
head->next=NULL;
temp=add;
}
else
{
temp->next=add;
add->next=NULL;
temp=add;
}
/*display();*/
}
void dele()
{
struct node *del;
int num,found=0;
printf("Enter the number to be deleted\n");
scanf("%d",&num);
for(del=head;del!=NULL;del=del->next)
{
if(head->data==num)
{
head=head->next;
found=1;
}
else if(del->next->data==num)
{
del->next=del->next->next;
found=1;
}
}
if(found==1)
printf("%d was deleted\n",num);
}
void insert()
{
struct node *ins,*trav;
int no,x;
ins=(struct node*)malloc(sizeof(struct node));
printf("Enter the data after which the new data has to be entered\n");
scanf("%d",&no);
printf("Enter the data to be inserted\n");
scanf("%d",&ins->data);
for(trav=head;trav!=NULL;trav=trav->next)
{
if(trav->data==no)
{
ins->next=trav->next;
trav->next=ins;
x=1;
}
}
if(x==1)
printf("The number has been inserted\n");
}
void modify()
{
struct node *mod,*data;
int x,num,no;
printf("Enter the number to be modified\n");
scanf("%d",&no);
printf("Enter the new number\n");
scanf("%d",&num);
for(mod=head;mod!=NULL;mod=mod->next)
{
if(mod->data==no)
{
mod->data=num;
x=1;
}
}
if(x==1)
printf("The number has been modified\n");
}
void display()
{
struct node *disp;
if(head==NULL)
printf("The list is empty\n");
else
{
for(disp=head;disp!=NULL;disp=disp->next)
{
printf("%d\t",disp->data);
}
}
}
void main()
{
int ch;
char a='y';
clrscr();
printf("1.Add\t2.Delete\t3.Insert\t4.Modify\t5.Display");
do
{
printf("\nEnter the choice\n");
scanf("%d",&ch);
switch(ch)
{
case 1:
add();
break;
case 2:
dele();
break;
case 3:
insert();
break;
case 4:
modify();
break;
case 5:
display();
break;
default:
printf("\nEnter correct choice\n");
}
printf("\nDo you want to continue(y/n):\n");
a=getch();
}while(a=='y');
getch();}

Output:
1.Add 2.Delete 3.Insert 4.Modify 5.Display
Enter the choice
1
Enter the data
11
Do you want to continue(y/n):
Enter the choice
1
Enter the data
22
Do you want to continue(y/n):
Enter the choice
5
11 22
Do you want to continue(y/n):

Enter the choice


3
Enter the data after which the new data has to be entered
11
Enter the data to be inserted
33
The number has been inserted

Do you want to continue(y/n):


Enter the choice
5
11 33 22
Do you want to continue(y/n):
Enter the choice
4
Enter the number to be modified
22
Enter the new number
44
The number has been modified
Do you want to continue(y/n):
Enter the choice
5
11 33 44
Do you want to continue(y/n):n

Result:
Thus the program to implement singly linked list was executed and verified.
Ex.No.3 DOUBLY LINKED LIST
Aim:
To write a C program to implement a doubly linked list.
Algorithm:
1. Start the program.
2. Create a node with three fields data, next and previous field.
 Allocate space for the node dynamically.
 Create link between the created nodes. Let the next pointer of the last node be with
NULL Link and previous pointer of the first node be with NULL link.
 Insert the input data in the data field.
3. Get the choice of operations either insertion or deletion.
4. For insertion get the element after which insertion is to be done and the element to be
inserted. Check for the middle or end position of insertion. Insert the node and change its
link accordingly.
5. For insertion in the first position make the new node as head and change the link
accordingly.
6. For deletion get the element of the node which is to be deleted. Delete the node and change
the link accordingly. Before deletion check whether there is data in the list to be deleted.
7. Using display option, list the elements of the list.
8. Stop the program.
Program:
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
struct node *prev;
};
struct node *head,*temp,*tail;
void createlist()
{
struct node *add;
int n,i;
printf("enter the numberof elements:");
scanf("%d",&n);
for (i=0;i<n;i++)
{
add=(struct node*)malloc(sizeof(struct node));
printf("Enter the data\n");
scanf("%d",&add->data);
if(head==NULL)
{
head=add;
head->next=NULL;
head->prev=NULL;
temp=add;
}
else
{
temp->next=add;
add->prev=head;
add->next=NULL;
temp=add;
}
}
}
void dele()
{
struct node *del,*delnode;
int num,found=0;
printf("Enter the number to be deleted\n");
scanf("%d",&num);
for(del=head;del!=NULL;del=del->next)
{
if(head->data==num)
{
head=head->next;
head->prev=NULL;
found=1;

}
else if(del->next->data==num)
{
delnode=del->next;
del->next=delnode->next;
delnode->next->prev=del;
found=1;
}
}
if(found==1)
printf("%d was deleted\n",num);
}
void insert()
{
struct node *ins,*trav;
int no,x;
ins=(struct node*)malloc(sizeof(struct node));
printf("Enter the data after which the new data has to be entered\n");
scanf("%d",&no);
printf("Enter the data to be inserted\n");
scanf("%d",&ins->data);
for(trav=head;trav!=NULL;trav=trav->next)
{
if(trav->data==no)
{
ins->next=trav->next;
trav->next->prev=ins;
trav->next=ins;
ins->prev=trav;
x=1;
}
}
if(x==1)
printf("The number has been inserted\n");
}
void insfirst()
{
struct node *ins,*trav;
int no,x;
ins=(struct node*)malloc(sizeof(struct node));
printf("Enter the data to be inserted\n");
scanf("%d",&ins->data);
ins->next=head;
head->prev=ins;
ins->prev=NULL;
head=ins;
printf("The number has been inserted\n");
}
void display()
{
struct node *disp;
if(head==NULL)
printf("The list is empty\n");
else
{
for(disp=head;disp!=NULL;disp=disp->next)
{
printf("%d\t",disp->data);
}
}}
void main()
{
int ch;
char a='y';
clrscr();
printf("1.Createlist \t2.Delete\t3.Insert\t4.Insfirst\t5.Display");
do
{
printf("\nEnter the choice\n");
scanf("%d",&ch);
switch(ch)
{
case 1:
createlist();
break;
case 2:
dele();
break;
case 3:
insert();
break;
case 4
Insfirst();
break;
case 5:
display();
break;
default:
printf("\nEnter correct choice\n");
}
printf("\nDo you want to continue(y/n):\n");
a=getch();
}while(a=='y');
getch();}

Output:
1.Createlist 2.Delete 3.Insert 4.Insfirst 5.Display
Enter the choice1
enter the numberof elements:3
Enter the data
11
Enter the data
22
Enter the data
33
Do you want to continue(y/n):
Enter the choice
5
11 22 33
Do you want to continue(y/n):
Enter the choice3
Enter the data after which the new data has to be entered
22
Enter the data to be inserted
44
The number has been inserted
Do you want to continue(y/n):
Enter the choice
5
11 22 44 33
Do you want to continue(y/n):
Enter the choice4
Enter the data to be inserted
88
The number has been inserted
Do you want to continue(y/n):
Enter the choice
5
88 11 22 44 33
Do you want to continue(y/n):
Enter the choice2
Enter the number to be deleted
11
11 was deleted
Do you want to continue(y/n):
Enter the choice
5
88 22 44 33
Do you want to continue(y/n):

Result:
Thus the program to implement doubly linked list was executed and verified.
EX.No:4 POLYNOMIAL ADDITION

Aim:
To write a C program to represent polynomials as linked list and to add two polynomials.

Algorithm:

1: Read the coefficient and power of the polynomial equation one and assign its
elements into a linked list.
2: Read the coefficient and power of the polynomial equation two and assign it's
elements into a linked list.
3: Sorting the first polynomial in power order wise.Compare the first node's power with next
nodes power, if second node's power is greater than first Node then swap. Repeat the process
until we get the proper order.
4: Sorting the second polynomial in power order wise.
Compare the first node's power with next nodes power, if second node's power is greater
than first Node then swap. Repeat the process until we get the proper order.
5: If power part of the two list is Equal than add the coefficient.
6: Display the result of polynomial addition.

Program:
#include<stdio.h>
#include<conio.h>
struct poly
{
int coff;
int pow;
struct poly *link;
}*ptr,*start1,*node,*start2,*start3,*ptr1,*ptr2;
typedef struct poly pol;
int temp1,temp2;

void main()
{

void create(void);
void display(void);
void polyaddtion(void);
void sorting(void);
clrscr();

printf("\n\nEnrter the elements of the first poly");


node = (pol *) malloc(sizeof (pol));
start1=node;
if (start1==NULL)
{
printf("\n\nUnable to create memory.");
getch();
exit();
}
create();
printf("\n\nEnrter the elements of the second poly :");
node = (pol *) malloc(sizeof (pol));
start2=node;
if (start2==NULL)
{
printf("\n\nUnable to create memory.");
getch();
exit();
}
create();
clrscr();
//printing the elements of the lists
printf("\n\nThe elements of the poly first are :");
ptr=start1;
display();

printf("\n\nThe elements of the poly second are :");


ptr=start2;
display();

printf("\n\nThe first sorted list is :");


ptr=start1;
sorting();
ptr=start1;
display();

printf("\n\nThe second sorted list is :");


ptr=start2;
sorting();
ptr=start2;
display();

printf("\n\nThe sum of the two lists are :");


polyaddtion();
ptr=start3;
display();

getch();

/*----------------------------------------------------------------------------------------------------------------*/
void create()
{
char ch;
while(1)
{
printf("\n\nEnter the coff and pow :");
scanf("%d%d",&node->coff,&node->pow);
if (node->pow==0 )
{
ptr=node;
node=(pol *)malloc(sizeof(pol));
node=NULL;
ptr->link=node;
break;
}

printf("\n\nDo u want enter more coff ?(y/n)");


fflush(stdin);
scanf("%c",&ch);
if (ch=='n' )
{
ptr=node;
node=(pol *)malloc(sizeof(pol));
node=NULL;
ptr->link=node;
break;
}
ptr=node;
node=(pol *)malloc(sizeof(pol));
ptr->link=node;
}
}
/*-------------------------------------------------------------------------------------------------------------*/
void display()
{ int i=1;

while(ptr!=NULL )
{
if(i!=1)
printf("+ ");
printf(" %dx^%d ",ptr->coff,ptr->pow);
ptr=ptr->link;
i++;
}
}
/*------------------------------------------------------------------------------------------------------------*/
void sorting()
{
for(;ptr->coff!=NULL;ptr=ptr->link)
for(ptr2=ptr->link;ptr2->coff!=NULL;ptr2=ptr2->link)
{
if(ptr->pow>ptr2->pow)
{
temp1=ptr->coff;
temp2=ptr->pow;
ptr->coff=ptr2->coff;
ptr->pow=ptr2->pow;
ptr2->coff=temp1;
ptr2->pow=temp2;

}
}
}
/*----------------------------------------------------------------------------------------------------------*/
void polyaddtion()
{
node=(pol *)malloc (sizeof(pol));
start3=node;

ptr1=start1;
ptr2=start2;

while(ptr1!=NULL && ptr2!=NULL)


{
ptr=node;
if (ptr1->pow > ptr2->pow )
{
node->coff=ptr2->coff;
node->pow=ptr2->pow;
ptr2=ptr2->link; //update ptr list B
}
else if ( ptr1->pow < ptr2->pow )
{
node->coff=ptr1->coff;
node->pow=ptr1->pow;
ptr1=ptr1->link; //update ptr list A
}
else
{
node->coff=ptr2->coff+ptr1->coff;
node->pow=ptr2->pow;
ptr1=ptr1->link; //update ptr list A
ptr2=ptr2->link; //update ptr list B

node=(pol *)malloc (sizeof(pol));


ptr->link=node; //update ptr list C
}//end of while

if (ptr1==NULL) //end of list A


{
while(ptr2!=NULL)
{
node->coff=ptr2->coff;
node->pow=ptr2->pow;
ptr2=ptr2->link; //update ptr list B
ptr=node;
node=(pol *)malloc (sizeof(pol));
ptr->link=node; //update ptr list C
}
}

else if (ptr2==NULL) //end of list B


{
while(ptr1!=NULL)
{
node->coff=ptr1->coff;
node->pow=ptr1->pow;
ptr1=ptr1->link; //update ptr list B
ptr=node;
node=(pol *)malloc (sizeof(pol));
ptr->link=node; //update ptr list C
}
}
node=NULL;
ptr->link=node;
}

Output:

Enrter the elements of the first poly


Enter the coff and pow :2 3
Do u want enter more coff ?(y/n)y
Enter the coff and pow :4 3
Do u want enter more coff ?(y/n)y
Enter the coff and pow :1 2
Do u want enter more coff ?(y/n)n

Enter the elements of the second poly :


Enter the coff and pow :2 4
Do u want enter more coff ?(y/n)y
Enter the coff and pow :2 1
Do u want enter more coff ?(y/n)y
Enter the coff and pow :1 2
Do u want enter more coff ?(y/n)

The elements of the poly first are : 2x^4 + 4x^3 + 1x^2


The elements of the poly second are : 2x^4 + 2x^1 + 1x^2
The first sorted list is : 1x^2 + 4x^3 + 2x^4
The second sorted list is : 2x^1 + 1x^2 + 2x^4
The sum of the two lists are : 2x^1 + 2x^2 + 4x^3 + 4x^4

Result:
Thus the program to represent polynomials as linked list and to add two polynomials
was executed and verified.

EX.No.5a ARRAY IMPLEMENTATION - STACK

Aim:
To create stack and to perform push and pop operations on it.

Algorithm:

1. Start the program.


2. Get the choice of operation either push or pop.
3. To insert an element into the stack do as follows.
a. Check for the array size of the stack, if full then no element can be inserted.
b. Otherwise Increment the top by one and increment top point by one.
4. To delete an element from the stack do as follows.
a. Check the stack for any element, if empty then no element can be deleted.
b. Otherwise delete the element and decrement top point by one.
5. Display the elements from top list.
6. Stop the program.

Program:
#include<stdio.h>
#include<conio.h>
static top=0;
const max=50;
struct stack
{
int no;
}st[50];
void push()
{
int num;
if(top>=max)
printf("Stack is full\n");
else
{
printf("Enter the number\n");
scanf("%d",&num);
st[to p].no=num;
top=top+1;
}
}
void pop()
{
int num,x;
if(top!=NULL)
{
top=top-1;
x=1;
if(x==1)
printf("%d is poped",st[top].no);
}
else
printf("The stack is empty\n");
}
void disp()
{
int i;
if(top!=NULL)
{
for(i=0;i<top;i++)
printf("%d\t",st[i].no);
}
else
printf("The stack is empty\n");
}
void main()
{
int ch;
char a='y';
clrscr();
do
{
printf("\n1.push\t2.pop\t3.display\t4.exit");
printf("\nEnter your choice\n");
scanf("%d",&ch);
switch(ch)
{
case 1:
push();
break;
case 2:
pop();
break;
case 3:
disp();
break;
case 4:
exit();
break;
default:
printf("Enter correct choice\n");
break;
}
printf("\n Do you want to continue(y/n):");
a=getch();
}while(a=='y');
getch();
}

Output:

1.push 2.pop 3.display 4.exit


Enter your choice
1
Enter the number
11

Do you want to continue(y/n):


1.push 2.pop 3.display 4.exit
Enter your choice
1
Enter the number
22

Do you want to continue(y/n):


1.push 2.pop 3.display 4.exit
Enter your choice
3
11 22
Do you want to continue(y/n):
1.push 2.pop 3.display 4.exit
Enter your choice
2
22 is poped
Do you want to continue(y/n):
1.push 2.pop 3.display 4.exit
Enter your choice
2
11 is poped
Do you want to continue(y/n):
1.push 2.pop 3.display 4.exit
Enter your choice
2
The stack is empty

Do you want to continue(y/n):

Result:

Thus the program to create stack and to perform push and pop operations was executed and
verified.

EX.NO:5b LINKED LIST IMPLEMENTATION – STACK

Aim:

To write a C program to implement the Stack using linked list.

Algorithm:

1. Start the program.


2. Create a node with two fields data and link field.
 Allocate space for the node dynamically.
 Create link between the created nodes and let the last node be with NULL link
3. Get the choice of operations either insertion or deletion.
4. To insert an element into the stack do as follows.
a. Insert the node at the first and change the node accordingly.
5. To delete an element from the stack do as follows.
b. Check the stack for any element, if empty then no element can be deleted.
c. Otherwise delete the first node and set the next node as the head node
6. Display the elements from top list.
7. Stop the program.

Program:
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
struct stack
{
int data;
struct stack *next;
};
struct stack *head;
void push()
{
struct stack *push;
push=(struct stack*)malloc(sizeof(struct stack));
printf("Enter the item to be inserted\n");
scanf("%d",&push->data);
if(head==NULL)
{
head=push;
head->next=NULL;
}
else
{
push->next=head;
head=push;
}

}
void pop()
{
struct stack *pop;
if(head==NULL)
printf("The stack is empty\n");
else
{
printf("The poped item is %d",head->data);
head=head->next;
}
}
void display()
{
struct stack *p;
p=(struct stack*)malloc(sizeof(struct stack));
if(head==NULL)
printf("The stack is empty\n");
else
p=head;
while(p!=NULL)
{
printf("%d\n",p->data);
p=p->next;
}
}
void modify()
{
struct stack *mod,*data;
int x,num,no;
printf("Enter the number to be modified\n");
scanf("%d",&no);
printf("Enter the new number\n");
scanf("%d",&num);
for(mod=head;mod!=NULL;mod=mod->next)
{
if(mod->data==no)
{
mod->data=num;
x=1;
}
}
if(x==1)
printf("The number has been modified\n");
}
void main()
{
int ch;
char a='y';
clrscr();
printf("1.PUSH\t2.POP\t3.DISPLAY\t4.MODIFY\t5.EXIT\t");
do
{
printf("\nEnter the choice\n");
scanf("%d",&ch);
switch(ch)
{
case 1:
push();
break;
case 2:
pop();
break;
case 3:
display();
break;
case 4:
modify();
break;
default:
printf("\nEnter correct choice\n");
}
printf("\nDo you want to continue(y/n):\n");
a=getch();
}while(a=='y');
getch();
}

Output:
1.PUSH 2.POP 3.DISPLAY 4.MODIFY 5.EXIT
Enter the choice
1
Enter the item to be inserted
11

Do you want to continue(y/n):

Enter the choice


1
Enter the item to be inserted
22

Do you want to continue(y/n):

Enter the choice


3
22
11

Do you want to continue(y/n):

Enter the choice


4
Enter the number to be modified
22
Enter the new number
66
The number has been modified

Do you want to continue(y/n):

Enter the choice


3
66
11

Do you want to continue(y/n):

Enter the choice


2
The poped item is 66
Do you want to continue(y/n):

Enter the choice


2
The poped item is 11
Do you want to continue(y/n):

Enter the choice


2
The stack is empty

Do you want to continue(y/n):n

Result:
Thus the program to implement stack using linked list was executed and verified.

EX.No:6 INFIX TO POSTFIX CONVERSION USING STACK IMPLEMENTATION

Aim:
To convert infix expression into postfix expression using stack implementation.

Algorithm:

1. Start the program.


2. Include stack using arrays implementation program as header file.
3. Get the Infix string from left to right.
4. Initialize an empty stack. If the scanned character is an operand, add it to the output stack.
If the scanned character is an operator and if the stack is empty Push the character to stack.
5. If the scanned character is an Operand and the stack is not empty, compare the precedence
of the character with the element on top of the stack (topStack). If topStack has higher
precedence over the scanned character Pop the stack else Push the scanned character to
stack. Repeat this step as long as stack is not empty and topStack has precedence over the
character.
6. Repeat this step till all the characters are scanned.
7. (After all characters are scanned, we have to add any character that the stack may have to
the Postfix string.) If stack is not empty add topStack to Postfix string and Pop the stack.
Repeat this step as long as stack is not empty.
8. Return the Postfix string.
9. Stop the program.

Program:

#include<stdio.h>
#include<conio.h>
#include<alloc.h>
#include<ctype.h>
#include<string.h>
#include"stack.h"
int weight(char c)
{
if(c=='+'||c=='-')
return 1;
else if(c=='*'||c=='/')
return 2;
else
return 3;
}
int islow(char c,char d)
{
if(weight(c)<weight(d))
return 1;
else
return 0;
}
int isoperator(char c)
{
switch(c)
{
case '+':
case '-':
case '*':
case '/':
case '=':
return 1;
default:
return 0;
}
}
void main()
{
char iput[20],oput[20],c;
int len,j,k;
clrscr();
printf("enter the infix expression\n");
scanf("%s",iput);
len=strlen(iput);
iput[len]=')';
iput[++len]='\o';
j=0;
k=0;
push('(');
do
{
c=iput[j];
if(isalpha(c))
{
oput[k]=c;
k++;
}
else if(c=='(')
push(c);
else if(isoperator(c))
{
while(isoperator(tos())&&islow(c,tos()))
{
oput[k]=pop();
k++;
}
push(c);
}
else if(c==')')
{
while(tos()!='(')
{
oput[k]=pop();
k++;
}

pop();
}
j++;
}while(tos()!=NULL);
oput[k]='\o';
printf("\n postfix form is %s",oput);
getch();
}
Stack.h
#include<stdio.h>
#include<conio.h>
#include<alloc.h>
struct stack
{
char data;
struct stack *next;
}*p,*temp;
struct stack *head=NULL;
push(char c)
{
temp=malloc(sizeof(struct stack));
temp->data=c;
if(head==NULL)
{
head=temp;
temp->next=NULL;
}
else
{
temp->next=head;
head=temp;
}
return;
}
char pop()
{
char retval;
p=head;
if(head==NULL)
printf("stack is empty");
else
{
head=head->next;
retval=p->data;
free(p);
}
return(retval);
}
char tos()
{
return(head->data);
}

Output:

Enter the infix expression (a+b)*c


Postfix form is ab+c*

Result:
Thus the program to convert infix expression into postfix expression using stack was
executed and output is verified.
EX.NO:7 CIRCULAR QUEUE

Aim:
To write a C program to implement Circular queue.
Algorithm:
1. Start the program.
2. Initialize the rear and front as -1.
3. Get the choice of operation
4. To enqueue an element check the queue size is not full and insert the element in the rear end
by incrementing the rear value.
5. To Dequeue an element Check the queue is not empty and delete the element by incrementing
the front value.
6. Display the elements
7. Terminate the program.
Program:
# include<stdio.h>
# define MAX 5

int cqueue_arr[MAX];
int front = -1;
int rear = -1;

void main()
{
int choice;
clrscr();
while(1)
{
printf("\n1.Insert\n");
printf("2.Delete\n");
printf("3.Display\n");
printf("4.Quit\n");
printf("\nEnter your choice : ");
scanf("%d",&choice);

switch(choice)
{
case 1 :
insert();
break;
case 2 :
del();
break;
case 3:
display();
break;
case 4:
exit(1);
default:
printf("\nWrong choice\n");
}/*End of switch*/
}/*End of while */
}/*End of main()*/

insert()
{
int added_item;
if((front == 0 && rear == MAX-1) || (front == rear+1))
{
printf("Queue Overflow \n");
return;
}
if (front == -1) /*If queue is empty */
{
front = 0;
rear = 0;
}
else
if(rear == MAX-1)/*rear is at last position of queue */
rear = 0;
else
rear = rear+1;
printf("Input the element for insertion in queue : ");
scanf("%d", &added_item);
cqueue_arr[rear] = added_item ;
printf("\nFront:%d\n",front);
printf("\nRear :%d\n",rear);
}/*End of insert()*/
del()
{
if (front == -1)
{
printf("Queue Underflow\n");
return ;
}
printf("Element deleted from queue is : %d\n",cqueue_arr[front]);
if(front == rear) /* queue has only one element */
{
front = -1;
rear=-1;
}
else
if(front == MAX-1)
front = 0;
else
front = front+1;
printf("\nFront:%d\n",front);
printf("\nRear :%d\n",rear);
}/*End of del() */

display()
{
int front_pos = front,rear_pos = rear;
if(front == -1)
{
printf("Queue is empty\n");
return;
}
printf("Queue elements :\n");
if( front_pos <= rear_pos )
while(front_pos <= rear_pos)
{
printf("%d ",cqueue_arr[front_pos]);
front_pos++;
}
else
{
while(front_pos <= MAX-1)
{
printf("%d ",cqueue_arr[front_pos]);
front_pos++;
}
front_pos = 0;
while(front_pos <= rear_pos)
{
printf("%d ",cqueue_arr[front_pos]);
front_pos++;
}
}/*End of else */
printf("\n");
getch();
}/*End of display() */

OUTPUT:

1.Insert
2.Delete
3.Display
4.Quit

Enter your choice : 1


Input the element for insertion in queue : 1

Front:0
Rear :0

1.Insert
2.Delete
3.Display
4.Quit

Enter your choice : 1


Input the element for insertion in queue : 2

Front:0
Rear :1

1.Insert
2.Delete
3.Display
4.Quit
Enter your choice : 1
Input the element for insertion in queue : 3

Front:0
Rear :2

1.Insert
2.Delete
3.Display
4.Quit

Enter your choice : 1


Input the element for insertion in queue : 4

Front:0
Rear :3

1.Insert
2.Delete
3.Display
4.Quit

Enter your choice : 1


Input the element for insertion in queue : 5

Front:0
Rear :4

1.Insert
2.Delete
3.Display
4.Quit

Enter your choice : 1


Queue Overflow

1.Insert
2.Delete
3.Display
4.Quit

Enter your choice : 2


Element deleted from queue is : 1

Front:1
Rear :4

1.Insert
2.Delete
3.Display
4.Quit
Enter your choice : 2
Element deleted from queue is : 2

Front:2
Rear :4

1.Insert
2.Delete
3.Display
4.Quit
Enter your choice : 2
Element deleted from queue is : 3

Front:3
Rear :4

1.Insert
2.Delete
3.Display
4.Quit

Enter your choice : 2


Element deleted from queue is : 4

Front:4
Rear :4

1.Insert
2.Delete
3.Display
4.Quit

Enter your choice : 2


Element deleted from queue is : 5

Front:-1
Rear :-1
1.Insert
2.Delete
3.Display
4.Quit
Enter your choice : 2
Queue Underflow
1.Insert
2.Delete
3.Display
4.Quit

Enter your choice :4

Result:
Thus the C program to implement circular queue was executed and verified.
Ex.No.8 Tree Traversal

Aim:
To write a C program to perform various tree traversals in a binary tree.

Algorithm:

1. Create a structure for a tree node with data to be stored in node along with the left and right
subtree.
2. Get the root node value and let the initial link of right subtree and left subtree be NULL.
3. Get the element to be inserted to the root of the tree.
4. If the data is less than the root node key value then the value is stored in the left subtree in
appropriate position.
5. If the data is greater than the root node key value then the value is stored in the right subtree
in appropriate position.
6. Get the order of traversal either in order, preorder or post order traversal.
7. For in order traversal the tree is traversed in following sequence
 Left sub tree
 Root node
 Right sub tree.
8. For preorder traversal the tree is traversed in following sequence
 Root node
 Left sub tree
 Right sub tree
9. For post order traversal the tree is traversed in following sequence
 Right sub tree
 Left sub tree
 Root node.
10. Stop the program.

Program:
#include<stdio.h>
#include<conio.h>

struct node
{
int info;
struct node *llink;
struct node *rlink;
};

typedef struct node *NODE;

NODE insert(NODE root)


{
NODE newnode,cur,prev;
int item;
newnode=(NODE)malloc(sizeof(struct node));
printf("\nEnter the item to be inserted : ");
scanf("%d",&item);
newnode->info=item;
newnode->rlink=newnode->llink=NULL;
if(root==NULL)
root = newnode;
else
{
cur=root;
while(cur!=NULL)
{
prev=cur;
if(item==cur->info)
{
printf("\nDuplicate item cannot be inserted. ");
free(newnode);
break;
}
else
cur=(item<cur->info)?cur->llink:cur->rlink;
}
if(item<prev->info)
prev->llink=newnode;
else
prev->rlink=newnode;
}
return(root);
}

void inorder(NODE root)


{
if(root!=NULL)
{
inorder(root->llink);
printf("%d\n",root->info);
inorder(root->rlink);
}
}

void preorder(NODE root)


{
if(root!=NULL)
{
printf("%d\n",root->info);
preorder(root->llink);
preorder(root->rlink);
}
}

void postorder(NODE root)


{
if(root!=NULL)
{
postorder(root->llink);
postorder(root->rlink);
printf("%d\n",root->info);
}
}
void main()
{
NODE root=NULL;
int ch;
while(1)
{
clrscr();
printf("\n1. Insert\n2. Preorder\n3. Inorder\n4. Postorder\n5. Display\n6.
Exit");
printf("\n\nEnter your choice : ");
scanf("%d",&ch);
switch(ch)
{
case 1: root = insert(root);
break;
case 2: preorder(root);
break;
case 3: inorder(root);
break;
case 4: postorder(root);
break;
case 5: inorder(root);
break;
case 6: exit(0);

}
getch();
}
}

Output:

1. Insert
2. Preorder
3. Inorder
4. Postorder
5. Display
6. Exit

Enter your choice : 1

Enter the item to be inserted : 23

1. Insert
2. Preorder
3. Inorder
4. Postorder
5. Display
6. Exit

Enter your choice : 1

Enter the item to be inserted : 12


1. Insert
2. Preorder
3. Inorder
4. Postorder
5. Display
6. Exit

Enter your choice : 1

Enter the item to be inserted : 45

1. Insert
2. Preorder
3. Inorder
4. Postorder
5. Display
6. Exit

Enter your choice : 2


23
12
45

1. Insert
2. Preorder
3. Inorder
4. Postorder
5. Display
6. Exit

Enter your choice : 3


12
23
45

1. Insert
2. Preorder
3. Inorder
4. Postorder
5. Display
6. Exit

Enter your choice : 4


12
45
23

1. Insert
2. Preorder
3. Inorder
4. Postorder
5. Display
6. Exit

Enter your choice : 5


12
23
45

1. Insert
2. Preorder
3. Inorder
4. Postorder
5. Display
6. Exit

Enter your choice : 6

Result:
Thus the program to perform various tree traversals was executed

EX.No:9 BINARY SEARCH TREE

Aim:
To write a C program to create a binary search tree and perform some operations on it

Algorithm:

2. Create a structure for a tree node with data to be stored in node along with the left and right
subtree.
3. Get the root node value and let the initial link of right subtree and left subtree be NULL.
4. Get the element to be inserted to the root of the tree.
5. If the data is less than the root node key value then the value is stored in the left subtree in
appropriate position.
6. If the data is greater than the root node key value then the value is stored in the right subtree
in appropriate position.
7. Element can be searched by using Findmin, Findmax and Find routine.
8. Display the elements in the tree by in order traversal
9. Stop the program.

Program:
# include<stdio.h>
# include<alloc.h>
#include<conio.h>
# include<process.h>

struct treenode;
typedef struct treenode *position;
typedef struct treenode *searchtree;
searchtree T,temp;
position findmin(searchtree T);
position findmax(searchtree T);
position find(searchtree T,int element);

struct treenode
{
int element;
searchtree left,right;
};
searchtree insert(int x,searchtree T)
{
if(T==NULL)
{
T=(struct treenode *)malloc(sizeof(struct treenode));
if(T==NULL)
printf("OUT OF SPACE!");
else
{
T->element=x;
T->left=T->right=NULL;
}
}
else
{
if(x<T->element)
T->left=insert(x,T->left);
else
T->right=insert(x,T->right);
}
return T;
}
searchtree del(int x,searchtree T)
{
position tmpcell;
if(T==NULL)
printf("\nElement not found.");
else
if(x<T->element) /* Go Left */
T->left=del(x,T->left);
else
if(x>T->element) /* Go right */
T->right=del(x,T->right);
else /* Found element to be deleted */
if(T->left&&T->right) /* Two children */
{
tmpcell=findmin(T->right);
T->element=tmpcell->element;
T->right=del(T->element,T->right);
}
else
{
tmpcell=T;
if(T->left==NULL) /* Also handles 0 children */
T=T->right;
else if(T->right==NULL)
T=T->left;
free(tmpcell);
}
return T;
}
position findmin(searchtree T)
{
if(T==NULL)
return T;
else
if(T->left==NULL)
return T;
else
return findmin(T->left);
}
void inorder(searchtree T)
{
if(T!=NULL)
{
inorder(T->left);
printf("%d\t",T->element);
inorder(T->right);
}
else
return;
}
position findmax(searchtree T)
{
if(T==NULL)
return 0;
else if(T->right==NULL)
return T;
else
return findmax(T->right);
}
position find(searchtree T, int data)
{
if(T==NULL)
return NULL;
else if(data<T->element)
return find(T->left, data);
else if(data>T->element)
return find(T->right, data);
else if(data==T->element)
return T;
}
void main()
{
int x,n,data;
clrscr();
do
{
printf("\n1.INSERT\n2.DELETE\n3.FINDMIN \n4.FINDMAX \n5.FIND\n6.DISPLAY\n7.EXIT");
printf("\nEnter your choice: ");
scanf("%d",&n);
switch(n)
{
case 1:
{
printf("Enter the element to be inserted: ");
scanf("%d",&x);
T=insert(x,T);
break;
}
case 2:
{
printf("Enter the element to be deleted: ");
scanf("%d",&x);
T=del(x,T);
break;
}
case 3:
{
temp = findmin(T);
printf ("Minimum element is %d", temp->element);
break;
}
case 4:
{
temp = findmax(T);
printf("Maximum element is %d", temp->element);
break;
}
case 5:
{
printf ("Enter the data");
scanf ("%d",&data);
temp = find (T, data);
if(temp->element==data)
printf ("Element %d is found", data);
else
printf ("Element is not found");
break;
}
case 6:
inorder(T);
break;
case 7:
exit(0);
}
}while(n<10);
getch();
}

Output:
1.INSERT
2.DELETE
3.FINDMIN
4.FINDMAX
5.FIND
6.DISPLAY
7.EXIT
Enter your choice: 1
Enter the element to be inserted: 11

1.INSERT
2.DELETE
3.FINDMIN
4.FINDMAX
5.FIND
6.DISPLAY
7.EXIT
Enter your choice: 1
Enter the element to be inserted: 22

1.INSERT
2.DELETE
3.FINDMIN
4.FINDMAX
5.FIND
6.DISPLAY
7.EXIT
Enter your choice: 1
Enter the element to be inserted: 8

1.INSERT
2.DELETE
3.FINDMIN
4.FINDMAX
5.FIND
6.DISPLAY
7.EXIT
Enter your choice: 6
8 11 22
1.INSERT
2.DELETE
3.FINDMIN
4.FINDMAX
5.FIND
6.DISPLAY
7.EXIT
Enter your choice: 3
Minimum element is 8
1.INSERT
2.DELETE
3.FINDMIN
4.FINDMAX
5.FIND
6.DISPLAY
7.EXIT
Enter your choice: 4
Maximum element is 22
1.INSERT
2.DELETE
3.FINDMIN
4.FINDMAX
5.FIND
6.DISPLAY
7.EXIT
Enter your choice: 5
Enter the data22
Element 22 is found
1.INSERT
2.DELETE
3.FINDMIN
4.FINDMAX
5.FIND
6.DISPLAY
7.EXIT
Enter your choice: 2
Enter the element to be deleted: 11

1.INSERT
2.DELETE
3.FINDMIN
4.FINDMAX
5.FIND
6.DISPLAY
7.EXIT
Enter your choice: 6
8 22
1.INSERT
2.DELETE
3.FINDMIN
4.FINDMAX
5.FIND
6.DISPLAY
7.EXIT
Enter your choice: 7

Result:
Thus the program to implement binary search tree was executed and verified.
EX.No:10, 11 AVL TREE (Insertion and Deletion)

Aim:
To write a C program to create a AVL tree and perform some operations on it

Algorithm:

1. Create a structure for a tree node with data to be stored in node along with the left and right
subtree.
2. Get the root node value and let the initial link of right subtree and left subtree be NULL.
3. Get the element to be inserted to the root of the tree.
4. If the data is less than the root node key value then the value is stored in the left subtree in
appropriate position.
5. If the data is greater than the root node key value then the value is stored in the right subtree
in appropriate position.
6. Find the balance factor for all the elements of the avl tree.
7. If the balance factor other than 0,+1,-1 ,apply rotation (LL,LR,RR,RL) to make tree height
balanced.
8. Display the elements in the tree by preorder and in order traversal
9. Stop the program.

Program:
#include<conio.h>
#include<stdio.h>
#include<stdlib.h>
typedef struct node
{
int data;
struct node *left,*right;
int ht;
}node;
node *insert(node *,int);
node *Delete(node *,int);
void preorder(node *);
void inorder(node *);
int height( node *);
node *rotateright(node *);
node *rotateleft(node *);
node *RR(node *);
node *LL(node *);
node *LR(node *);
node *RL(node *);
int BF(node *);
int main()
{
node *root=NULL;
int x,n,i,op;
do
{
printf(“n1)Create:”);
printf(“n2)Insert:”);
printf(“n3)Delete:”);
printf(“n4)Print:”);
printf(“n5)Quit:”);
printf(“nnEnter Your Choice:”);
scanf(“%d”,&op);
switch(op)
{
case1: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;
case 2:printf(“nEnter a data:”);
scanf(“%d”,&x);
root=insert(root,x);
break;
case 3:printf(“nEnter a data:”);
scanf(“%d”,&x);
root=Delete(root,x);
break;
case 4: printf(“nPreorder sequence:\n”);
preorder(root);
printf(“nnInorder sequence:\n”);
inorder(root);
printf(“\n”);
break;
}
}while(op!=5);
return 0;
}
node * insert(node *T,int x)
{
if(T==NULL)
{
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);
}
node * Delete(node *T,int x)
{
node *p;
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)
{
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(BF(T)==2)//Rebalance during windup
if(BF(T->left)>=0)
T=LL(T);
else
T=LR(T);
}
else
return(T->left);
}
T->ht=height(T);
return(T);
}
int height(node *T)
{
int lh,rh;
if(T==NULL)
return(0);
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);
return(rh);
}
node * rotateright(node *x)
{
node *y;
y=x->left;
x->left=y->right;
y->right=x;
x->ht=height(x);
y->ht=height(y);
return(y);
}
node * rotateleft(node *x)
{
node *y;
y=x->right;
x->right=y->left;
y->left=x;
x->ht=height(x);
y->ht=height(y);
return(y);
}
node * RR(node *T)
{
T=rotateleft(T);
return(T);
}
node * LL(node *T)
{
T=rotateright(T);
return(T);
}
node * LR(node *T)
{
T->left=rotateleft(T->left);
T=rotateright(T);
return(T);
}
node * RL(node *T)
{
T->right=rotateright(T->right);
T=rotateleft(T);
return(T);
}
int BF(node *T)
{
int lh,rh;
if(T==NULL)
return(0);
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);
}
void preorder(node *T)
{
if(T!=NULL)
{
printf(“%d(Bf=%d)“,T->data,BF(T));
preorder(T->left);
preorder(T->right);
}
}
void inorder(node *T)
{
if(T!=NULL)
{
inorder(T->left);
printf(“%d(Bf=%d)“,T->data,BF(T));
inorder(T->right);
}
}

OUTPUT:

Menu

1. Create 2.insert 3.delete 4.print 5.quit

Enter Your Choice:1


Enter no of elements:3
4
3
5

1. Create 2.insert 3.delete 4.print 5.quit


Enter Your Choice:4
Inorder sequence 4(BF=0) 3(BF=0) 5(BF=0)

EX.NO:12 PRIORITY QUEUE USING HEAP

Aim:
To write a C program to implement priority queue using heaps.

Algorithm:
1. Declare the heap structure as heapstruct.
2. Initialize the heap by getting the size.
3. Get the choice for inserting an element and perform the following steps
4. If the heap is full then display the error message.
5. Else insert the element in the position where it satisfies heap property.
6. Get the choice for deletion and perform the following steps
7. If the heap is empty then display the error message.
8. Else delete the minimum element in the heap by satisfying heap property.
9. Using display option, print all the Elements in heap.

Program:
#include<stdio.h>
#include <stdlib.h>
struct HeapStruct;
typedef struct HeapStruct *PriorityQueue;
typedef int ElementType;

PriorityQueue Initialize(int MaxElements);


void Insert(ElementType X, PriorityQueue H);
ElementType DeleteMin(PriorityQueue H);
int IsEmpty(PriorityQueue H);
int IsFull(PriorityQueue H);

#define MinPQSize (10)


#define MinData 0

struct HeapStruct {
int Capacity;
int Size;
ElementType *Elements;
};

PriorityQueue Initialize(int MaxElements) {


PriorityQueue H;
if (MaxElements < MinPQSize)
printf("Priority queue size is too small");
H = malloc(sizeof ( struct HeapStruct));
if(H==NULL)
printf("Out of space!!!");
/* Allocate the array plus one extra for sentinel */

H->Elements = malloc((MaxElements + 1)*sizeof(ElementType));


if (H->Elements == NULL)
printf("Out of space!!!");
H->Capacity = MaxElements;
H->Size = 0;
H->Elements[ 0 ] = MinData;
return H;
}

/* H->Element[ 0 ] is a sentinel */
void Insert(ElementType X, PriorityQueue H) {
int i;
if (IsFull(H)) {
printf("Priority queue is full");
return;
}
for (i = ++H->Size; H->Elements[ i / 2 ] > X; i /= 2)
H->Elements[ i ] = H->Elements[ i / 2 ];
H->Elements[ i ] = X;
}

ElementType DeleteMin(PriorityQueue H) {
int i, Child;
ElementType MinElement, LastElement;
if (IsEmpty(H)) {
printf("Priority queue is empty");
return H->Elements[ 0 ];
MinElement = H->Elements[ 1 ];
LastElement = H->Elements[ H->Size-- ];
for (i = 1; i * 2 <= H->Size; i = Child) {
/* Find smaller child */
Child = i * 2;
if (Child != H->Size && H->Elements[ Child + 1 ]< H->Elements[ Child ])
Child++;
/* Percolate one level */
if (LastElement > H->Elements[ Child ])
H->Elements[ i ] = H->Elements[ Child ];
else
break;
}
H->Elements[ i ] = LastElement;
return MinElement;
}

int IsEmpty(PriorityQueue H) {
return H->Size == 0;
}

int IsFull(PriorityQueue H) {
return H->Size == H->Capacity;
}

void display(PriorityQueue H)
{
int i;
printf("BINARY HEAP\n");
for(i=0;i<=H->Size;i++)
{
printf("%d",H->Elements[i]);
printf("->");
}
printf("0");
}
main()
{
PriorityQueue H;

int i, j,Size,ch,ele;

clrscr();

printf("\nEnter the Size of Bineary heap:");


scanf("%d",&Size);
H = Initialize(Size);
do
{
printf("\n\t\tMenu\n");
printf("\n1. Insert");
printf("\n2. Delete");
printf("\n3. Display");
printf("\n4. Exit");
printf("\nEnter Your Choice:");
scanf("%d",&ch);
switch(ch)
{
case 1:
printf("\nEnter an Element:");
scanf("%d",&ele);
Insert(ele, H);
break;
case 2:
DeleteMin(H);
break;
case 3:
display(H);
break;
case 4:
printf("\n Exit ");
}
}while(ch<4);
getch();
return 0;
}

OUTPUT:
Enter the Size of Bineary heap:10

Menu

1. Insert
2. Delete
3. Display
4. Exit
Enter Your Choice:1

Enter an Element:11

Menu

1. Insert
2. Delete
3. Display
4. Exit
Enter Your Choice:1

Enter an Element:5

Menu

1. Insert
2. Delete
3. Display
4. Exit
Enter Your Choice:1
Enter an Element:2

Menu

1. Insert
2. Delete
3. Display
4. Exit
Enter Your Choice: Enter an Element:4

Menu

1. Insert
2. Delete
3. Display
4. Exit
Enter Your Choice:3
BINARY HEAP
0->2->4->5->11->0
Menu

1. Insert
2. Delete
3. Display
4. Exit
Enter Your Choice: 2
Menu

1. Insert
2. Delete
3. Display
4. Exit
Enter Your Choice:3
BINARY HEAP
0->4->11->5->0
Menu

1. Insert
2. Delete
3. Display
4. Exit
Enter Your Choice:2

Menu

1. Insert
2. Delete
3. Display
4. Exit
Enter Your Choice: Enter Your Choice:3
BINARY HEAP
0->5->11->0
Menu
1. Insert
2. Delete
3. Display
4. Exit
Enter Your Choice:4
Exit

Result:
Thus the program to implement priority queue using heaps was executed and verified.

EX.No:13 HASHING USING SEPARATE CHAINING METHOD


Aim :
To write a C program to implement hashing using separate chaining method

Algorithm:
1. Declare the structure of the hash table as hashtbl.
2. Allocate the memory for the array of pointers that point to the corresponding linked list.
3. Perform the hash function for calculating hash value.
4. For insertion: Traverse down the appropriate list and insert the element in the first position
of linked list if the element is not already present in the list.
5. For deletion: Traverse down the appropriate list and delete the element in the list by
changing corresponding pointer in the list if the element is present.
6. For finding the element: Traverse down the appropriate list and return the position of the
element if it is found.

Program:

#include<stdio.h>
#include<alloc.h>
struct listnode;
typedef struct listnode *position;
typedef position list;
struct hashtbl;
typedef struct hashtbl *hashtable;
hashtable initialize(int tablesize);
void destroytable(hashtable h);
position find(int key, hashtable h);
void insert(int key,hashtable h);
int retrieve(position p);
int hash(int key, int tablesize);
struct listnode
{
int element;
position next;
};
struct hashtbl
{
int tablesize;
list *thelists;
};
int hash(int key, int tablesize)
{
return key%tablesize;
}
position find(int key, hashtable h)
{
position p;
list l;
l=h->thelists[hash(key,h->tablesize)];
p=l->next;
while(p!=NULL && p->element !=key)
p=p->next;
return p;
}

position findprevious(int key, hashtable h)


{
position p;
p=h->thelists[hash(key,h->tablesize)];
while(p!=NULL && p->next->element!=key)
p=p->next;
return p;
}

void insert(int key, hashtable h)


{
position pos, newcell;
list l;
pos=find(key,h);
if(pos==NULL)
{
newcell=malloc(sizeof(struct listnode));
if(newcell!=NULL)
{
l=h->thelists[hash(key,h->tablesize)];
newcell->next=l->next;
newcell->element=key;
l->next=newcell;
}
}
else
printf("\nElement is already available in the Table..\n");
}

void del(int key, hashtable h)


{
position pos, oldcell;
list l;
pos=findprevious(key,h);
if(pos->next!=NULL)
{
oldcell=pos->next;
pos->next=oldcell->next;
free(oldcell);
}
else
printf("\nElement is not found in the Hash Table\n");
}
hashtable initialize(int tablesize)
{
hashtable h;
int i;
if(tablesize<1)
{
printf("Table Size is too small\n");
return NULL;
}
h=malloc(sizeof(struct hashtbl));
if(h!=NULL)
{
h->tablesize= tablesize;
h->thelists[i]=malloc(sizeof(list)*h->tablesize);
for(i=0; i<h->tablesize; i++)
{
h->thelists[i]=malloc(sizeof(struct listnode));
h->thelists[i]->next = NULL;
}
}
return h;
}
void display(hashtable h)
{
int i;
position p;
printf("\nThe Hash Table is:\n");
for(i=0; i<h->tablesize; i++)
{
p=h->thelists[i]->next;
while(p!=NULL)
{
printf("%d",p->element);
printf("->");
p=p->next;
}
printf("NULL\n");
}
printf("-");
}
void main()
{
int size,ch,ele,child;
hashtable h;
clrscr();
printf("nWorking with Hashing Techniques – Separate Chaining Method\n");
printf("\nEnter the Size of the Hash Table:");
scanf("%d",&size);
h = initialize(size);
do
{
printf("\n\t\tMenu\n");
printf("\n1. Insert");
printf("\n2. Delete");
printf("\n3. Display");
printf("\n4. Find");
printf("\n5. Exit");
printf("\nEnter Your Choice:");
scanf("%d",&ch);
switch(ch)
{
case 1:
printf("nEnter an Element:");
scanf("%d",&ele);
insert(ele, h);
break;
case 2:
printf("\nEnter an Element:");
scanf("%d",&ele);
del(ele,h);
break;
case 3:
display(h);
break;
case 4:
printf("\nEnter an Element:");
scanf("%d",&ele);
if(find(ele, h)!=NULL)
printf("The Element is found in the table\n");
else
printf("The Element is not found in the table\n");
break;
case 5:
printf("\n Exit ");
}
}while(ch<5);
}

Output:

Working with Hashing Techniques û Separate Chaining Method

Enter the Size of the Hash Table:5

Menu
1. Insert
2. Delete
3. Display
4. Find
5. Exit
Enter Your Choice:1
nEnter an Element:11

Menu

1. Insert
2. Delete
3. Display
4. Find
5. Exit
Enter Your Choice:1
nEnter an Element:22

Menu

1. Insert
2. Delete
3. Display
4. Find
5. Exit
Enter Your Choice:1
nEnter an Element:33

Menu

1. Insert
2. Delete
3. Display
4. Find
5. Exit
Enter Your Choice:
The Hash Table is:3
NULL
11->NULL
22->NULL
33->NULL
NULL
-
Menu

1. Insert
2. Delete
3. Display
4. Find
5. Exit
Enter Your Choice:2

Enter an Element:22
Menu

1. Insert
2. Delete
3. Display
4. Find
5. Exit
Enter Your Choice:3

The Hash Table is:


NULL
11->NULL
NULL
33->NULL
NULL
-
Menu

1. Insert
2. Delete
3. Display
4. Find
5. Exit
Enter Your Choice:4

Enter an Element:11
The Element is found in the table

Menu

1. Insert
2. Delete
3. Display
4. Find
5. Exit
Enter Your Choice:5

Result:
Thus the to implement hashing using separate chaining method was executed and
verified.

EX.NO:14 PRIM’S ALGORITHM

Aim:
To Write a C program to implement Dijkstra’s shortest path algorithm.

Algorithm:
1. Define the size of the Graph.
2. Get the number of weighted edges in the input graph.
3. Set the first node as the source node.
4. From the source node find the shortest path to all other vertices using dijkstra’s
algorithm.
5. Display the shortest path from the source to all other vertices.

Program:
#include <stdio.h>
#define GRAPHSIZE 20
#define INFINITY GRAPHSIZE*GRAPHSIZE
#define MAX(a, b) ((a > b) ? (a) : (b))

int e; /* The number of nonzero edges in the graph */


int n; /* The number of nodes in the graph */
long dist[GRAPHSIZE][GRAPHSIZE]; /* dist[i][j] is the distance between node i and j; or 0 if there
is no direct connection */
long d[GRAPHSIZE]; /* d[i] is the length of the shortest path between the source (s) and node i */

void printD() {
int i;
for (i = 1; i <= n; ++i)
printf("%10d", i);
printf("\n");
for (i = 1; i <= n; ++i) {
printf("%10ld", d[i]);
}
printf("\n");
}
void dijkstra() {
int i, k, mini;
int visited[GRAPHSIZE];

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


d[i] = INFINITY;
visited[i] = 0; /* the i-th element has not yet been visited */
}

d[1] = 0;

for (k = 1; k <= n; ++k) {


mini = -1;
for (i = 1; i <= n; ++i)
if (!visited[i] && ((mini == -1) || (d[i] < d[mini])))
mini = i;
visited[mini] = 1;
for (i = 1; i <= n; ++i)
if (dist[mini][i])
if (d[mini] + dist[mini][i] < d[i])
d[i] = d[mini] + dist[mini][i];
}
}

int main() {
int i, j;
int u, v, w;

//FILE *fin = fopen("dist.txt", "r");


printf("enter the no of vertices:");
scanf("%d", &e);
for (i = 0; i < e; ++i)
for (j = 0; j < e; ++j)
dist[i][j] = 0;
n = -1;
for (i = 0; i < e; ++i) {
scanf("%d%d%d",&u,&v,&w);
dist[u][v] = w;
n = MAX(u, MAX(v, n));
}
dijkstra(1);
printf(“\nThe Shortest path form 1 to all other vertices:”)
printD();

getch();
return 0;
}

OUTPUT:
enter the no of vertices:12

122
141
243
2 5 10
365
314
432
452
468
474
576
761

The Shortest path form 1 to all other vertices:

1 2 3 4 5 6 7
0 2 3 1 3 6 5

Result:
Thus the C program to implement Dijkstra’s shortest path algorithm was executed and
verified.

You might also like