You are on page 1of 80

EX NO:1(a)

SINGLY LINKED LIST


AIM:

To write a C program to perform the implementation of Singly Linked List.

ALGORITHM:

1. Define the node structure & read the choice to perform the operations.

2. If the choice is to insert at first, then,


a. Create a new node & add data to the data field.
b. Assign the address of head to the address field of new node.
c. Assign new node to the head.

3. If the choice is to insert at last, then,


a. Create a new node & add data to the data field.
b. Assign the address of new node to the address field of last node.
c. Assign new node to the last.

4. If the choice is to insert at position, ‘p’, then,

a. Assign some temporary node ‘temp’ to the head.


b. Create a new node & add data to the data field.
c. Traverse the list till the given position is reached.
d. Let ‘pre’ contains address of previous node and ‘curr’ contains address of the next node.
Assign address of new node to address field of ‘pre’ node and address of ‘curr’ to address
field of new node.

5. If the choice is to delete the first node then,

a. Assign some temporary node ‘temp’ to the first.


b. Assign address of the next immediate node to ‘first’.
c. Delete the temp node.

6. If the choice is to delete the last node then,


a. Traverse the list and assign the address of last node to ‘temp’ and address of last before
node to
‘pre’.
b. Assign null value to the address field of node ‘pre’.
c. Assign the address of ‘pre’ to last.
d. Delete the temp node.

7. If the choice is to delete the middle node then,


a. Traverse the list , find the node to be deleted and assign its address to ‘t’.
b.Assign the address of next node to temp .
c. Assign the address of ‘temp’ to address field of previous node ‘pre’.
d. Delete the node ‘t’.

8. If the choice is display, then,


a. Display the contents of the list until you encounter the NULL pointer.
PROGRAM:

#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
#include<malloc.h>
struct node
{
int info;
struct node *link;
};
struct node *first=NULL,*last=NULL;
struct node *n, *temp, *curr, *pre, *t;
void main()
{
int choice,c,p,i=1;
clrscr();
do
{
printf("\n 1. INSERTION OF NODE AT LAST POSITION");
printf("\n 2. INSERTION OF NODE AT FIRST POSITION");
printf("\n 3. INSERTION OF NODE AT MIDDILE POSITION");
printf("\n 4. DELETION OF NODE");
printf("\n 5. DISPLAY OF NODES");
printf("\n 6.EXIT");
printf("\n ENTER YOUR CHOICE: \t");
scanf("%d",&choice);
switch(choice)
{
case 1:
n=(node *)malloc(sizeof(struct node));
printf("\n ENTER THE NODE TO BE INSERTED AT LAST
POSITION\t");
scanf("%d",&n->info);
if(first==NULL)
{
first=last=n;
first->link=NULL;
}
else
{
last->link=n;
last=n;
last->link=NULL;
}
printf("\n\t\t NODE INSERTED");
break;
case 2:
n=(node *)malloc(sizeof(struct node));
printf("\n ENTER THE NODE TO BE INSERTED AT FIRST
POSITION:");
scanf("%d",&n->info);
n->link=first;
first=n;
break;

case 3:
n=(node *)malloc(sizeof(struct node));
temp=curr=first;
pre=NULL;
c=0;
printf("\n ENTER THE NODE TO BE INSERTED AT ANY
POSITION");
scanf("%D",&n->info);
n->link=NULL;
while(temp!=NULL)
{
temp=temp->link;
c=c+1;
}
printf("\n TOTAL NUMBER OF ELEMENTS ARE %d",c);
printf("\n ENTER THE POSITION");
scanf("%d",&p);
c=1;
while((c<p)&&(curr!=NULL))
{
pre=curr;
curr=curr->link;
c=c+1;
}
if(curr==NULL)
printf("\n\t THE ELEMENT CAN'T BE INSERTED\n");
else
{
if(c==p)
{
pre->link=n;
n->link=curr;
printf("\n\t\t NODE INSERTED\n");
}
}
break;
case 4:
printf("\n MENU");
printf("\n 1. DELETE THE FIRST NODE");
printf("\n 2. DELETE THE LAST NODE");
printf("\n 3.DELETE THE MIDDLE NODE");
printf("\n ENTER YOUR CHOICE");
scanf("%d",&c);
switch(c)
{
case 1:
if(first==NULL)
printf("\n\t\t LIST IS EMPTY, CAN'T DELETE");
else
{
temp=first;
first=first->link;
free(temp);
printf("\n\t\t FIRST NODE IS DELETED");
}
break;
case 2:
if(first==NULL)
printf("\n\t\tLIST IS EMPTY");
else
{
temp=first;
pre=NULL;
if(first==last)
{
first=last=NULL;
free(temp);
}
while(temp!=last)
{
pre=temp;
temp=temp->link;
}
pre->link=NULL;
last=pre;
free(temp);
printf("\n\t\t LAST NODE DELETED");
}
break;
case 3:
if(first==NULL)
printf("\n\t\t LIST IS EMPTY");
else
{
temp=first;
printf("\n ENTER THE POSITION");
scanf("%d",&p);
if(p==1)
{
first=first->link;
free(temp);
}
else
{
temp=first;
while(i<p)
{
pre=temp;
temp=temp->link;
i++;
}
t=temp;
temp=temp->link;
pre->link=temp;
free(t);
}
printf("\n Node is deleted");
break;
}
}
case 5:
temp=first;
while(temp!=NULL)
{
printf("%d-->",temp->info);
temp=temp->link;
}
printf("NULL");
break;
case 6:
exit(0);
break;
}
}while(choice<6);
getch();
}

OUTPUT :

1. INSERTION OF NODE AT LAST POSITION


2. INSERTION OF NODE AT FIRST POSITION
3. INSERTION OF NODE AT MIDDILE POSITION
4. DELETION OF NODE
5. DISPLAY OF NODES
6.EXIT
ENTER YOUR CHOICE: 1

ENTER THE NODE TO BE INSERTED AT LAST POSITION 10

NODE INSERTED

1. INSERTION OF NODE AT LAST POSITION


2. INSERTION OF NODE AT FIRST POSITION
3. INSERTION OF NODE AT MIDDILE POSITION
4. DELETION OF NODE
5. DISPLAY OF NODES
6.EXIT
ENTER YOUR CHOICE: 2

ENTER THE NODE TO BE INSERTED AT FIRST POSITION:20

1. INSERTION OF NODE AT LAST POSITION


2. INSERTION OF NODE AT FIRST POSITION
3. INSERTION OF NODE AT MIDDILE POSITION
4. DELETION OF NODE
5. DISPLAY OF NODES
6.EXIT
ENTER YOUR CHOICE: 5
20-->10-->NULL

1. INSERTION OF NODE AT LAST POSITION


2. INSERTION OF NODE AT FIRST POSITION
3. INSERTION OF NODE AT MIDDILE POSITION
4. DELETION OF NODE
5. DISPLAY OF NODES
6.EXIT
ENTER YOUR CHOICE:

RESULT:

Thus the singly linked list is implemented .


EX No: 1(b)

DOUBLY LINKED LIST


AIM:

To implement doubly linked list for performing insert, delete and search operations.

ALGORITHM:

1. Create a node with data and rlink and llink fields. Assign null value to rlink and llink.
2. If the choice is to insert, then
a. Create a new node ‘temp’ & add data to the data field.
Assign some temporary node next to the head.
b. Traverse the list till the given position is reached.
c. Let next contains address of previous node and temp contains address of the new node.
Assign
1.address of ‘next’ node to llink field of ‘temp’ node ,
2.rlink of next to rlink of temp.
3.address of temp to next->rlink->llink.
4.address of temp to rlink of next.

3. If the choice is to delete, then


a. Assign some temporary node next to the head.
b.Traverse the list till the given position is reached.
c. Let next contains address of previous node of the node to be deleted.
Assign
 rlink of next to temp.
 rlink of temp to rlink of next
 rlink of next to prev
 address of next to llink of prev.

4. If the choice is to display, then
a. Display the contents of the list until you encounter the NULL pointer.

PROGRAM :

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

struct node
{
int data;
struct node *llink,*rlink;
}*temp,*next,*prev;

typedef struct node node;


struct node *start=NULL,*end;

void main()
{
void insert();
void del();
void display();
void create();
int ch;
clrscr();
create();
do
{
printf("\t\t\nMENU\n");
printf("1.INSERT\n");
printf("2.DELETE\n");
printf("3.DISPLAY\n");
printf("4.EXIT\n");
printf("ENTER UR CHOICE:");
scanf("%d",&ch);
switch(ch)
{
case 1:
insert();
break;
case 2:
del();
break;
case 3:
display();
break;
case 4:
exit(0);
}
}while(ch<=4);
getch();
}

void create()
{
int data;
temp=(node *)malloc(sizeof(node));
temp->llink=NULL;
temp->rlink=NULL;
printf("\nENTER THE ELEMENT:");
scanf("%d",&data);
temp->data=data;
start=temp;
}
void insert()
{
int p,data,i;
temp=(node *)malloc(sizeof(node));
printf("\nENTER THE POSITION TO BE INSERTED:");
scanf("%d",&p);
printf("\nENTER THE ELEMENT:");
scanf("%d",&data);
temp->data=data;
if(p==1)
{
temp->llink=NULL;
temp->rlink=start;
start->llink=temp;
start=temp;
}
else
{
i=1;
next=start;
while(i<p-1)
{
next=next->rlink;
i++;
}
temp->llink=next;
temp->rlink=next->rlink;
next->rlink->llink=temp;
next->rlink=temp;
}
printf("\n\nNODE INSERTED SUCCESSFULLY");
}
void del()
{
int p,i;
printf("\nENTER THE POSITION TO BE DELETED:");
scanf("%d",&p);
if(p==1)
{
temp=start;
start=temp->rlink;

start->llink=NULL;
}
else
{
i=1;
next=start;
while(i<p-1)
{
next=next->rlink;
i++;
}
temp=next->rlink;
next->rlink=temp->rlink;
prev=next->rlink;
prev->llink=next;
}
free(temp);
printf("\n\nNODE REMOVED SUCCESSFULLY");
}
void display()
{
temp=start;
printf("\nTHE ELEMENTS IN THE DOUBLY LINKED LIST ARE:");
if(temp==NULL)
{
printf("\nTHERE ARE NO NODES IN THE LIST");
}
else
{
while(temp->rlink!=NULL)
{
printf("\t%d",temp->data);
temp=temp->rlink;
}
printf("\t%d",temp->data);
}
}

OUTPUT:

ENTER THE ELEMENT:10


MENU 1.INSERT
2.DELETE 3.DISPLAY
4.EXIT
ENTER UR CHOICE:1
ENTER THE POSITION TO BE INSERTED:2
ENTER THE ELEMENT:20
NODE INSERTED SUCCESSFULLY

MENU 1.INSERT
2.DELETE 3.DISPLAY
4.EXIT ENTER UR CHOICE:3
THE ELEMENTS IN THE DOUBLY LINKED LIST ARE: 10 20

MENU 1.INSERT
2.DELETE 3.DISPLAY
4.EXIT ENTER UR CHOICE:2
ENTER THE POSITION TO BE DELETED:1
NODE REMOVED SUCCESSFULLY

MENU 1.INSERT
2.DELETE 3.DISPLAY
4.EXIT ENTER UR CHOICE:3
THE ELEMENTS IN THE DOUBLY LINKED LIST ARE: 20

MENU 1.INSERT
2.DELETE 3.DISPLAY
4.EXIT
ENTER UR CHOICE:4

RESULT:

Thus doubly linked list is implemented.


EX NO:2 ARRAY IMPLEMETATION OF LIST

AIM: To perform list operations with the help of arrays using C


programming.

ALGORITHM
main()
1. Display the operation that can be performed
2. Repeat step 3 and 4 uptil x!=7
3. x← choice of user
4. switch x

case 1: insertion(y,p)
case 2: deletion()
case 3: findpos()
case 4: index(y)
case 5: empty()
case 6: display()
[end switch]
[[end do while]
insertion(int a, int b)
1. If end>9

print overflow
2. Else

For I from end +1 to b


Arr(i+1)←Arr(i)
deletion(int a, int b)
1. For I in range a to end

Arr(i)←Arr(i+1)
2. (end for)
3. end←end+1

findpos(int a)
1. if a>=0 and a<=end
Print Arr(a)
2. Else

Print position doesn’t exist


Empty()
1. end← -1

display()
1. for i=0 to end

Print Arr(i)

Program-
#include<stdio.h>
void insert();
void delete();
voidmakeempty();
voidfindpos();
voidfindele();
voiddisp();
intarr[100],size=0;
int main()
{
intch;
do
{
printf("\n1.Insertion");
printf("\n2.Deletion");
printf("\n3.Make Empty");
printf("\n4.Find element");
printf("\n5.Find element pos");
printf("\n6.Display");
printf("\n7.Exit");
printf("\nEnter choice:-");
scanf("%d",&ch);
switch(ch)
{
case 1: insert();
break;
case 2: delete();
break;
case 3: makeempty();
break;
case 4: findpos();
break;
case 5: findele();
break;
case 6: disp();
break;
}
}while(ch<=6);
return 0;
}
void insert()
{
if(size==100)
{
printf("\nOverflow");
}
else
{
inti,no,pos;
printf("\nEnter position :-");
scanf("%d",&pos);
if(pos<=size)
{
printf("Enter elelment:-");
scanf("%d",&no);
for(i=size;i>=pos;i--)
{
arr[i+1]=arr[i];
}
arr[pos]=no;
++size;
printf("\nElement %d inserted\n",no);
}
else
{
printf("\nInvalid position");
}
}
}
void delete()
{
intpos,i;
if(size==0)
{
printf("Underflow\n");
}
else
{
printf("\nEnter position :-");
scanf("%d",&pos);
if(pos<=size)
{
for(i=pos;i<size;i++)
{
arr[i]=arr[i+1];
}
--size;
printf("\nElement deleted");
}
else
{
printf("\nInvalidpostion");
}
}
}
voidmakeempty()
{
size=0;
printf("\nArray Emptied");
}
voidfindpos()
{
intpos;
printf("\nEnter position :");
scanf("%d",&pos);
if(pos<=size)
{
printf("\nElement at postion %d is : %d",pos,arr[pos]);
}
else
{
printf("\n Invalid Position");
}
}
voidfindele()
{
inti,no,pos=-1;
printf("Enter element : ");
scanf("%d",&no);
for(i=0;i<size;i++)
{
if(arr[i]==no)
{
pos=i;
break;
}
}
if(pos!=-1)
{
printf("\nElement %d found at %d position",no,pos);
}
else
{
printf("\nElement not found");
}
}
voiddisp()
{
inti;
printf("\n List is :-\n");
for(i=0;i<size;i++)
{
printf("%d\t",arr[i]);
}
}

OUTPUT:

ENTER THE ELEMENT:10


MENU 1.INSERT
2.DELETE 3.DISPLAY
4.EXIT
ENTER UR CHOICE:1
ENTER THE POSITION TO BE INSERTED:2
ENTER THE ELEMENT:20
NODE INSERTED SUCCESSFULLY

MENU 1.INSERT
2.DELETE 3.DISPLAY
4.EXIT ENTER UR CHOICE:3
THE ELEMENTS IN THE LIST ARE: 10 20

MENU 1.INSERT
2.DELETE 3.DISPLAY
4.EXIT ENTER UR CHOICE:2
ENTER THE POSITION TO BE DELETED:1
NODE REMOVED SUCCESSFULLY

MENU 1.INSERT
2.DELETE 3.DISPLAY
4.EXIT ENTER UR CHOICE:3
THE ELEMENTS IN the LIST ARE: 20

MENU 1.INSERT
2.DELETE 3.DISPLAY
4.EXIT
ENTER UR CHOICE:4
RESULT: Thus list is implemented.

EX NO:3 APPLICATIONS OF LIST


POLYNOMIAL ADDITION
AIM:

To represent a polynomial as a linked list and write functions for polynomial addition.

ALGORITHM:

Step 1: Start the program

Step 2: Read the number of terms for the first polynomial.

Step 3: Get the co efficient and exponents of every term in the first
polynomial.

Step 4:Read the number of terms for the second polynomial.

Step 5 : Get the co efficient and exponents of every term in the second polynomial.

Step 6: Add the polynomials using function poly_add


Step 6.1: Check for the exponents of first polynomial and the second polynomial.
Step 6.2: If both the exponents are same the co efficients of first polynomial and second
polynomial are added.

Step 7: Display the result

Step 8: Terminate the program.

PROGRAM :

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<alloc.h>
struct polynode
{
int coeff;
int exp;
struct polynode *link;
};
void poly_append(struct polynode**,int,int);
void poly_display(struct polynode *);
void poly_add(struct polynode*,struct polynode*,struct polynode**);
struct polynode *first,*second,*result;
void main()
{
int i,n,x,y,m;
clrscr();
first=second=result=NULL; /* Empty Linked Lists*/
printf("\nEnter the number of terms in the first polynomial:");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
printf("\nEnter the coefficient of term %d of first polynomial:",i);
scanf("%d",&x);
printf("\nEnter the exponent of term %d of first polynomial:",i);
scanf("%d",&y);
poly_append(&first,x,y);
}
printf("\nEnter the number of terms in the second polynomial:");
scanf("%d",&m);
for(i=1;i<=m;i++)
{
printf("\nEnter the coefficient of term %d of second polynomial:",i);
scanf("%d",&x);
printf("\nEnter the exponent of term %d of second polynomial:",i);
scanf("%d",&y);
poly_append(&second,x,y);
}
printf("\nThe first polynomial is:\n");
poly_display(first);
printf("\nThe second polynomial is:\n");
poly_display(second);
poly_add(first,second,&result);
printf("\nThe resultant polynomial is:\n");
poly_display(result);
getch();
}
void poly_append(struct polynode **q,int x ,int y)
{
struct polynode *temp;
temp=*q;
/* Creates a new node if the list is empty */
if(*q==NULL)
{
*q=(polynode*)malloc(sizeof(struct polynode));
temp=*q;
}
else
{
/*Traverse the entire linked list */
while(temp->link!=NULL)
temp=temp->link;
/* Create new nodes at intermediate stages */
temp->link=(polynode*)malloc(sizeof(struct polynode));
temp=temp->link;
}
/*Assign coefficient and exponent */
temp->coeff=x;
temp->exp=y;
temp->link=NULL;
}
/* Displays the contents of linked list representing a polynomial */
void poly_display(struct polynode *q)
{
/* Traverse till the end of the linked list */
while(q!=NULL)
{
printf("%dX^%d :",q->coeff,q->exp);
q=q->link;
}
}
/* Adds two polynomials */
void poly_add(struct polynode *x,struct polynode *y, struct polynode **s)
{
struct polynode *z;
/* if both linked lists are empty */
if(x==NULL && y==NULL)
return;
/*Traverse till one of the lists ends */
while(x!=NULL&&y!=NULL)
{
/*Creates a new node if the list is empty */
if(*s==NULL)
{
*s=(polynode*)malloc(sizeof(struct polynode));
z=*s;
}
/* Create new nodes at intermediate stages */
else
{
z->link=(polynode*)malloc(sizeof(struct polynode));
z=z->link;
}
/*store a term of the larger degree polynomial */
if(x->exp<y->exp)
{
z->coeff=y->coeff;
z->exp=y->exp;
y=y->link; /*go to the next node */
}
else
{
if(x->exp>y->exp)
{
z->coeff=x->coeff;
z->exp=x->exp;
x=x->link; /*go to the next node */
}
else
{
/* Add the coefficients when exponents are equal*/
if(x->exp==y->exp)
{
z->coeff=x->coeff+y->coeff;
z->exp=x->exp;
x=x->link;
y=y->link;
}
}
}
}
/*assign remaining terms of the first polynomial to the result*/
while(x!=NULL)
{
if(*s==NULL)
{
*s=(polynode*)malloc(sizeof(struct polynode));
z=*s;
}
else
{
z->link=(polynode*)malloc(sizeof(struct polynode));
z=z->link;
}
z->coeff=x->coeff;
z->exp=x->exp;
x=x->link;
}
/*assign remaining terms of the second polynomial to the result*/
while(y!=NULL)
{
if(*s==NULL)
{
*s=(polynode*)malloc(sizeof(struct polynode));
z=*s;
}
else
{
z->link=(polynode*)malloc(sizeof(struct polynode));
z=z->link;
}
z->coeff=y->coeff;
z->exp=y->exp;
y=y->link;
}
z->link=NULL;/*assign NULL at end of resultant linked list*/
}

OUTPUT:

Enter the number of terms in the first polynomial:3


Enter the coefficient of term 1 of first polynomial:1
Enter the exponent of term 1 of first polynomial:2
Enter the coefficient of term 2 of first polynomial:2
Enter the exponent of term 2 of first polynomial:1
Enter the coefficient of term 3 of first polynomial:3
Enter the exponent of term 3 of first polynomial:0
Enter the number of terms in the second polynomial:3
Enter the coefficient of term 1 of second polynomial:1
Enter the exponent of term 1 of second polynomial:2
Enter the coefficient of term 2 of second polynomial:2
Enter the exponent of term 2 of second polynomial:1
Enter the coefficient of term 3 of second polynomial:3
Enter the exponent of term 3 of second polynomial:0
The first polynomial is: 1X^2 :2X^1 :3X^0 :
The second polynomial is: 1X^2 :2X^1 :3X^0 :
The resultant polynomial is: 2X^2 :4X^1 :6X^0 :

RESULT :
Thus functions for polynomial addition is implemented by using linked list.

EX.NO: 4(a) STACK USING ARRAY


#include<conio.h>
#include<stdio.h>
#define max 50
void push();
void pop();
void display();
int menu();
int stack[max], top=0;
 
void main()
{
    int ch;
    clrscr();
    do{
        ch=menu();
        switch(ch)
        {
            case 1: push();
                break;
            case 2: pop();
                break;
            case 3: display();
                break;
            case 4: exit();
            default: printf("\nEnter a valid choice!!");
        }
    }while(1);
}
 
int menu()
{
    int ch;
    printf("\nStack");
    printf("\n1.Push\n2.Pop\n3.Display\n4.Exit");
    printf("\nEnter your Choice:");
    scanf("%d",&ch);
    return ch;
}
 
void push()
{
    if(top==max)
        printf("\nOverflow");
    else
    {
        int element;
        printf("\nEnter Element:");
        scanf("%d",&element);
        printf("\nElement(%d) has been pushed at %d", element, top);
        stack[top++]=element;
    }
}
 
void pop()
{
    if(top==-1)
        printf("\nUnderflow");
    else
    {
        top--;
        printf("\nELement has been popped out!");
    }
}
 
void display()
{
    if(top==0)
        printf("\nStack is Empty!!");
    else
    {
        int i;
        for(i=0;i<max;i++)
            printf("%d",stack[i]);
    }
}

STACK ELEMENTS :44->33->22->11->


STACK OPTIONS
0: Exit
1: Add item
2: Remove item
Enter choice :::1

Enter an item to insert:55

Result:

Thus the program implemented successfully.


EX.NO: 4(a) QUEUE USING ARRAY

#define SIZE 10

void enQueue(int);
void deQueue();
void display();

int queue[SIZE], front = -1, rear = -1;

void main()
{
int value, choice;
clrscr();
while(1){
printf("\n\n***** MENU *****\n");
printf("1. Insertion\n2. Deletion\n3. Display\n4. Exit");
printf("\nEnter your choice: ");
scanf("%d",&choice);
switch(choice){
case 1: printf("Enter the value to be insert: ");
scanf("%d",&value);
enQueue(value);
break;
case 2: deQueue();
break;
case 3: display();
break;
case 4: exit(0);
default: printf("\nWrong selection!!! Try again!!!");
}
}
}
void enQueue(int value){
if(rear == SIZE-1)
printf("\nQueue is Full!!! Insertion is not possible!!!");
else{
if(front == -1)
front = 0;
rear++;
queue[rear] = value;
printf("\nInsertion success!!!");
}
}
void deQueue(){
if(front == rear)
printf("\nQueue is Empty!!! Deletion is not possible!!!");
else{
printf("\nDeleted : %d", queue[front]);
front++;
if(front == rear)
front = rear = -1;
}
}
void display(){
if(rear == -1)
printf("\nQueue is Empty!!!");
else{
int i;
printf("\nQueue elements are:\n");
for(i=front; i<=rear; i++)
printf("%d\t",queue[i]);
}
}
Result:

Thus the program implemented successfully.

EX NO:5 (a) STACK using Linked Lists


#include <stdio.h>
#include <stdlib.h>
 
struct node
{
int info;
struct node *ptr;
}*top,*top1,*temp;
 
int topelement();
void push(int data);
void pop();
void empty();
void display();
void destroy();
void stack_count();
void create();
 
int count = 0;
 
void main()
{
int no, ch, e;
 
printf("\n 1 - Push");
printf("\n 2 - Pop");
printf("\n 3 - Top");
printf("\n 4 - Empty");
printf("\n 5 - Exit");
printf("\n 6 - Dipslay");
printf("\n 7 - Stack Count");
printf("\n 8 - Destroy stack");
 
create();
 
while (1)
{
printf("\n Enter choice : ");
scanf("%d", &ch);
 
switch (ch)
{
case 1:
printf("Enter data : ");
scanf("%d", &no);
push(no);
break;
case 2:
pop();
break;
case 3:
if (top == NULL)
printf("No elements in stack");
else
{
e = topelement();
printf("\n Top element : %d", e);
}
break;
case 4:
empty();
break;
case 5:
exit(0);
case 6:
display();
break;
case 7:
stack_count();
break;
case 8:
destroy();
break;
default :
printf(" Wrong choice, Please enter correct choice ");
break;
}
}
}
 
/* Create empty stack */
void create()
{
top = NULL;
}
 
/* Count stack elements */
void stack_count()
{
printf("\n No. of elements in stack : %d", count);
}
 
/* Push data into stack */
void push(int data)
{
if (top == NULL)
{
top =(struct node *)malloc(1*sizeof(struct node));
top->ptr = NULL;
top->info = data;
}
else
{
temp =(struct node *)malloc(1*sizeof(struct node));
temp->ptr = top;
temp->info = data;
top = temp;
}
count++;
}
 
/* Display stack elements */
void display()
{
top1 = top;
 
if (top1 == NULL)
{
printf("Stack is empty");
return;
}
 
while (top1 != NULL)
{
printf("%d ", top1->info);
top1 = top1->ptr;
}
}
 
/* Pop Operation on stack */
void pop()
{
top1 = top;
 
if (top1 == NULL)
{
printf("\n Error : Trying to pop from empty stack");
return;
}
else
top1 = top1->ptr;
printf("\n Popped value : %d", top->info);
free(top);
top = top1;
count--;
}
 
/* Return top element */
int topelement()
{
return(top->info);
}
 
/* Check if stack is empty or not */
void empty()
{
if (top == NULL)
printf("\n Stack is empty");
else
printf("\n Stack is not empty with %d elements", count);
}
 
/* Destroy entire stack */
void destroy()
{
top1 = top;
 
while (top1 != NULL)
{
top1 = top->ptr;
free(top);
top = top1;
top1 = top1->ptr;
}
free(top1);
top = NULL;
 
printf("\n All stack elements destroyed");
count = 0;
}
$ cc pgm2.c
$ a.out
 
1 - Push
2 - Pop
3 - Top
4 - Empty
5 - Exit
6 - Dipslay
7 - Stack Count
8 - Destroy stack
Enter choice : 1
Enter data : 56
 
Enter choice : 1
Enter data : 80
 
Enter choice : 2
 
Popped value : 80
Enter choice : 3
 
Top element : 56
Enter choice : 1
Enter data : 78
 
Enter choice : 1
Enter data : 90
 
Enter choice : 6
90 78 56
Enter choice : 7
 
No. of elements in stack : 3
Enter choice : 8
 
All stack elements destroyed
Enter choice : 4
 
Stack is empty
Enter choice : 5

Result:

Thus the program implemented successfully.


EX NO:5 (a) Queue using Linked Lists

Program

include <stdio.h>
#include <stdlib.h>
 
struct node
{
int info;
struct node *ptr;
}*front,*rear,*temp,*front1;
 
int frontelement();
void enq(int data);
void deq();
void empty();
void display();
void create();
void queuesize();
 
int count = 0;
 
void main()
{
int no, ch, e;
 
printf("\n 1 - Enque");
printf("\n 2 - Deque");
printf("\n 3 - Front element");
printf("\n 4 - Empty");
printf("\n 5 - Exit");
printf("\n 6 - Display");
printf("\n 7 - Queue size");
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:
exit(0);
case 6:
display();
break;
case 7:
queuesize();
break;
default:
printf("Wrong choice, Please enter correct choice ");
break;
}
}
}
 
/* Create an empty queue */
void create()
{
front = rear = NULL;
}
 
/* Returns queue size */
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);
}
 
/* Dequeing the queue */
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 */
int frontelement()
{
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");
}
$ cc pgm4.c
$ a.out
 
1 - Enque
2 - Deque
3 - Front element
4 - Empty
5 - Exit
6 - Display
7 - Queue size
Enter choice : 1
Enter data : 14
 
Enter choice : 1
Enter data : 85
 
Enter choice : 1
Enter data : 38
 
Enter choice : 3
Front element : 14
Enter choice : 6
14 85 38
Enter choice : 7
 
Queue size : 3
Enter choice : 2
 
Dequed value : 14
Enter choice : 6
85 38
Enter choice : 7
 
Queue size : 2
Enter choice : 4
Queue not empty
Enter choice : 5

Result:

Thus the program implemented successfully.


EX. NO: 6

BINARY SEARCH TREE


AIM:

To write a C program to perform various operations on a binary search tree

ALGORITHM:

CREATION OF BINARY SEARCH TREE:

Step 1: Enter the number of elements in the tree n

Step 2: Enter the n elements into the binary search tree

Step 3: As each element is put into the tree check whether tree is binary

SEARCH TREE PROPERTY IS MAINTAINED:

Step 1: Enter the element to be inserted x

Step 2: If x< root, Keep moving towards the left sub tree

Step 3: If x>root, Keep moving towards right sub tree

Step 4: Perform steps 2 and 3 for the sub trees until the exact location of insertion is

Found

Step 5: Insert at that location and display the new tree using inorder traversal

DELETION OF A NODE:

Step 1: Enter the element to be deleted x

Step 2: If X has no children then it can be deleted immediately

Step 3: If x has no child then adjust the parent’s pointer by passing the node

Step 4: If the node has two children then replace the data in the node with the minimum

Data in the right sub tree of that node and then delete the node recursively

Step 5: Display the new tree using inorder traversal

FINDING THE MINIMUM AND MAXIMUM


Step 1: More towards the left sub tree to find the minimum

Step 2: More towards the right sub tree to find the maximum

PROGRAM :

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#define NULL 0
struct treenode
{ int element;
struct treenode *left;
struct treenode *right;
};
typedef struct treenode *position,*searchtree;
searchtree insert(int x,searchtree t)
{
if(t==NULL)
{
t=(struct treenode*)malloc(sizeof(struct treenode));
if(t==NULL)
exit(0);
else
{
t->element=x;
t->left=t->right=NULL;
}
}
else
if(x<t->element)
t->left=insert(x,t->left);
else
if(x>t->element)
t->right=insert(x,t->right);
return t;
}
position findmin(searchtree t)
{
if(t==NULL)
return NULL;
else
if(t->left==NULL)
return t;
else
return findmin(t->left);
}
position findmax(searchtree t)
{
if(t==NULL)
return NULL;
else
if(t->right==NULL)
return t;
else
return findmax(t->right);
}

searchtree rem(int x,searchtree t)


{
position temp;
if(t==NULL)
printf("\nElement not found");
else
if(x<t->element)
t->left=rem(x,t->left);
else
if(x>t->element)
t->right=rem(x,t->right);
else
if(t->left&&t->right)
{
temp=findmin(t->right);
t->element=temp->element;
t->right=rem(t->element,t->right);
}
else
{
temp=t;
if(t->left==NULL)
t=t->right;
else
if(t->right==NULL)
t=t->left;
free(temp);
}
return t;
}

void intrav(searchtree head)


{
if(head==NULL)
return;
if(head->left!=NULL)
intrav(head->left);
printf("%d\t",head->element);
if(head->right!=NULL)
intrav(head->right);
}

void main()
{
int n,i,dat,ch;
searchtree t=NULL;
position node;
clrscr();
printf("Enter no of elements:\n");
scanf("%d",&n);
printf("Enter the elements:\n");
for(i=1;i<=n;i++)
{
scanf("%d",&dat);
t=insert(dat,t);
}
intrav(t);
do
{
printf("\n\n");
printf("\n ****MENU****\n");
printf("\nEnter 1 -> Insert a node\n");
printf("\n 2 -> Delete a node\n");
printf("\n 3 -> Find Minimum\n");
printf("\n 4 -> Find Maximum\n");
printf("\n 5 -> Display(Inorder Traversal\n");
printf("\n 6 -> Exit\n");
printf("\nEnter your choice:");
scanf("%d",&ch);
switch(ch)
{
case 1:printf("\nEnter the element to be inserted:");
scanf("%d",&dat);
t=insert(dat,t);
break;
case 2:printf("\n Enter the node to be deleted:");
scanf("%d",&dat);
t=rem(dat,t);
break;
case 3:node=findmin(t);
printf("\nThe minimum element is %d",node->element);
break;
case 4:node=findmax(t);
printf("\nThe maximum element is %d",node->element);
break;
case 5:intrav(t);
break;
case 6:exit(0);
}
}while(ch!=6);
getch();
}

OUTPUT:

Enter no of elements:

Enter the elements:


10

2 6 10

****MENU****

Enter 1 -> Insert a node

2 -> Delete a node

3 -> Find Minimum

4 -> Find Maximum

5 -> Display(Inorder Traversal

6 -> Exit

Enter your choice:3

The minimum element is 2

****MENU****

Enter 1 -> Insert a node

2 -> Delete a node

3 -> Find Minimum

4 -> Find Maximum

5 -> Display(Inorder Traversal

6 -> Exit

Enter your choice:6

RESULT:

Thus the C program to implement binary search tree is executed.


EX. NO : 7

INSERTION IN AVL TREE


AIM :

To write a C program to perform insertion in an AVL tree.

ALGORITHM :

Step 1: Read the elements to be inserted into an AVL tree one at a time.

Step 2: Insert each element into an initially empty AVL tree based on the BST tree property.

Step 3: After inserting an element check whether the balance property is maintained.If not then

Step 3.1 :Identify the node at which the balance is lost.

Step 3.2: Find the kind of insertion . If it is left-left or right –right then perform a single
, .

rotation.

Step 3.3: If it is left-right or right-left then perform a double rotation.

Step 4: Repeat steps 2 and 3 till all the elements are inserted.

Step 5: Display the elements present in the AVL tree according to inorder traversal.

PROGRAM:

#include<stdio.h>

#include<stdlib.h>

#include<conio.h>

typedef struct node *pos;

typedef struct node *avltree;

avltree t;

struct node

int element;

avltree left;

avltree right;
int height;

};

avltree insert(int,avltree);

int max(int,int);

int height(pos p);

pos singlerotatewithleft(pos);

pos singlerotatewithright(pos);

pos doublerotatewithleft(pos);

pos doublerotatewithright(pos);

void display(avltree);

void main()

int ch,ele;

clrscr();

t=NULL;

do

printf("\nMENU\n");

printf("\n1. Insertion\n");

printf("\n2. Display\n");

printf("\n3. Exit\n");

printf("\nEnter your choice:");

scanf("%d",&ch);

switch(ch)

case 1: printf("\nEnter the element to be inserted:");

scanf("%d",&ele);

t=insert(ele,t);
printf("\nThe element is inserted");

break;

case 2: printf("\nThe elements in the AVL TREE are:");

display(t);

break;

case 3: exit(0);

break;

}while(ch<4);

getch();

avltree insert(int x,avltree t)

if(t==NULL)

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

if(t==NULL)

exit(0);

else

t->element=x;t->height=0;

t->left=t->right=NULL;

else

if(x<t->element)

t->left=insert(x,t->left);
if(height(t->left)-height(t->right)==2)

if(x<t->left->element)

t=singlerotatewithleft(t);

else

t=doublerotatewithleft(t);

else

if(x>t->element)

t->right=insert(x,t->right);

if(height(t->right)-height(t->left)==2)

if(x>t->left->element)

t=singlerotatewithright(t);

else

t=doublerotatewithright(t);

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

return t;

int height(pos p)

if(p==NULL)

return -1;

else

return p->height;

int max(int p,int q)

{
if(p>q)

return p;

else

return q;

pos singlerotatewithleft(pos k2)

pos k1;

k1=k2->left;

k2->left=k1->right;

k1->right=k2;

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

k1->height=max(height(k1->left),k2->height)+1;

return k1;

pos singlerotatewithright(pos k1)

pos k2;

k2=k1->right;

k1->right=k2->left;

k2->left=k1;

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

k2->height=max(k1->height,height(k2->right))+1;

return k2;

pos doublerotatewithleft(pos k3)

k3->left=singlerotatewithright(k3->left);
return singlerotatewithleft(k3);

pos doublerotatewithright(pos k1)

k1->right=singlerotatewithleft(k1->right);

return singlerotatewithright(k1);

void display(avltree t)

if(t!=NULL)

display(t->left);

printf("\n%d",t->element);

display(t->right);

OUTPUT:

MENU

1. Insertion

2. Display

3. Exit
Enter your choice:1
Enter the element to be inserted:10
The element is inserted

MENU

1. Insertion

2. Display

3. Exit
Enter your choice:2
The elements in the AVL TREE are: 10
MENU

1. Insertion

2. Display

3. Exit
Enter your choice:1
Enter the element to be inserted:20

The element is inserted

MENU

1. Insertion

2. Display

3. Exit
Enter your choice: 3

RESULT:

Thus the C program to implement AVL tree is executed.


EX. NO : 8 :

IMPLEMENTATION OF PRIORITY QUEUE USING BINARY


HEAPS
AIM :

To write a C program to implement a priority queue using binary heap.

ALGORITHM:

Step 1: Enter the maximum number of elements in the priority queue.


Step 2: Initialize the priority queue as follows:
Step 2.1 : Initialize heap size = 0.
Step 2.2 : Initialize heap capacity = maxelements.
Step 2.3 : Allocate space for the maximum number of elements in the priority queue.
Step 3: After performing the required number of insertions and deletions , display the elements in
the heap.

Insertion

Step 1: Enter the element to be inserted.


Step 2: Insert the element in the respective hole by using the percolate up strategy.

DeleteMin:

Step 1: Delete the root of the heap and return it.


Step 2: Percolate down the hole till the right place for the lastelement is found.

PROGRAM :

#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
#include<malloc.h>
typedef struct heapstruct *pqueue;
struct heapstruct
{
int capacity;
int size;
int *elements;
};
void insert(int,pqueue);
pqueue initialize(int);
int deletemin(pqueue);
int isfull(pqueue);
int isempty(pqueue);
void display(pqueue);
void main()
{
pqueue heap;
int i,max,ele,ch,t;
clrscr();
printf("\nEnter the maximum no.of elements in the priority queue:");
scanf("%d",&max);
heap=initialize(max);
do
{
printf("\nMENU\n");
printf("\n1. Insertion\n");
printf("\n2.DeleteMin\n");
printf("\n3. Display\n");
printf("\n4. Exit\n");
printf("\nEnter your choice:");
scanf("%d",&ch);
switch(ch)
{
case 1: printf("\nEnter the element to be inserted:");
scanf("%d",&ele);
insert(ele,heap);
printf("\nThe element is inserted");
break;
case 2: t=deletemin(heap);
printf("\nThe minimum element %d is deleted\n",t);
break;
case 3: printf("\nThe elements in the HEAP are:");
display(heap);
break;
case 4: exit(0);
break;
}
}while(ch<4);
getch();
}
pqueue initialize(int max)
{
pqueue h;
if(max<3)
{
printf("\nPriority queue size is too small\n");
exit(0);
}
h=(heapstruct*)malloc(sizeof(struct heapstruct));
if(h==NULL)
exit(0);
h->elements=(int*)malloc(max+1*sizeof(int));
if(h->elements==NULL)
exit(0);
h->capacity=max;
h->size=0;
return h;
}
void insert(int x,pqueue h)
{
int i;
if(isfull(h))
{
printf("\nPriority queue is full");
return;
}
if(h->size==0)
{
h->elements[1]=x;
h->size++;
}
else
{
for(i=++h->size;h->elements[i/2]>x;i/=2)
h->elements[i]=h->elements[i/2];
h->elements[i]=x;
}
}
int deletemin(pqueue h)
{
int i,child,minelement,lastelement;
if(isempty(h))
{
printf("\nPriority queue is empty");
exit(0);
}
minelement=h->elements[1];
lastelement=h->elements[h->size--];
for(i=1;i*2<=h->size;i=child)
{
child=i*2;
if(child!=h->size&&h->elements[child+1]<h->elements[child])
child++;
if(lastelement>h->elements[child])
h->elements[i]=h->elements[child];
else
break;
}
h->elements[i]=lastelement;
return minelement;
}
void display(pqueue h)
{
int i;
for(i=1;i<=h->size;i++)
printf("\n%d",h->elements[i]);
}
int isfull(pqueue h)
{
if(h->size==h->capacity)
return 1;
else
return 0;
}
int isempty(pqueue h)
{
if(h->size==0)
return 1;
else
return 0;
}

OUTPUT:

Enter the maximum no.of elements in the priority queue:5

MENU
1. Insertion
2.DeleteMin
3. Display
4. Exit
Enter your choice:1
Enter the element to be inserted:40
The element is inserted

MENU
1. Insertion
2.DeleteMin
3. Display
4. Exit
Enter your choice:1
Enter the element to be inserted:30
The element is inserted

MENU
1. Insertion
2.DeleteMin
3. Display
4. Exit
Enter your choice:

RESULT:

Thus the C program to implement priority queue is executed.


EX NO: 9 (a) GRAPH TRAVERSAL
Aim : To implement breadth first search (bfs) and depth first search (dfs) in graphs using adjacency
matrix.

Algorithm:

bfs(ints,int n)

1) list L = empty
2) tree T = empty

3)choose a starting vertex x


4)search(x)
5) while(L nonempty)
6) remove edge (s,n) from start of L
7)if n not yet visited
add (s,n) to T
search(n)
dfs(ints,int n)

1) list L = empty
2) tree T = empty

3)choose a starting vertex x


4)search(x)
5) while(L nonempty)
6) remove edge (s,n) from end of L
7)if n not yet visited
add (s,n) to T
search(n)
Program:

#include<stdio.h>
#include<conio.h>
int q[20],top=-1,front=-1,rear=-1,a[20][20],vis[20],stack[20];
int delete();
void add(int item);
voidbfs(ints,int n);
voiddfs(ints,int n);
void push(int item);
int pop();
void main()
{ intn,i,s,ch,j;
charc,dummy;
clrscr();
printf("\n\n\n\t\t\tDFS and BFS implementation !");
printf("\n\n\nEnter the Number of Nodes in Graph: ");
scanf("%d",&n);
for(i=1;i<=n;i++)
{ for(j=1;j<=n;j++)
{ printf("\nEnter 1 if %d has a NODE with %d else 0 ",i,j);
scanf("%d",&a[i][j]);
}}
printf("\n\n\t\tTheAdjecency Matrix is: ");
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("\n\nMENU");
printf("\n1) B.F.S (Breadth First Search)");
printf("\n2) D.F.S (Depth First Search)");
printf("\n\nEnter your choice: ");
scanf("%d",&ch);
printf("\nEnter source VERTEX:");
scanf("%d",&s);
switch(ch)
{
case 1:bfs(s,n);
break;
case 2:
dfs(s,n);
break;
} printf("\n\nWould you like to continue ?\n\n Yes(Y) or No (N): ");
scanf("%c",&dummy);
scanf("%c",&c);
}while((c=='y')||(c=='Y'));
} void bfs(ints,int n)
{ intp,i;
add(s);
vis[s]=1;
p=delete();
if(p!=0)
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("\n\nQUEUE is FULL: Error No Space!");
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);
}}
voiddfs(ints,int n)
{ inti,k;
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("\n\nStackoverflow.com");
else
stack[++top]=item;
}
int pop()
{ int k;
if(top==-1)
return(0);
else
{ k=stack[top--];
return(k);
}}

Output:
Result
Hence the program for implementing breadth first search (bfs) and depth first search (dfs) in graphs
using adjacency matrix was successfully executed.
EX NO : 9(b) TREE TRAVERSAL
Aim : To implement binary search tree traversal.

Algorithm:

preorder(node)
1) repeat step 2 to step 4 while tree!=NULL
2) write “TREEdata”
3) preorder(Treeleft)
4) Preorder(TreeRight)
5) End

postorder(node)
1) repeat step 2 to step 4 while tree!=NULL
2) postorder(Treeleft)
3) Postorder(TreeRight)
4) Write”TREEdata”
5) End

inorder(node)
1) repeat step 2 to step 4 while tree!=NULL
2) inorder(Treeleft)
3) write “TREEdata”
4) inorder(TreeRight)
5) End

Program:

# include <stdio.h>
# include <conio.h>
# include <stdlib.h>
typedefstruct BST {
int data;
struct BST *lchild, *rchild;
} node;
void insert(node *, node *);
voidinorder(node *);
voidpreorder(node *);
voidpostorder(node *);
node *search(node *, int, node **);
void main() {
int choice;
charans = 'N';
int key;
node *new_node, *root, *tmp, *parent;
node *get_node();
root = NULL;
clrscr();
printf("\nProgram For Binary Search Tree ");
do {
printf("\n--MENU--");
printf("\n1) Create binary search tree");
printf("\n2) Search");
printf("\n3) Recursive Traversals");
printf("\n4) Exit");
printf("\n Enter your choice :");
scanf("%d", &choice);
switch (choice) {
case 1:
do {
new_node = get_node();
printf("\nEnter the element ");
scanf("%d", &new_node->data);
if (root == NULL) /* Tree is not Created */
root = new_node;
else
insert(root, new_node);
printf("\nDo you want to enter more elements?(y/n)");
ans = getch();
} while (ans == 'y');
break;
case 2:
printf("\nEnter the element to be searched :");
scanf("%d", &key);
tmp = search(root, key, &parent);
printf("\nParent of the node %d is %d", tmp->data, parent->data);
break;
case 3:
if (root == NULL)
printf("Tree is not created");
else {
printf("\nTheInorder display -> ");
inorder(root);
printf("\nThePreorder display -> ");
preorder(root);
printf("\nThePostorder display -> ");
postorder(root);
}
break;
}
} while (choice != 4);
}
node *get_node() {
node *temp;
temp = (node *) malloc(sizeof(node));
temp->lchild = NULL;
temp->rchild = NULL;
return temp;
}
void insert(node *root, node *new_node) {
if (new_node->data < root->data) {
if (root->lchild == NULL)
root->lchild = new_node;
else
insert(root->lchild, new_node);
}
if (new_node->data > root->data) {
if (root->rchild == NULL)
root->rchild = new_node;
else
insert(root->rchild, new_node);
}}
node *search(node *root, int key, node **parent) {
node *temp;
temp = root;
while (temp != NULL) {
if (temp->data == key) {
printf("\nThe %d Element is Present", temp->data);
return temp;
}
*parent = temp;
if (temp->data > key)
temp = temp->lchild;
else
temp = temp->rchild;
}
return NULL;
}
voidinorder(node *temp) {
if (temp != NULL) {
inorder(temp->lchild);
printf("%d ", temp->data);
inorder(temp->rchild);
}}
voidpreorder(node *temp) {
if (temp != NULL) {
printf("%d ", temp->data);
preorder(temp->lchild);
preorder(temp->rchild);
}}
voidpostorder(node *temp) {
if (temp != NULL) {
postorder(temp->lchild);
postorder(temp->rchild);
printf("%d ", temp->data);
}}

OUTPUT:
Result : Hence the program for implementing binary search tree traversal was successfully
executed.

EX NO:10 APPLICATIONS OF GRAPHS


DIJKSTRA’S ALGORITHM

AIM:

To implement dijkstra’s algorithm using priority queue to find shortest path

ALGORITHM:

Step 1: Read the no.of vertices n from the user

Step 2: Call the Build_Graph function

Step 3: Read the source src and destination dest from the user

Step 4: Call the dijkstra function

Step 5: Check if (front <= rear) then call the Delete_Q function and assign it to path_node and
goto step 6 else goto step 8

Step 6: Check if(path_node != infinity) then print the path_node and goto step 7 else goto setp 7

Step 7: Increment front by 1

Step 8: Stop

ALGORITHM FOR BUILD_GRAPH FUNCTION

Step 1: Set i as 1

Step 2: Check if (i<=n) then goto step 2

Step 3: Set j as 1

Step 4: Check if (j< = n) then goto step 5 else goto step 7

Step 5: Read the weight between two vertices i and j

Step 6: Increment j by 1

Repeat the step 4 – 6 until the condition is false

Step 7: Increment I by 1

Repeat the steps 2 – 7 until the condition is false

ALGORITHM FOR DIJKSTRA FUNCTION

Step 1: Check if(i<=n) then goto step 2 else goto step 4

Step 2: Set Q[i] as 0 and dist[i] as infinity

Step 3: Increment I by 1
Repeat the step 1 – 3 until the condition is false

Step 4: Set initial distance as 0 for the source node and assign source node as the current node

Step 5: Check if (current ! = dest) then set start as distance of the current node and goto step 6
else goto step 12

Step 6: Check if (i<=n) then goto step 7

Step 7: Check if (Q[i] == 0) then goto step 8

Step 8: Calculate the new distance for the vertex i

Step 9: Check if new value is lesser than the distance of I node then set distance as new one
else goto 10

Step 10: Check if distance of I node is lesser than small then set small as distance of i

Step 11: Increment I by 1

Repeat the steps 6 – 11 until the condition is false

Step 12: Set the current as smallest node

Step 13: Use node in the queue using insert_Q function

PROGRAM:

#include<stdio.h>

#define member 1

#define nomember 0

#define max 10

#define infinity 999

int g[max][max],q[max];

int n;

main()

int src,dest,path_node;

void build_graph();

void dijkstra(int,int);

int delete_q(int);
int front,rear;

printf("\nProgram for shortest path algorithm using priority queue");

printf("\nEnter the no of vertices: ");

scanf("%d", &n);

build_graph();

printf("\nEnter the source: ");

scanf("%d",&src);

printf("\nEnter the destination: ");

scanf("%d", &dest);

dijkstra(src,dest);

printf("\nThe shortest path is ... \n");

front=1;

rear=n;

while(front<=rear)

path_node=delete_q(front);

if(path_node!=infinity)

printf("%d",path_node);

front++;

void build_graph()

int i,j,v1,v2;

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

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

printf("\nEnter the edge of v %d to v %d: ",i,j);

scanf("%d", &g[i][j]);

printf("\n");

void insert_q(int index)

q[index]=1;

int delete_q(int i)

if(q[i]==1)

return i;

return infinity;

void dijkstra(int src,int dest)

int small,dist[10],current,start,new1;

int temp,i;

void insert_q(int);

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

q[i]=0;

dist[i]=infinity;

}
q[src]=1;

dist[src]=0;

current=src;

while(current!=dest)

small=infinity;

start=dist[current];

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

if(q[i]==0)

new1=start+g[current][i];

if(new1<dist[i])

dist[i]=new1;

if(dist[i]<small)

small=dist[i];

temp=i;

current=temp;

insert_q(current);

OUTPUT:
Program for shortest path algorithm using priority queue

Enter the no of vertices: 5

Enter the edge of v 1 to v 1: 999

Enter the edge of v 1 to v 2: 9

Enter the edge of v 1 to v 3: 4

Enter the edge of v 1 to v 4: 999

Enter the edge of v 1 to v 5: 999

Enter the edge of v 2 to v 1: 9

Enter the edge of v 2 to v 2: 999

Enter the edge of v 2 to v 3: 999

Enter the edge of v 2 to v 4: 3

Enter the edge of v 2 to v 5: 999

Enter the edge of v 3 to v 1: 4

Enter the edge of v 3 to v 2: 999

Enter the edge of v 3 to v 3: 999

Enter the edge of v 3 to v 4: 999

Enter the edge of v 3 to v 5: 1

Enter the edge of v 4 to v 1: 999

Enter the edge of v 4 to v 2: 3

Enter the edge of v 4 to v 3: 999

Enter the edge of v 4 to v 4: 999

Enter the edge of v 4 to v 5: 1

Enter the edge of v 5 to v 1: 999

Enter the edge of v 5 to v 2: 999

Enter the edge of v 5 to v 3: 1

Enter the edge of v 5 to v 4: 1


Enter the edge of v 5 to v 5: 999

Enter the source: 1

Enter the destination: 5

The shortest path is ...

135

RESULT:

Thus the C program has written to implement dijkstra’s algorithm using priority queue to
find shortest path and executed.

EX NO :11(a) INSERTION SORT


Aim : To arrange the numbers in ascending order using insertion sort.

Algorithm:

1) Repeat step 2 to 5 for K=1 to n-1

2) Set temp=arr[k]

3) Set j=k-1

4) Repeat while temp <=arr[j]&&j>=0

Set arr[j+1]=arr[j]

Set j=j-1

5) Set arr [j+1] = temp

6) Exit

Program:

#include<stdio.h>
#include<conio.h>
voidinsertion_sort(int a[]);
void main()
{intarr[10],i;
printf("Enter the elements of the array");
for(i=0;i<10;i++)
{
scanf("%d",&arr[i]);
}
insertion_sort(arr);
getch();
}
voidinsertion_sort(int a[])
{
intk,j,temp,n;
n=10;
for(k=1;k<=(n-1);k++)
{
temp=a[k];
j=k-1;
while(temp<=a[j] && j>=0)
{
a[j+1]=a[j];
j=j-1;
}
a[j+1]=temp;
}
printf("sorted array is:");
for(k=0;k<10;k++)
{ printf("%d\n",a[k]);
}
output

Result : The elements were successfully arranged in ascending order using Insertion sort.

EX NO-11(b) SELECTION SORT


Aim : To arrange the numbers in ascending order using selection sort.

Algorithm:

1) Repeat step 2 and 3 for K=1 to n-1


2) Call smallest (arr ,k,n,pos)

3) Swap a[k] with arr[pos]

4) Exit

Smallest(arr,k,n,pos)

1) Set small = arr[k]

2) Set pos=k

3) Repeat for j=k+1 to n-1

If small>arr[j]

Set pos=j

[end of if]

[end of loop]

4) Exit

Program:

#include<stdio.h>
#include<conio.h>
int smallest(intarr[],intk,int n)
{
intsmall,j,pos;
small=arr[k];
pos=k;
for(j=k+1;j<n;j++)
{
if(small>arr[j])
{
small=arr[j];
pos=j;}}
returnpos;
}
void main()
{
inti,arr[6],k,c,temp;
clrscr();
printf("Enter 6 numbers: ");
for(i=0;i<6;i++)
{
scanf("%d",&arr[i]);
}
for(i=0;i<6;i++)
{
c=smallest(arr,i,6);
temp=arr[i];
arr[i]=arr[c];
arr[c]=temp;
}
for(i=0;i<6;i++)
{
printf("%d ",arr[i]);}
getch();
}

Output :

Result : The elements were successfully arranged in ascending order using selection sort.
EX NO-11(c) MERGE SORT
Aim : To sort the given elements using Merge sort.

Algorithm:

Merge _Sort(arr,beg,end)

1) If beg <end then

Set mid =(beg + end)/2

Call Merge _Sort(arr,beg,mid)

Call Merge _Sort(arr,mid+1,end)

Call Merge _Sort(arr,beg,mid,end)

[end of if]

Merge (arr,beg,mid,end)

1) Initialise set i = beg ; j=mid+1 ; index =0

2) Repeat while (i<=mid) and (j<=end)

If arr[i]<arr[j],then

Set temp[index] = arr[i]

Set i=i+1

else

Set temp[index]=arr[j]

Set j=j+1

[End of if]

Set index =index +1

[End of loop]

Merge (arr,beg,mid,end)

3) [Copy the remaining elements of right sub array if any]

If i> mid then

Repeat while j <= end

Set index = index +1


[ end of loop]
[copy the remaining elements of left sub. Array ,if any]
else
repeat while i<= mid
set temp[index]=arr[i]
set index = index + 1,sort i = i+1
[end of loop]

program:
#include<stdio.h>
#include<conio.h>
intarr[10];
voidmerge_sort(intarr[],int beg, int end);
void merge(int a[],intbeg,intmid,int end);
void main()
{
inti;
clrscr();
printf("Enter the array");
for(i=0;i<10;i++)
{
scanf("%d",&arr[i]);
}
merge_sort(arr,0,9);
printf("array");
for(i=0;i<10;i++)
{
printf("%d",&arr[i]);
}
getch();
}
voidmerge_sort(intarr[],intbeg,int end)
{inti;
if(beg<end)
{int mid=(beg+end)/2;
merge_sort(arr,beg,mid);
merge_sort(arr,mid+1,end);
merge(arr,beg,mid,end);
}}
void merge(intarr[],intbeg,intmid,int end)
{inti,j,index,temp[10];
i=beg;
j=mid+1;
index=beg;
while(i<=mid && j<=end)
{if(arr[i]<arr[j])
{temp[index]=arr[i];
i=i+1;
}
else
{temp[index]=arr[j];
j=j+1;
}
index=index+1;
}
if(i>mid)
{ while(j<=end)
{ temp[index]=arr[j];
index=index+1;
j=j+1;
}}
Else
{ while(i<=mid)
{temp[index]=arr[i];
index=index+1;
i=i+1;
}}
for(i=beg;i<index;i++)
{ arr[i]=temp[i];
}}

Output

Result : Hence the program for Sorting an array using merge sort was successfully executed.
EX NO :11(D) BINARY SEARCH

BINARY SEARCH PROGRAM

#include <stdio.h>
 
int main()
{
int c, first, last, middle, n, search, array[100];
 
printf("Enter number of elements\n");
scanf("%d",&n);
 
printf("Enter %d integers\n", n);
 
for (c = 0; c < n; c++)
scanf("%d",&array[c]);
 
printf("Enter value to find\n");
scanf("%d", &search);
 
first = 0;
last = n - 1;
middle = (first+last)/2;
 
while (first <= last) {
if (array[middle] < search)
first = middle + 1;
else if (array[middle] == search) {
printf("%d found at location %d.\n", search,
middle+1);
break;
}
else
last = middle - 1;
 
middle = (first + last)/2;
}
if (first > last)
printf("Not found! %d isn't present in the
list.\n", search);
 
return 0;
}

Result : Hence the program was successfully executed.


EX. NO : 12
HASHING WITH OPEN ADDRESSING
AIM:
To write a C program to implement hashing with open addressing

ALGORITHM:

Step 1: Read the elements to be entered into the hash table one at a time.

Step 2: Using create() function generate the hash key.The hash function used is number %10.

Step 3: The linear_prob() function is used to handle the collision. If the location indicated by hash
key is empty then place the element in the hash table.Otherwise move linearly down searching for
an empty location and place the number at the empty location encountered.

Step 4: The display() function is used to display the hash table.

PROGRAM:

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#deine MAX 10
void main()
{
int a[MAX],num,key,i;
char ans;
int create(int);
void linear_prob(int[],int,int);
void display(int[]);
clrscr();
printf("\nCollision Handling by Linear Probing");
for(i=0;i<MAX;i++)
a[i]=-1;
do
{
printf("\nEnter the number:");
scanf("%d",&num);
key=create(num);
linear_prob(a,key,num);
printf("\nDo you want to continue?");
ans=getch();
}while(ans=='y');
display(a);
}
int create(int num)
{
int key;
key=num%10;
return key;
}
void linear_prob(int a[MAX],int key,int num)
{
int flag,i,count=0;
void display(int a[]);
flag=0;
if(a[key]==-1)
a[key]=num;
else
{
i=0;
while(i<MAX)
{
if(a[i]!=-1)
count++;
i++;
}
if(count==MAX)
{
printf("\nHash Table is full");
display(a);
getch();
exit(1);
}
for(i=key+1;i<MAX;i++)
if(a[i]==-1)
{
a[i]=num;
flag=1;
break;
}
for(i=0;i<key&&flag==0;i++)
if(a[i]==-1)
{
a[i]=num;
flag=1;
break;
}
}
}
void display(int a[MAX])
{
int i;
printf("\nThe Hash Table is ...\n");
for(i=0;i<MAX;i++)
printf("\n %d %d",i,a[i]);
}

OUTPUT:

Collision Handling by Linear Probing


Enter the number:10

Do you want to continue?


Enter the number:
11

Do you want to continue?


Enter the number:15

Do you want to continue?


Enter the number:19

Do you want to continue?


Enter the number:20

Do you want to continue?


Enter the number:25

Do you want to continue?


Enter the number:17

Do you want to continue?


The Hash Table is ...

0 10
1 11
2 20
3 -1
4 -1
5 15
6 25
7 17
8 -1
9 19

RESULT :
Thus the c program to implement hashing with open addressing is executed.
CONTENT BEYOND SYLLABUS
EX NO:13 PRIMS ALGORITHM

AIM:

To write a C program to implement prim’s algorithm.

ALGORITHM:

Step 1: Start

Step 2: Read the no.of vertices n from the user

Step 3: To read the adjacency matrix check if (i<n) then set visible[i] as 0 and goto step 4
else goto step 8

Step 4: Check if (j<n) then read the cost then goto step 5 else goto step 7

Step 5: Check if (cost == 0) then set cost as 99 and goto step 6

Step 6: Increment j value by 1


Repeat the steps 4 – 6 until the condition is false

Step 7: Increment i by 1
Repeat the steps 3 – 7 until the condition is false

Step 8: Check if (count<n) then goto step 9 else print the total weight and goto step 15

Step 9: Check if (i<n) then goto step 10 else Increment count value by 1

Step 10: Check if (j<n) then goto step 11 else goto 14

Step 11: Check if (visible[j] ==0) then increment j by 1 and goto step 12

Step 12: Check if (cost<min) then set cost as min and calculate weight by using wt = wt + min

Step 13: Print i, j and wt values

Step 14: Increment i by 1

Step 15: Stop


PROGRAM:

#include<stdio.h>

main()

int i,j,n,min,u,v,cost[10][10],visible[10],wt=0,count;

printf("\n\t\t PRIMS ALGORITHM");

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

printf("\n enter the no of vertice");

scanf("%d",&n);

printf("\n enter the adjacent matrix");

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

visible[i]=0;

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

scanf("%d",&cost[i][j]);

if(cost[i][j]==0)

cost[i][j]=99;

visible[0]=count=1;

printf("\n edges of minimum spanning trees");

while(count<n)

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

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

if(visible[j]==0)

j++;

if(cost[i][j]<min)

min=cost[i][j];

visible[j]=1;

wt=wt+min;

printf("u=%d,v=%d,w=%d\n",i,j,wt);

count++;

printf("\n\nMinimum spanning tree is %d",wt);

}}

/*sample o/p:
PRIMS ALGORITHM
--------------
enter the no of vertice3
enter the adjacent matrix
012
103
230
edges of minimum spanning treesu=0,v=2,w=2
u=1,v=0,w=3
Minimum spanning tree is 3 */

RESULT:
Thus the C program has written to implement prim’s algorithm and executed.

You might also like