Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
9 views70 pages

Final DS Lab Manual1

Uploaded by

trialwithzeeshan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views70 pages

Final DS Lab Manual1

Uploaded by

trialwithzeeshan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 70

LORDS INSTITUTE OF ENGINEERING & TECHNOLOGY

(Autonomous)

Department of CSE-AIML
DATA STRUCTURES Lab Manual

Course Name : DATA STRUCTURES LAB

Course Code : U24CS3L1

Class : BE – II, Semester – III

Branch : CSE -AIML

Academic Year : 2025 – 2026

Prepared By : Mohammad Hozaifa

Assistant Professor, Department of AIML

OBJECTIVES

To meet the challenge of ensuring excellence in engineering education, the issue of quality
needs to be addressed, debated and taken forward in a systematic manner. Accreditation is
the principal means of quality assurance in higher education. The major emphasis of
accreditation process is to measure the outcomes of the program that is beingaccredited.

In line with this, Faculty of Institute of Aeronautical Engineering, Hyderabad has taken a lead
in incorporating philosophy of outcome-based education in the process of problem solving and
career development. So, all students of the institute should understand the depth and
approach of course to be taught through this question bank, which will enhance learner’s
learning process.
Course Code Course Title Core

U24CS3L1 DATA STRUCTURES LAB Core

Hours Per Week


CIE SEE Credits
Prerequisite L T D P

PPS Lab - - - 3 25 50 1.5

Course Objectives:

Develop ability to

1. Develop skills to design and analyze simple linear and nonlinear data structures, such as stacks,
queues and lists and their applications.
2. Gain programming skills to implement sorting and searching algorithms
3. Strengthen the ability to identify and apply the suitable data structures for the given real world
problem.
4. Gain knowledge in practical applications of data structures
5. Understand essential for future programming and software engineering courses.
Course Outcomes:

At the end of the course, student would be able to


1. Implement various kinds of sorting techniques and apply appropriate techniques for solving a
given problem
2. Implement various data structures using arrays, linked lists
3. Develop ADT necessary for solving problems based on Stacks and Queues
4. Implement binary trees, general tree structures, advanced search trees, heaps, graphs.
5. Implement hash functions and handle collisions.

List of Experiments:
1.Implementation of Binary Search and Linear Search.
2. Implementation of Selection, Merge, Quick, and Insertion Sort.
3. Implementation of Stacks and Queues using Arrays.
4. Implementation of Infix to Postfix Conversion, Postfix Expression Evaluation.
5. Implementation of Circular Queue using Arrays.
6. Implementation of Singly Linked List
7. Implementation of Doubly Linked List.
8. Implementation of Circular Linked List.
9. Implementation of Stacks, Queues using Linked Lists.
10. Implementation of Binary Search Tree. (Insertion, Deletion, and Search operations)
11. Implementation of Tree Traversal on Binary Trees.
12. Implementation of AVL Trees.
13. Implementation of Traversal on Graphs.
14. Implementation of Prim’s and Kruskal’s Algorithm.
Suggested Readings:

1.S. Lipschutz, “Data Structures”, Tata McGraw Hill Education, 1st Edition, 2008.
2. D. Samanta, “Classic Data Structures”, PHI Learning, 2nd Edition, 2004.
3. Mark A Weiss, Data Structures and Algorithm Analysis In C, Second Edition (2002),
Pearson.
1. a) Implementation of Linear Search:
#include<stdio.h>
void main() {
int a[20], i, n, key, flag = 0, pos;
scanf("%d", &n);
//Write your code here...
//Read element of Array
for(i=0;i<n;i++){
scanf("%d", &a[i]);
}
//Read the element to search
scanf("%d", &key);
//Linear Search;
for(i=0;i<n;i++){
if(a[i]==key){
flag=1;
pos=i;
break;
}
}
if (flag == 1) {
printf("found at position %d\n", pos);
} else {
printf("%d not found\n", key);
}
}

Output:
b) Implementation of Binary Search:

#include<stdio.h>
int main(){
int a[100],n, key;
int low,high,mid;
int found=0;
//Read size of array
scanf("%d", &n);
//Read sorted element
for(int i=0;i<n;i++){
scanf("%d", &a[i]);
}
//Read the Target element
scanf("%d", &key);
//Binary Search
low=0;
high=n-1;
while(low <= high){
mid=(low+high)/2;
if(a[mid]==key){
printf("Element found at index %d\n", mid);
found=1;
break;
}
else if(a[mid]<key){
low=mid+1;
}
else{
high=mid-1;
}
}
if(!found){
printf("Element not found\n");
}
return 0;
}
2. Implementation of Selection, Merge Quick and Insertion Sort.
//Selection sort
#include<stdio.h>
void main( )
{
int i,j,t,n,min,a[10];
//clrscr( );
printf("\n How many elements you want to sort? ");
scanf("%d",&n);
printf("\Enter elements for an array:");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
for(i=0;i<n;i++)
{
min=i;
for(j=i+1;j<n;j++)
if(a[j] < a[min])
{
min=j;
}
t=a[i];
a[i]=a[min];
a[min]=t;
} printf("\nAfter sorting the elements are:");
for(i=0;i<n;i++)
printf("%d ",a[i]);
//getch( );
}
Output:
How many elements you want to sort? 3
ter elements for an array:12
1
23
After sorting the elements are:1 12 23
// Merge Sort
#include<stdio.h>
void disp( );
void mergesort(int,int,int);
void msortdiv(int,int);
int a[50],n;
void main( )
{
int i;
//clrscr( );
printf("\nEnter the n value:");
scanf("%d",&n);
printf("\nEnter elements for an array:");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("\nBefore Sorting the elements are:");
disp( );
msortdiv(0,n-1);
printf("\nAfter Sorting the elements are:");
disp( );
//getch( );
}
void disp( )
{
int i;
for(i=0;i<n;i++)
printf("%d ",a[i]);
}
void mergesort(int low,int mid,int high)
{
int t[50],i,j,k;
i=low;
j=mid+1;
k=low;
while((i<=mid) && (j<=high))
{
if(a[i]>=a[j])
t[k++]=a[j++];
else
t[k++]=a[i++];
}
while(i<=mid)
t[k++]=a[i++];
while(j<=high)
t[k++]=a[j++];
for(i=low;i<=high;i++)
a[i]=t[i];
}
void msortdiv(int low,int high)
{
int mid;
if(low!=high)
{
mid=((low+high)/2);
msortdiv(low,mid);
msortdiv(mid+1,high);

mergesort(low,mid,high);
}
}
Output:
Enter the n value:4
Enter elements for an array:34
5
6
12
Before Sorting the elements are:34 5 6 12
After Sorting the elements are:5 6 12 34
// Quick Sort

#include<stdio.h>
void quicksort(int[ ],int,int);
void main( )
{
int low, high, pivot, t, n, i, j, a[10];
//clrscr( );
printf("\nHow many elements you want to sort ? ");
scanf("%d",&n);
printf("\Enter elements for an array:");
for(i=0; i<n; i++)
scanf("%d",&a[i]);
low=0;
high=n-1;
quicksort(a,low,high);
printf("\n After Sorting the elements are:");
for(i=0;i<n;i++)
printf("%d ",a[i]);
//getch( );
}
void quicksort(int a[ ],int low,int high)
{
int pivot,t,i,j;
if(low<high)
{
pivot=a[low];
i=low+1;
j=high;
while(1)
{
while(pivot>a[i]&&i<=high)
i++;
while(pivot<a[j]&&j>=low)
j--;
if(i<j)
{
t=a[i];
a[i]=a[j];
a[j]=t;
}
else
break;
}
a[low]=a[j];
a[j]=pivot;
quicksort(a,low,j-1);
quicksort(a,j+1,high);
}
}

Output:
How many elements you want to sort ? 4
Enter elements for an array: 34 2 65 12
After Sorting the elements are: 2 12 34 65
// Insertion Sort
#include<stdio.h>
#include<conio.h>
void main( )
{
int a[10],i,j,k,n;
// clrscr( );
printf("How many elements you want to sort?\n");
scanf("%d",&n);
printf("\nEnter the Elements into an array:\n");
for (i=0;i<n;i++)
scanf("%d",&a[i]);
for(i=1;i<n;i++)
{
k=a[i];
for(j= i-1; j>=0 && k<a[j]; j--)
a[j+1]=a[j];
a[j+1]=k;
} printf("\n\n Elements after sorting: \n");
for(i=0;i<n;i++)
printf("%d\n", a[i]);
//getch( );
}

Output:
How many elements you want to sort?
4
Enter the Elements into an array:
34
56
76
8
Elements after sorting:
8
34
56
76
3. a) Implementation of Stack Using Array

#include <stdio.h>
int stack[100],i,j,choice=0,n,top=-1;
void push();
void pop();
void show();
void main ()
{
printf("Enter the number of elements in the stack ");
scanf("%d",&n);
printf("*********Stack operations using array*********");
printf("\n \n");
while(choice != 4)
{
printf("Chose one from the below options...\n");
printf("\n1.Push\n2.Pop\n3.Show\n4.Exit");
printf("\n Enter your choice \n");
scanf("%d",&choice);
switch(choice)
{
case 1:
{
push();
break;
}
case 2:
{
pop();
break;
}
case 3:
{
show();
break;
}
case 4:
{
printf("Exiting... ");
break;
}
default:{
printf("Please Enter valid choice ");
}
};
}
}
void push ()
{
int val;
if (top == n )
printf("\n Overflow");
else
{
printf("Enter the value?");
scanf("%d",&val);
top = top +1;
stack[top] = val;
}
}
void pop ()
{
if(top == -1)
printf("Underflow");
else
top = top -1;
}
void show()
{
for (i=top;i>=0;i--)
{
printf("%d\n",stack[i]);
}
if(top == -1)
{
printf("Stack is empty");
}
}
b) Implementation of Queue Using Array:
#include<stdio.h>
#include<stdlib.h>
#define maxsize 5
void insert();
void delete();
void display();
int front = -1, rear = -1;
int queue[maxsize];
void main ()
{
int choice;
while(choice != 4)
{
printf("\n*************************Main Menu*****************************\n");
printf("\n=================================================================\n");
printf("\n1.insert an element\n2.Delete an element\n3.Display the queue\n4.Exit\n");
printf("\nEnter your choice ?");
scanf("%d",&choice);
switch(choice)
{
case 1:
insert();
break;
case 2:
delete();
break;
case 3:
display();
break;
case 4:
exit(0);
break;
default:
printf("\nEnter valid choice??\n");
}
}
}
void insert()
{
int item;
printf("\nEnter the element\n");
scanf("\n%d",&item);
if(rear == maxsize-1)
{
printf("\nOVERFLOW\n");
return;
}
if(front == -1 && rear == -1)
{
front = 0;
rear = 0;
}
else
{
rear = rear+1;
}
queue[rear] = item;
printf("\nValue inserted ");

}
void delete()
{
int item;
if (front == -1 || front > rear)
{
printf("\nUNDERFLOW\n");
return;
}
else
{
item = queue[front];
if(front == rear)
{
front = -1;
rear = -1 ;
}
else
{
front = front + 1;
}
printf("\nvalue deleted ");
}
}
void display()
{
int i;
if(rear == -1)
{
printf("\nEmpty queue\n");
}
else
{ printf("\nprinting values ...... \n");
for(i=front;i<=rear;i++)
{
printf("\n%d\n",queue[i]);
}
}
}

Output:

*************************Main Menu*****************************

=================================================================

1. insert an element
2. Delete an element
3. Display the queue
4.Exit
Enter your choice ?1
Enter the element
10
Value inserted
*************************Main Menu*****************************

=================================================================

1.insert an element
2.Delete an element
3.Display the queue
4.Exit
Enter your choice ?1
4.Implementation of Infix to Postfix Conversion. Postfix Expression Evaluation.

#define SIZE 50 /* Size of Stack */


#include <ctype.h>
#include <stdio.h>

char s[SIZE];
int top = -1; /* Global declarations */

/* Function to remove spaces from given string */


void RemoveSpaces(char* source) {
char* i = source;
char* j = source;
while(*j != 0) {
*i = *j++;
if(*i != '')
i++;
}
*i = 0;
}

/* Function for PUSH operation */


void push(char elem) {
s[++top] = elem;
}

/* Function for POP operation */


char pop() {
return (s[top--]);
}

/* Function for precedence */


int pr(char elem) {
switch (elem) {
case '#':
return 0;
case '(':
return 1;
case '+':
case '-':
return 2;
case '*':
case '/':
return 3;
}
}

/*
* Function to convert from infix to postfix expression
*/
void infix_to_postfix(char *infix, char *postfix) {
char ch, elem;
int i = 0, k = 0;

RemoveSpaces(infix);
push('#');

while ((ch = infix[i++]) != '\n') {


if (ch == '(')
push(ch);
else if (isalnum(ch))
postfix[k++] = ch;
else if (ch == ')') {
while (s[top] != '(')
postfix[k++] = pop();
elem = pop(); /* Remove ( */
} else { /* Operator */
while (pr(s[top]) >= pr(ch))
postfix[k++] = pop();
push(ch);
}
}

while (s[top] != '#') /* Pop from stack till empty */


postfix[k++] = pop();

postfix[k] = 0; /* Make postfix as valid string */


}
/*
* Function to evaluate a postfix expression*/
int eval_postfix(char *postfix) {
char ch;
int i = 0, op1, op2;
while((ch = postfix[i++]) != 0) {
if(isdigit(ch))
push(ch-'0'); /* Push the operand */
else { /* Operator,pop two operands */
op2 = pop();
op1 = pop();
switch(ch) {
case '+' : push(op1+op2);
break;
case '-' : push(op1-op2);
break;
case '*' : push(op1*op2);
break;
case '/' : push(op1/op2);
break;
}
}
}
return s[top];
}void main() { /* Main Program */char infx[50], pofx[50];
printf("\nInput the infix expression: ");
fgets(infx, 50, stdin);
infix_to_postfix(infx, pofx);
printf("\nGiven Infix Expression: %sPostfix Expression: %s", infx, pofx);
top = -1;
printf("\nResult of evaluation of postfix expression : %d", eval_postfix(pofx));
}

Output:
Input the infix expression: 2*3+4
Given Infix Expression: 2*3+4
Postfix Expression: 23*4+
Result of evaluation of postfix expression : 10
5.Implementation of Circular Queue Using C
#include <stdio.h>
# define max 6
int queue[max]; // array declaration
int front=-1;
int rear=-1;
// function to insert an element in a circular queue
void enqueue(int element)
{
if(front==-1 && rear==-1) // condition to check queue is empty
{
front=0;
rear=0;
queue[rear]=element;
}
else if((rear+1)%max==front) // condition to check queue is full
{
printf("Queue is overflow..");
}
else
{
rear=(rear+1)%max; // rear is incremented
queue[rear]=element; // assigning a value to the queue at the rear position.
}
}
// function to delete the element from the queue
int dequeue()
{
if((front==-1) && (rear==-1)) // condition to check queue is empty
{
printf("\nQueue is underflow..");
}
else if(front==rear)
{
printf("\nThe dequeued element is %d", queue[front]);
front=-1;
rear=-1;
}
else
{
printf("\nThe dequeued element is %d", queue[front]);

front=(front+1)%max;
}
}
// function to display the elements of a queue
void display()
{
int i=front;
if(front==-1 && rear==-1)
{
printf("\n Queue is empty..");
}
else
{
printf("\nElements in a Queue are :");
while(i<=rear)
{
printf("%d,", queue[i]);
i=(i+1)%max;
}
}
}
int main()
{
int choice=1,x; // variables declaration
while(choice<4 && choice!=0) // while loop
{
printf("\n Press 1: Insert an element");
printf("\nPress 2: Delete an element");
printf("\nPress 3: Display the element");
printf("\nEnter your choice");
scanf("%d", &choice);
switch(choice)
{
case 1:
printf("Enter the element which is to be inserted");
scanf("%d", &x);
enqueue(x);
break;
case 2:
dequeue();
break;

case 3:
display();
}}
return 0;
}
Output:
Press 1: Insert an element
Press 2: Delete an element
Press 3: Display the element
Enter your choice1
Enter the element which is to be inserted100
Press 1: Insert an element
Press 2: Delete an element
Press 3: Display the element
Enter your choice1
Enter the element which is to be inserted200
Press 1: Insert an element
Press 2: Delete an element
Press 3: Display the element
Enter your choice3
Elements in a Queue are :100,200,
Press 1: Insert an element
Press 2: Delete an element
Press 3: Display the element
Enter your choice2
The dequeued element is 100
Press 1: Insert an element
Press 2: Delete an element
Press 3: Display the element
Enter your choice3
Elements in a Queue are :200,
Press 1: Insert an element
Press 2: Delete an element
Press 3: Display the element
Enter your choice
6. Implementation of Singly Linked List Using C

#include<stdio.h>
#include<string.h>
#include<math.h>
#include<stdlib.h>
typedef struct Node {
int data;
struct Node* link;
}Node;
Node *root=NULL;
void Insert() {
Node *temp;
temp=( Node*)malloc(sizeof( Node));
printf("Enter The element to be Inserted: ");
scanf("%d",&temp->data);
temp->link=NULL;
if(root==NULL)
root=temp;
else {
Node *p;
p=root;
while(p->link!=NULL) {
p=p->link;
}
p->link=temp;
}
}
int Length() {
int count=0;
Node *temp;
temp=root;
while(temp!=NULL) {
count++; temp=temp->link;
}
return (count);
}
void addbegin() {
Node *temp;
temp=( Node*)malloc(sizeof( Node));
printf("Enter The element");
scanf("%d",&temp->data);
if(root==NULL)
root=temp;
else {
temp->link = root;
root = temp;
}
}
void addanywhere() {
Node *temp,*p;
int loc,i=1;
printf("\nEnter the location where you want to enter data");
scanf("%d",&loc);
if(loc>Length()) {
printf("\nInvalid location\n");
printf("current lenght of list is %d so enter value under it\n",Length());
}
else {
p=root;
while (i<loc) {
p=p->link; i++;
}
temp=( Node *)malloc(sizeof( Node));
printf("\nEnter The element you want to add");
scanf("%d",&temp->data);
28temp->link=p->link; p->link=temp;
}
}
void display() {
Node *temp;
temp=root;
if(temp==NULL)
printf("\nNo elements in list");
else {
while (temp!=NULL) {
printf("%d\t",temp->data); temp=temp->link;
}
}
}
void Delete() {
Node* temp;
int loc;
printf("\nEnter Location to delete: ");
scanf("%d",&loc);
if(loc>Length())
printf("Invalid Location");
else if(loc==1) {
temp=root;
root=temp->link;
temp->link=NULL;
free(temp);
}
else {
Node* p = root, *q;
int i=1;
while(i<loc-1) {
p=p->link;
i++;
}
q=p->link;
p- >link=q->link;
29free(q);
}
}
int main() {
int choice;
while(1) {
printf("\nChoose the option:");
printf("\n\n1.Insert data\n");
printf("2.Add at begning\n");
printf("3.Add after specific\n");
printf("4.Length\n");
printf("5.Display all elements\n");
printf("6.Delete Element\n");
printf("7.Quit\n");
scanf("%d",&choice);
switch (choice) {
case 1:
Insert(); break;
case 2:
addbegin(); break;
case 3:
addanywhere(); break;
case 4:
if(Length()==0) {
printf("List have no element");
break;
}
printf("The Length of current list is %d",Length());
break;
case 5:
display(); break;
case 6:
Delete(); break;
case 7:
exit(0); break;
default:
printf("wrong choice entered"); break;
}
}
return 0;
}
Output:

Choose the option:


1.Insert data
2.Add at begning
3.Add after specific
4.Length
5.Display all elements
6.Delete Element
7.Quit
1
Enter The element to be Inserted: 100
Choose the option:
1.Insert data
2.Add at begning
3.Add after specific
4.Length
5.Display all elements
6.Delete Element
7.Quit
2
Enter The element20
7. Implementation of Doubly Linked List Using C.
#include<stdio.h>
#include<stdlib.h>
struct node
{
struct node *prev;
struct node *next;
int data;
};
struct node *head;
void insertion_beginning();
void insertion_last();
void insertion_specified();
void deletion_beginning();
void deletion_last();
void deletion_specified();
void display();
void search();
void main ()
{
int choice =0;
while(choice != 9)
{
printf("\n*********Main Menu*********\n");
printf("\nChoose one option from the following list ...\n");
printf("\n===============================================\n");
printf("\n1.Insert in begining\n2.Insert at last\n3.Insert at any random location\n4.Delete from
Beginning\n
5.Delete from last\n6.Delete the node after the given data\n7.Search\n8.Show\n9.Exit\n");
printf("\nEnter your choice?\n");
scanf("\n%d",&choice);
switch(choice)
{
case 1:
insertion_beginning();
break;
case 2:
insertion_last();
break;
case 3:
insertion_specified();
break;
case 4:
deletion_beginning();
break;
case 5:
deletion_last();
break;
case 6:
deletion_specified();
break;
case 7:
search();
break;
case 8:
display();
break;
case 9:
exit(0);
break;
default:
printf("Please enter valid choice..");
}
}
}
void insertion_beginning()
{
struct node *ptr;
int item;
ptr = (struct node *)malloc(sizeof(struct node));
if(ptr == NULL)
{
printf("\nOVERFLOW");
}
else
{
printf("\nEnter Item value");
scanf("%d",&item);

if(head==NULL)
{
ptr->next = NULL;
ptr->prev=NULL;
ptr->data=item;
head=ptr;
}
else
{
ptr->data=item;
ptr->prev=NULL;
ptr->next = head;
head->prev=ptr;
head=ptr;
}
printf("\nNode inserted\n");
}
}
void insertion_last()
{
struct node *ptr,*temp;
int item;
ptr = (struct node *) malloc(sizeof(struct node));
if(ptr == NULL)
{
printf("\nOVERFLOW");
}
else
{
printf("\nEnter value");
scanf("%d",&item);
ptr->data=item;
if(head == NULL)
{
ptr->next = NULL;
ptr->prev = NULL;
head = ptr;
}
else
{
temp = head;
while(temp->next!=NULL)
{
temp = temp->next;
}
temp->next = ptr;
ptr ->prev=temp;
ptr->next = NULL;
}

}
printf("\nnode inserted\n");
}
void insertion_specified()
{
struct node *ptr,*temp;
int item,loc,i;
ptr = (struct node *)malloc(sizeof(struct node));
if(ptr == NULL)
{
printf("\n OVERFLOW");
}
else
{
temp=head;
printf("Enter the location");
scanf("%d",&loc);
for(i=0;i<loc;i++)
{
temp = temp->next;
if(temp == NULL)
{
printf("\n There are less than %d elements", loc);
return;
}
}
printf("Enter value");
scanf("%d",&item);
ptr->data = item;
ptr->next = temp->next;
ptr -> prev = temp;
temp->next = ptr;
temp->next->prev=ptr;
printf("\nnode inserted\n");
}
}
void deletion_beginning()
{
struct node *ptr;
if(head == NULL)
{
printf("\n UNDERFLOW");
}
else if(head->next == NULL)
{
head = NULL;
free(head);
printf("\nnode deleted\n");
}
else
{
ptr = head;
head = head -> next;
head -> prev = NULL;
free(ptr);
printf("\nnode deleted\n");
}
}
void deletion_last()
{
struct node *ptr;
if(head == NULL)
{
printf("\n UNDERFLOW");
}
else if(head->next == NULL)
{
head = NULL;
free(head);
printf("\nnode deleted\n");
}
else
{
ptr = head;
if(ptr->next != NULL)
{
ptr = ptr -> next;
}
ptr -> prev -> next = NULL;
free(ptr);
printf("\nnode deleted\n");
}
}
void deletion_specified()
{
struct node *ptr, *temp;
int val;
printf("\n Enter the data after which the node is to be deleted : ");
scanf("%d", &val);
ptr = head;
while(ptr -> data != val)
ptr = ptr -> next;
if(ptr -> next == NULL)
{
printf("\nCan't delete\n");
}
else if(ptr -> next -> next == NULL)
{
ptr ->next = NULL;
}
else
{
temp = ptr -> next;
ptr -> next = temp -> next;
temp -> next -> prev = ptr;
free(temp);
printf("\nnode deleted\n");
}
}
void display()
{
struct node *ptr;
printf("\n printing values...\n");
ptr = head;
while(ptr != NULL)
{
printf("%d\n",ptr->data);
ptr=ptr->next;
}
}
void search()
{
struct node *ptr;
int item,i=0,flag;
ptr = head;
if(ptr == NULL)
{
printf("\nEmpty List\n");
}
else
{
printf("\nEnter item which you want to search?\n");
scanf("%d",&item);
while (ptr!=NULL)
{
if(ptr->data == item)
{
printf("\nitem found at location %d ",i+1);
flag=0;
break;
}
else
{
flag=1;
}
i++;
ptr = ptr -> next;
}
if(flag==1)
{
printf("\nItem not found\n");
}
}
}
Output:

DOUBLY LINKED LIST IMPLEMENTATION OF LIST ADT


1. INSERT 2. DELETE 3. FIND 4. PRINT 5. QUIT
Enter the choice :: 1
Enter the element to be inserted :: 12
Enter the position of the element :: 1
1. INSERT 2. DELETE 3. FIND 4. PRINT 5. QUIT
Enter the choice :: 4
The list element are :: 12
8.Implementation of Circular linked List using C.
#include<stdio.h>
#include<stdlib.h>
struct Node;
typedef struct Node
* PtrToNode;
typedef PtrToNode
List;
typedef PtrToNode
Position; struct Node
{
int e; Position next;
};

void Insert(int x, List l, Position p)


{
Position TmpCell;
TmpCell = (struct Node*) malloc(sizeof(struct Node));
if(TmpCell == NULL)
printf("Memory out of space\n"); else
{
TmpCell->e = x;
TmpCell->next = p->next; p->next =
TmpCell;
}
}
int isLast(Position p, List l)
{
return (p->next == l);
}
Position

FindPrevious(int x, List l)
{
Position p = l;
while(p->next != l && p->next->e != x) p
= p->next;
return p;
}
Position Find(int x, List l)
{
Position p = l->next; while(p != l && p->e != x)

p = p->next; return p;
}
void Delete(int x, List l)
{
Position p, TmpCell; p = FindPrevious(x, l);
if(!isLast(p, l))
{
TmpCell = p->next;
p->next = TmpCell->next;
free(TmpCell);
}
else
printf("Element does not exist!!!\n");
}
void Display(List l)
{
printf("The list element are :: ");
Position p = l->next;
while(p != l)
{
printf("%d ->", p->e); p = p->next;
}
}
void main()
{
int x, pos, ch, i; List l, l1;
l = (struct Node *) malloc(sizeof(struct Node));
l->next = l;
List p = l;
printf("CIRCULAR LINKED LIST IMPLEMENTATION OF LIST ADT\n\n");
do
{
printf("\n\n1. INSERT\t 2. DELETE\t 3. FIND\t 4. PRINT\t 5. QUIT\n\nEnter the choice :: ");
scanf("%d", &ch);
switch(ch)
{
case 1:

p = l;
printf("Enter the element to be inserted :: ");
scanf("%d",&x);
printf("Enter the position of the element :: ");
scanf("%d",&pos);
for(i = 1; i < pos; i++)
{
p = p->next;
}
Insert(x,l,p); break;
case 2:
p = l;
printf("Enter the element to be deleted :: ");
scanf("%d",&x);
Delete(x,p); break;

case 3:
p = l;
printf("Enter the element to be searched :: "); scanf("%d",&x);
p = Find(x,p); if(p == l)
printf("Element does not exist!!!\n");
else
printf("Element exist!!!\n"); break;
case 4: Display(l); break;
}
}while(ch<5); return 0;
}

Output:

CIRCULAR LINKED LIST IMPLEMENTATION OF LIST ADT

1. INSERT 2. DELETE 3. FIND 4. PRINT 5. QUIT

Enter the choice :: 1


Enter the element to be inserted :: 12
Enter the position of the element :: 1

1. INSERT 2. DELETE 3. FIND 4. PRINT 5. QUIT

Enter the choice :: 4


The list element are :: 12 ->
1. INSERT 2. DELETE 3. FIND 4. PRINT 5. QUIT
Enter the choice :: 1
Enter the element to be inserted :: 32
Enter the position of the element :: 2

1. INSERT 2. DELETE 3. FIND 4. PRINT 5. QUIT


Enter the choice :: 4
The list element are :: 12 -> 32 -
9.a) Implementation of Stacks Using Linked List
#include <stdio.h>
#include <stdlib.h>
void push();
void pop();
void display();
struct node
{
int val;
struct node *next;
};
struct node *head;

void main ()
{
int choice=0;
printf("\n*********Stack operations using linked list*********\n"); printf("\n \n");
while(choice != 4)
{
printf("\n\nChose one from the below options...\n"); printf("\n1.Push\n2.Pop\n3.Show\n4.Exit");
printf("\n Enter your choice \n"); scanf("%d",&choice);
switch(choice)
{
case 1:
{
push(); break;
}
case 2:
{
pop(); break;
}
case 3:
{
display(); break;
}
case 4:
{
printf("Exiting... ");
break;
}
default:
{
printf("Please Enter valid choice ");
}
};
}
}
void push ()
{
int val;
struct node *ptr = (struct node*)malloc(sizeof(struct node));
if(ptr == NULL)
{
printf("not able to push the element");
}
else
{
printf("Enter the value");
scanf("%d",&val);
if(head==NULL)
{
ptr->val = val;
ptr -> next = NULL;
head=ptr;
}
else
{
ptr->val = val;
ptr->next = head;
head=ptr;
}
printf("Item pushed");
}
}
void pop()
{
int item;
struct node *ptr;
if (head == NULL)
{
printf("Underflow");
}
else
{
item = head->val;
ptr = head;
head = head->next;
free(ptr);
printf("Item popped");

}
}
void display()
{
int i;
struct node *ptr;
ptr=head;
if(ptr == NULL)
{
printf("Stack is empty\n");
}
else
{
printf("Printing Stack elements \n");
while(ptr!=NULL)
{
printf("%d\n",ptr->val);
ptr = ptr->next;
}
}
}
Output:

*********Stack operations using linked list*********

Chose one from the below options...


1.Push
2.Pop
3.Show
4.Exit
Enter your choice
1
Enter the value10
Item pushed
Chose one from the below options...
1.Push
2.Pop
3.Show
4.Exit
Enter your choice
1
Enter the value20
Item pushed
Chose one from the below options...
1.Push
2.Pop
3.Show
4.Exit
Enter your choice
1
Enter the value3
b) Implementation of Queue Using Linked List
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
};
struct node *front;
struct node *rear;
void insert();
void delete();
void display();
void main ()
{
int choice;
while(choice != 4)
{
printf("\n*************************Main Menu*****************************\n");
printf("\n=================================================================\n");
printf("\n1.insert an element\n2.Delete an element\n3.Display the queue\n4.Exit\n");
printf("\nEnter your choice ?");
scanf("%d",& choice);
switch(choice)
{
case 1:
insert();
break;
case 2:
delete();
break;
case 3:
display();
break;
case 4:
exit(0);
break;
default:
printf("\nEnter valid choice??\n");
}
}
} void insert()
{
struct node *ptr;
int item;

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


if(ptr == NULL)
{
printf("\nOVERFLOW\n");
return;
}
else
{
printf("\nEnter value?\n");
scanf("%d",&item);
ptr -> data = item;
if(front == NULL)
{
front = ptr;
rear = ptr;
front -> next = NULL;
rear -> next = NULL;
}
else
{
rear -> next = ptr;
rear = ptr;
rear->next = NULL;
}
}
}
void delete ()
{
struct node *ptr;
if(front == NULL)
{
printf("\nUNDERFLOW\n");
return;
}
else
{
ptr = front;
front = front -> next;
free(ptr);
}
}
void display()
{
struct node *ptr;
ptr = front;
if(front == NULL)
{
printf("\nEmpty queue\n");
}
else
{ printf("\nprinting values ...... \n");
while(ptr != NULL)
{
printf("\n%d\n",ptr -> data);
ptr = ptr -> next;
}
}
}
Output:

*************************Main Menu*****************************

=================================================================

1. insert an element
2. Delete an element
3. Display the queue
4.Exit
Enter your choice ?1
Enter value?
100
*************************Main Menu*****************************
=================================================================
1. insert an element
2. Delete an element
3. Display the queue
4.Exit
Enter your choice ?1
Enter value?
200
*************************Main Menu*****************************
=================================================================
1. insert an element
2. Delete an element
3. Display the queue
4.Exit
Enter your choice ?1
Enter value?
300
10. Implementation of Binary Search Tree.(Insertion, Deletion and Search Operations).
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
//Represent a node of binary tree
struct node{
int data;
struct node *left;
struct node *right;
};

//Represent the root of binary tree


struct node *root= NULL;

//createNode() will create a new node


struct node* createNode(int data){
//Create a new node
struct node *newNode = (struct node*)malloc(sizeof(struct node));
//Assign data to newNode, set left and right children to NULL
newNode->data= data;
newNode->left = NULL;
newNode->right = NULL;

return newNode;
}

//insert() will add new node to the binary search tree


void insert(int data) {
//Create a new node
struct node *newNode = createNode(data);

//Check whether tree is empty


if(root == NULL){
root = newNode;
return;
}
else {
//current node point to root of the tree
struct node *current = root, *parent = NULL;

while(true) {

//parent keep track of the parent node of current node.


parent = current;
//If data is less than current's data, node will be inserted to the left of tree
if(data < current->data) {
current = current->left;
if(current == NULL) {
parent->left = newNode;
return;
}
}
//If data is greater than current's data, node will be inserted to the right of tree
else {
current = current->right;
if(current == NULL) {
parent->right = newNode;
return;
}
}
}
}
}
//minNode() will find out the minimum node
struct node* minNode(struct node *root) {
if (root->left != NULL)
return minNode(root->left);
else
return root;
}

//deleteNode() will delete the given node from the binary search tree
struct node* deleteNode(struct node *node, int value) {
if(node == NULL){
return NULL;
}
else {
//value is less than node's data then, search the value in left subtree
if(value < node->data)
node->left = deleteNode(node->left, value);

//value is greater than node's data then, search the value in right subtree
else if(value > node->data)

node->right = deleteNode(node->right, value);

//If value is equal to node's data that is, we have found the node to be deleted
else {
//If node to be deleted has no child then, set the node to NULL
if(node->left == NULL && node->right == NULL)
node = NULL;
//If node to be deleted has only one right child
else if(node->left == NULL) {
node = node->right;
}

//If node to be deleted has only one left child


else if(node->right == NULL) {
node = node->left;
}

//If node to be deleted has two children node


else {
//then find the minimum node from right subtree
struct node *temp = minNode(node->right);
//Exchange the data between node and temp
node->data = temp->data;
//Delete the node duplicate node from right subtree
node->right = deleteNode(node->right, temp->data);
}
}
return node;
}
}

//inorder() will perform inorder traversal on binary search tree


void inorderTraversal(struct node *node) {

//Check whether tree is empty


if(root == NULL){
printf("Tree is empty\n");
return;
}

else {

if(node->left!= NULL)

inorderTraversal(node->left);
printf("%d ", node->data);
if(node->right!= NULL)
inorderTraversal(node->right);

}
}
int main()
{
//Add nodes to the binary tree
insert(50);
insert(30);
insert(70);
insert(60);
insert(10);
insert(90);

printf("Binary search tree after insertion: \n");


//Displays the binary tree
inorderTraversal(root);

struct node *deletedNode = NULL;


//Deletes node 90 which has no child
deletedNode = deleteNode(root, 90);
printf("\nBinary search tree after deleting node 90: \n");
inorderTraversal(root);

//Deletes node 30 which has one child


deletedNode = deleteNode(root, 30);
printf("\nBinary search tree after deleting node 30: \n");
inorderTraversal(root);

//Deletes node 50 which has two children


deletedNode = deleteNode(root, 50);
printf("\nBinary search tree after deleting node 50: \n");
inorderTraversal(root);

return 0;
}

Output:
Binary search tree after insertion:
10 30 50 60 70 90
Binary search tree after deleting node 90:
10 30 50 60 70
Binary search tree after deleting node 30:
10 50 60 70
Binary search tree after deleting node 50:
10 60 70
11. Implementation of Tree Traversal on Binary Trees.

// Tree traversal in C
#include <stdio.h>
#include <stdlib.h>
struct node {
int item;
struct node* left;
struct node* right;
};
// Inorder traversal
void inorderTraversal(struct node* root) {
if (root == NULL) return;
inorderTraversal(root->left);
printf("%d ->", root->item);
inorderTraversal(root->right);
}
// preorderTraversal traversal
void preorderTraversal(struct node* root) {
if (root == NULL) return;
printf("%d ->", root->item);
preorderTraversal(root->left);
preorderTraversal(root->right);
}
// postorderTraversal traversal
void postorderTraversal(struct node* root) {
if (root == NULL) return;
postorderTraversal(root->left);
postorderTraversal(root->right);
printf("%d ->", root->item);
}
// Create a new Node
struct node* createNode(value) {
struct node* newNode = malloc(sizeof(struct node));
newNode->item = value;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}
// Insert on the left of the node
struct node* insertLeft(struct node* root, int value) {
root->left = createNode(value);
return root->left;
}
// Insert on the right of the node
struct node* insertRight(struct node* root, int value) {
root->right = createNode(value);
return root->right;
}
int main() {
struct node* root = createNode(1);
insertLeft(root, 12);
insertRight(root, 9);
insertLeft(root->left, 5);
insertRight(root->left, 6);
printf("Inorder traversal \n");
inorderTraversal(root);
printf("\nPreorder traversal \n");
preorderTraversal(root);
printf("\nPostorder traversal \n");
postorderTraversal(root);
}

Output:
Inorder traversal
5 ->12 ->6 ->1 ->9 ->
Preorder traversal
1 ->12 ->5 ->6 ->9 ->
Postorder traversal
5 ->6 ->12 ->9 ->1 ->
12. Implementation of AVL Trees.

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

// Create Node
struct Node {
int key;
struct Node *left;
struct Node *right;
int height;
};

int max(int a, int b);

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

int max(int a, int b) {


return (a > b) ? a : b;
}

// Create a node
struct Node *newNode(int key) {
struct Node *node = (struct Node *)
malloc(sizeof(struct Node));
node->key = key;
node->left = NULL;
node->right = NULL;
node->height = 1;
return (node);
}

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

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


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

return x;
}

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

y->left = x;
x->right = T2;

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


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

return y;
}

// Get the balance factor


int getBalance(struct Node *N) {
if (N == NULL)
return 0;
return height(N->left) - height(N->right);
}
// Insert node
struct Node *insertNode(struct Node *node, int key) {
// Find the correct position to insertNode the node and insertNode it
if (node == NULL)
return (newNode(key));

if (key < node->key)


node->left = insertNode(node->left, key);
else if (key > node->key)
node->right = insertNode(node->right, key);
else
return node;

// Update the balance factor of each node and


// Balance the tree
node->height = 1 + max(height(node->left),
height(node->right));

int balance = getBalance(node);


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

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


return leftRotate(node);

if (balance > 1 && key > node->left->key) {


node->left = leftRotate(node->left);
return rightRotate(node);
}

if (balance < -1 && key < node->right->key) {


node->right = rightRotate(node->right);
return leftRotate(node);
}

return node;
}
struct Node *minValueNode(struct Node *node) {
struct Node *current = node;
while (current->left != NULL)
current = current->left;
return current;
}

// Delete a nodes
struct Node *deleteNode(struct Node *root, int key) {
// Find the node and delete it
if (root == NULL)
return root;
if (key < root->key)
root->left = deleteNode(root->left, key);
else if (key > root->key)
root->right = deleteNode(root->right, key);
else {
if ((root->left == NULL) || (root->right == NULL)) {
struct Node *temp = root->left ? root->left : root->right;
if (temp == NULL) {
temp = root;
root = NULL;
} else
*root = *temp;
free(temp);
} else {
struct Node *temp = minValueNode(root->right);
root->key = temp->key;
root->right = deleteNode(root->right, temp->key);
}
}
if (root == NULL)
return root;

// Update the balance factor of each node and


// balance the tree
root->height = 1 + max(height(root->left),
height(root->right));

int balance = getBalance(root);


if (balance > 1 && getBalance(root->left) >= 0)
return rightRotate(root);

if (balance > 1 && getBalance(root->left) < 0) {


root->left = leftRotate(root->left);
return rightRotate(root);
}
if (balance < -1 && getBalance(root->right) <= 0)
return leftRotate(root);

if (balance < -1 && getBalance(root->right) > 0) {


root->right = rightRotate(root->right);
return leftRotate(root);
}
return root;
}
// Print the tree
void printPreOrder(struct Node *root) {
if (root != NULL) {
printf("%d ", root->key);
printPreOrder(root->left);
printPreOrder(root->right);
}
}
int main() {
struct Node *root = NULL;
root = insertNode(root, 2);
root = insertNode(root, 1);
root = insertNode(root, 7);
root = insertNode(root, 4);
root = insertNode(root, 5);
root = insertNode(root, 3);
root = insertNode(root, 8);
printPreOrder(root);
root = deleteNode(root, 3);
printf("\nAfter deletion: ");
printPreOrder(root);
return 0;
}

Output:

4213758
After deletion: 4 2 1 7 5 8
13. a) Implementation of operations Traversal on Graphs. DFS Using C
#include <stdio.h>
#include <stdlib.h>
struct node {
int vertex;
struct node* next;
};
struct node* createNode(int v);
struct Graph {
int numVertices;
int* visited;

// We need int** to store a two dimensional array.


// Similary, we need struct node** to store an array of Linked lists
struct node** adjLists;
};

// DFS algo
void DFS(struct Graph* graph, int vertex) {
struct node* adjList = graph->adjLists[vertex];
struct node* temp = adjList;

graph->visited[vertex] = 1;
printf("Visited %d \n", vertex);

while (temp != NULL) {


int connectedVertex = temp->vertex;

if (graph->visited[connectedVertex] == 0) {
DFS(graph, connectedVertex);
}
temp = temp->next;
}
}

// Create a node
struct node* createNode(int v) {
struct node* newNode = malloc(sizeof(struct node));
newNode->vertex = v;
newNode->next = NULL;
return newNode;
}

// Create graph
struct Graph* createGraph(int vertices) {
struct Graph* graph = malloc(sizeof(struct Graph));
graph->numVertices = vertices;
graph->adjLists = malloc(vertices * sizeof(struct node*));
graph->visited = malloc(vertices * sizeof(int));
int i;
for (i = 0; i < vertices; i++) {
graph->adjLists[i] = NULL;
graph->visited[i] = 0;
}
return graph;
}
// Add edge
void addEdge(struct Graph* graph, int src, int dest) {
// Add edge from src to dest
struct node* newNode = createNode(dest);
newNode->next = graph->adjLists[src];
graph->adjLists[src] = newNode;

// Add edge from dest to src


newNode = createNode(src);
newNode->next = graph->adjLists[dest];
graph->adjLists[dest] = newNode;
}

// Print the graph


void printGraph(struct Graph* graph) {
int v;
for (v = 0; v < graph->numVertices; v++) {
struct node* temp = graph->adjLists[v];
printf("\n Adjacency list of vertex %d\n ", v);
while (temp) {
printf("%d ->", temp->vertex);
temp = temp->next;
}
printf("\n");
}
}
int main() {
struct Graph* graph = createGraph(4);
addEdge(graph, 0, 1);
addEdge(graph, 0, 2);
addEdge(graph, 1, 2);
addEdge(graph, 2, 3);
printGraph(graph);
DFS(graph, 2);
return 0;
}
Output:

Adjacency list of vertex 0


2 -> 1 ->

Adjacency list of vertex 1


2 -> 0 ->

Adjacency list of vertex 2


3 -> 1 -> 0 ->

Adjacency list of vertex 3


2 ->
Visited 2
Visited 3
Visited 1
Visited 0
b) Implementation of BFS:
// BFS algorithm in C

#include <stdio.h>
#include <stdlib.h>
#define SIZE 40

struct queue {
int items[SIZE];
int front;
int rear;
};

struct queue* createQueue();


void enqueue(struct queue* q, int);
int dequeue(struct queue* q);
void display(struct queue* q);
int isEmpty(struct queue* q);
void printQueue(struct queue* q);

struct node {
int vertex;
struct node* next;
};
struct node* createNode(int);
struct Graph {
int numVertices;
struct node** adjLists;
int* visited;
};

// BFS algorithm
void bfs(struct Graph* graph, int startVertex) {
struct queue* q = createQueue();

graph->visited[startVertex] = 1;
enqueue(q, startVertex);

while (!isEmpty(q)) {
printQueue(q);
int currentVertex = dequeue(q);
printf("Visited %d\n", currentVertex);
struct node* temp = graph->adjLists[currentVertex];
while (temp) {
int adjVertex = temp->vertex;
if (graph->visited[adjVertex] == 0) {
graph->visited[adjVertex] = 1;
enqueue(q, adjVertex);
}
temp = temp->next;
}
}
}
// Creating a node
struct node* createNode(int v) {
struct node* newNode = malloc(sizeof(struct node));
newNode->vertex = v;
newNode->next = NULL;
return newNode;
}
// Creating a graph
struct Graph* createGraph(int vertices) {
struct Graph* graph = malloc(sizeof(struct Graph));
graph->numVertices = vertices;
graph->adjLists = malloc(vertices * sizeof(struct node*));
graph->visited = malloc(vertices * sizeof(int));
int i;
for (i = 0; i < vertices; i++) {
graph->adjLists[i] = NULL;
graph->visited[i] = 0;
}
return graph;
}
// Add edge
void addEdge(struct Graph* graph, int src, int dest) {
// Add edge from src to dest
struct node* newNode = createNode(dest);
newNode->next = graph->adjLists[src];
graph->adjLists[src] = newNode;

// Add edge from dest to src


newNode = createNode(src);
newNode->next = graph->adjLists[dest];
graph->adjLists[dest] = newNode;
}
// Create a queue
struct queue* createQueue() {
struct queue* q = malloc(sizeof(struct queue));
q->front = -1;
q->rear = -1;
return q;
}

// Check if the queue is empty


int isEmpty(struct queue* q) {
if (q->rear == -1)
return 1;
else
return 0;
}

// Adding elements into queue


void enqueue(struct queue* q, int value) {
if (q->rear == SIZE - 1)
printf("\nQueue is Full!!");
else {
if (q->front == -1)
q->front = 0;
q- >rear++;
q->items[q->rear] = value;
}
}
// Removing elements from queue
int dequeue(struct queue* q) {
int item;
if (isEmpty(q)) {
printf("Queue is empty");
item = -1;
} else {
item = q->items[q->front];
q->front++;
if (q->front > q->rear) {
printf("Resetting queue ");
q->front = q->rear = -1;
}
}
return item;
}

// Print the queue


void printQueue(struct queue* q) {
int i = q->front;

if (isEmpty(q)) {
printf("Queue is empty");
} else {
printf("\nQueue contains \n");
for (i = q->front; i < q->rear + 1; i++) {
printf("%d ", q->items[i]);
}
}
}
int main() {
struct Graph* graph = createGraph(6);
addEdge(graph, 0, 1);
addEdge(graph, 0, 2);
addEdge(graph, 1, 2);
addEdge(graph, 1, 4);
addEdge(graph, 1, 3);
addEdge(graph, 2, 4);
addEdge(graph, 3, 4);
bfs(graph, 0);
return 0;
}

Output:

Queue contains
0 Resetting queue Visited 0

Queue contains
2 1 Visited 2

Queue contains
1 4 Visited 1

Queue contains
4 3 Visited 4

Queue contains
3 Resetting queue Visited 3
14. Implementation of Prims and Kruskals Algorithm
• Prims algorithm

#include<stdio.h>
#include<conio.h>
int a,b,u,v,n,i,j,ne=1;
int visited[10]={0},min,mincost=0,cost[10][10];
void main()
{
// clrscr();
printf("\nEnter the number of nodes:");
scanf("%d",&n);
printf("\nEnter the adjacency matrix:\n");
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
{
scanf("%d",&cost[i][j]);
if(cost[i][j]==0)
cost[i][j]=999;
}
visited[1]=1;
printf("\n");
while(ne < n)
{
for(i=1,min=999;i<=n;i++)
for(j=1;j<=n;j++)
if(cost[i][j]< min)
if(visited[i]!=0)
{
min=cost[i][j];
a=u=i;
b=v=j;
}
if(visited[u]==0 || visited[v]==0)
{
printf("\n Edge %d:(%d %d) cost:%d",ne++,a,b,min);
mincost+=min;
visited[b]=1;
}
cost[a][b]=cost[b][a]=999;
}
printf("\n Minimun cost=%d",mincost);
// getch();
}
Output:
Enter the number of nodes:6
Enter the adjacency matrix:
031600
305030
150564
605002
036006
004260
Edge 1:(1 3) cost:1
Edge 2:(1 2) cost:3
Edge 3:(2 5) cost:3
Edge 4:(3 6) cost:4
Edge 5:(6 4) cost:2
Minimun cost=13
• Implementation of Kruskals algorithm
#include<stdio.h>
//#include<conio.h>
#include<stdlib.h>
int i,j,k,a,b,u,v,n,ne=1;
int min,mincost=0,cost[9][9],parent[9];
int find(int);
int uni(int,int);
void main()
{
//clrscr();
printf("\n\tImplementation of Kruskal's algorithm\n");
printf("\nEnter the no. of vertices:");
scanf("%d",&n);
printf("\nEnter the cost adjacency matrix:\n");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
scanf("%d",&cost[i][j]);
if(cost[i][j]==0)
cost[i][j]=999;
}
}
printf("The edges of Minimum Cost Spanning Tree are\n");
while(ne < n)
{
for(i=1,min=999;i<=n;i++)
{
for(j=1;j <= n;j++)
{
if(cost[i][j] < min)
{
min=cost[i][j];
a=u=i;
b=v=j;
}
}
}
u=find(u);
v=find(v);
if(uni(u,v))
{
printf("%d edge (%d,%d) =%d\n",ne++,a,b,min);
mincost +=min;
}
cost[a][b]=cost[b][a]=999;
}
printf("\n\tMinimum cost = %d\n",mincost);
//getch();
}
int find(int i)
{
while(parent[i])
i=parent[i];
return i;
}
int uni(int i,int j)
{
if(i!=j)
{
parent[j]=i;
return 1;
}

return 0;
}
Output:
Implementation of Kruskal's algorithm
Enter the no. of vertices:6
Enter the cost adjacency matrix:
031600
305030
150564
605002
036006
004260
The edges of Minimum Cost Spanning Tree are
1 edge (1,3) =1
2 edge (4,6) =2
3 edge (1,2) =3
4 edge (2,5) =3
5 edge (3,6) =4
Minimum cost = 13

You might also like