Final DS Lab Manual1
Final DS Lab Manual1
(Autonomous)
Department of CSE-AIML
DATA STRUCTURES Lab Manual
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
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:
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.
char s[SIZE];
int top = -1; /* Global declarations */
/*
* 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('#');
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:
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:
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:
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:
*************************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;
};
return newNode;
}
while(true) {
//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)
//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;
}
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);
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;
};
// Calculate height
int height(struct Node *N) {
if (N == NULL)
return 0;
return N->height;
}
// 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;
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;
return y;
}
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;
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;
// 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);
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;
#include <stdio.h>
#include <stdlib.h>
#define SIZE 40
struct queue {
int items[SIZE];
int front;
int rear;
};
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;
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