Ds Lab Final-with Program
Ds Lab Final-with Program
Data Structures are the main part of many computer science algorithms
as they enable the programmers to handle the data in an efficient way. It
plays a vital role in enhancing the performance of a software or a program
as the main function of the software is to store and retrieve the user's
data as fast as possible
Basic Terminology
Data structures are the building blocks of any program or the software.
Choosing the appropriate data structure for a program is the most difficult
task for a programmer. Following terminology is used as far as data
structures are concerned
Group Items: Data items which have subordinate data items are called
Group item, for example, name of a student can have first name and the
last name.
Record: Record can be defined as the collection of various data items, for
example, if we talk about the student entity, then its name, address,
course and marks can be grouped together to form the record for the
student.
Data is organized to form a data structure in such a way that all items are
not required to be searched and required data can be searched instantly.
For example:
suppose, we have some data and we need to perform the search for a
particular record. In that case, if we organize our data in an array, we will
have to search sequentially element by element. hence, using array may
not be very efficient here.
There are better data structures which can make the search process
efficient like ordered array, binary search tree or hash tables.
Figure: CLL
1
Inserting into a SLL:
Figure 13: Binary Search Tree on Numbers Figure 14: Binary Search Tree on Strings
Graphs:
Let V be a finite set, and denote by E(V) = {{u, v} | u, v ∈ V, u ≠v}
3
v2v4, v5v6}.
Definition of Algorithm
The word Algorithm means” A set of finite rules or
instructions to be followed in calculations or other
problem-solving operations”
Or
4
How to Design an Algorithm?
To write an algorithm, the following things are needed as a pre-
requisite:
1. The problem that is to be solved by this algorithm i.e. clear
problem definition.
2. The constraints of the problem must be considered while
solving the problem.
3. The input to be taken to solve the problem.
4. The output is to be expected when the problem is solved.
5. The solution to this problem is within the given
constraints.
TOTAL: 60 PERIODS
COURSE OUTCOMES:
6
Upon successful completion of the course, student will be able to;
CO1 Understand the concept of Stacks and Queues and its application
CO2 Explain the concept of Queues and its application.
CO3 Study about different types of Tree along with their operations and
applications.
CO4 Solve problem involving Graphs and its applicability.
CO5 Design efficient algorithms for Sorting.
CO6 Implement efficient algorithms for Searching
7 a) Pre-order
b) In-order
c) Post-order
Program to implement the following Graph Traversal Methods
8 a)Breadth First Search
b) Depth First Search
Program to implement Minimum Spanning Tree
using the following
9 algorithms
a) Prim’s Algorithm
b) Kruskal’s Algorithm
Program to implement Single Source Shortest Path
10
algorithm using Dijkstra’s algorithm.
Program to search an element in the given list of elements using
searching algorithm
11 a Linear Search
b Binary Search
8
Ex. no.: 1 STACK OPERATION
AIM:
To Write a C program to implement the Stack operations
ALGORITHM:
1.Start
2. Define a array stack of size max = 4
3. Initialize top = -1
4. Display a menu listing stack operations
5. Accept choice
6. If choice = 1 then
7. If top < SIZE -1
8. Increment top
9. Store element at current position of top
10. Else
11. Print Stack overflow
12. If choice = 2 then
13. If top < 0 then
14. Print Stack underflow
15. Else
16. Display current top element
17. Decrement top
18. If choice = 3 then
19. Display stack elements starting from top
20. Stop
PROGRAM:
#include <stdio.h>
#include <stdlib.h>
#define SIZE 4
int top = -1, inp_array[SIZE];
void push();
void pop();
void show();
int main()
{
int choice;
while (1)
{
printf("\nPerform operations on the stack:");
printf("\n1.Push the element\n2.Pop the element\n3.Show\n4.End");
printf("\n\nEnter the choice: ");
scanf("%d", &choice);
switch (choice)
{
case 1:
9
push();
break;
case 2:
pop();
break;
case 3:
show();
break;
case 4:
exit(0);
default:
printf("\nInvalid choice!!");
}
}
}
void push()
{
int x;
if (top == SIZE - 1)
{
printf("\nOverflow!!");
}
else
{
printf("\nEnter the element to be added onto the stack: ");
scanf("%d", &x);
top = top + 1;
inp_array[top] = x;
}
}
void pop()
{
if (top == -1)
{
printf("\nUnderflow!!");
}
else
{
printf("\nPopped element: %d", inp_array[top]);
top = top - 1;
}
}
void show()
{
if (top == -1)
10
{
printf("\nUnderflow!!");
}
else
{
printf("\nElements present in the stack: \n");
for (int i = top; i >= 0; --i)
printf("%d\n", inp_array[i]);
}
}
Output:
Perform operations on the stack:
1.Push the element
2.Pop the element
3.Show
4.End
RESULT :-
Thus the program has been successfully executed and
verified .
12
Ex. no.: 2 QUEUE OPERATION
AIM:
To Write a C program to implement the Queue operations.
ALGORITHM:
1. Start
2. Define a array queue of size max = 5
3. Initialize front = rear = –1
4. Display a menu listing queue operations
5. Accept choice
6. If choice = 1 then
7. If rear < size -1
8. Increment rear
9. Store element at current position of rear
10. Else
11. Print Queue Full
12. If choice = 2 then
13. If front = –1 then
14. Print Queue empty
15. Else
16. Display current front element
17. Increment front
18. If choice = 3 then
19. Display queue elements
PROGRAM :
#include <stdio.h>
# define SIZE 100
void enqueue();
void dequeue();
void show();
int inp_arr[SIZE];
int Rear = - 1;
int Front = - 1;
main()
{
int ch;
while (1)
{
printf("1.Enqueue Operation\n");
printf("2.Dequeue Operation\n");
printf("3.Display the Queue\n");
printf("4.Exit\n");
printf("Enter your choice of operations : ");
scanf("%d", &ch);
switch (ch)
{
case 1:
enqueue();
13
break;
case 2:
dequeue();
break;
case 3:
show();
break;
case 4:
exit(0);
default:
printf("Incorrect choice \n");
}
}
}
void enqueue()
{
int insert_item;
if (Rear == SIZE - 1)
printf("Overflow \n");
else
{
if (Front == - 1)
Front = 0;
printf("Element to be inserted in the Queue\n : ");
scanf("%d", &insert_item);
Rear = Rear + 1;
inp_arr[Rear] = insert_item;
}
}
void dequeue()
{
if (Front == - 1 || Front > Rear)
{
printf("Underflow \n");
return ;
}
else
{
printf("Element deleted from the Queue: %d\n", inp_arr[Front]);
Front = Front + 1;
}
}
void show()
{
if (Front == - 1)
14
printf("Empty Queue \n");
else
{
printf("Queue: \n");
for (int i = Front; i <= Rear; i++)
printf("%d ", inp_arr[i]);
printf("\n");
}
}
Output:
1.Enqueue Operation
2.Dequeue Operation
3.Display the Queue
4.Exit
Enter your choice of operations : 1
Element to be inserted in the Queue: 10
1.Enqueue Operation
2.Dequeue Operation
3.Display the Queue
4.Exit
Enter your choice of operations : 1
Element to be inserted in the Queue: 20
1.Enqueue Operation
2.Dequeue Operation
3.Display the Queue
4.Exit
Enter your choice of operations : 3
Queue:
10 20
1.Enqueue Operation
2.Dequeue Operation
3.Display the Queue
4.Exit
Enter your choice of operations : 2
Element deleted from the Queue: 10
1.Enqueue Operation
2.Dequeue Operation
3.Display the Queue
4.Exit
Enter your choice of operations: 3
Queue:
20
RESULT : -
15
Thus the program has been successfully executed and
verified.
16
Ex. no.: 3 SINGLY LINKED LIST
AIM:
To Write a C program to Perform operations on Singly Linked
List
ALGORITHM:
1. Start
2. Define single linked list node as self referential structure
3. Display menu on list operation
5. Accept user choice
6. If choice = 1 then
7. Locate node after which insertion is to be done
8. Create a new node and get data part
9. Insert the new node at appropriate position by manipulating address
10. Else if choice = 3
11. Get node's data to be insert in last position.
12. Locate the node and delink the node
13. Rearrange the links
14. Else
15.Traverse the list from Head node to node which points to null
16. Stop
PROGRAM:
Singly linked lsit
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
int count=0;
struct node
{
int data;
struct node *next;
}*head,*newn,*trav;
//----------------------------------------------------------
void create_list()
{
int value;
struct node *temp;
temp=head;
newn=(struct node *)malloc(sizeof (struct node));
printf("\nenter the value to be inserted");
scanf("%d",&value);
newn->data=value;
if(head==NULL)
{
head=newn;
head->next=NULL;
count++;
}
else
17
{
while(temp->next!=NULL)
{
temp=temp->next;
}
temp->next=newn;
newn->next=NULL;
count++;
}
}
//----------------------------------------------------
void insert_at_begning(int value)
{
newn=(struct node *)malloc(sizeof (struct node));
newn->data=value;
if(head==NULL)
{
head=newn;
head->next=NULL;
count++;
}
else
{
newn->next=head;
head=newn;
count++;
}
}
//----------------------------------------------------------
void insert_at_end(int value)
{
struct node *temp;
temp=head;
newn=(struct node *)malloc(sizeof (struct node));
newn->data=value;
if(head==NULL)
{
head=newn;
head->next=NULL;
count++;
}
else
{
while(temp->next!=NULL)
{
temp=temp->next;
}
temp->next=newn;
newn->next=NULL;
count++;
18
}
}
//------------------------------------------------------
int insert_at_middle()
{
if(count>=2)
{
struct node *var1,*temp;
int loc,value;
printf("\n after which value you want to insert : ");
scanf("%d",&loc);
printf("\nenter the value to be inserted");
scanf("%d",&value);
newn=(struct node *)malloc(sizeof (struct node));
newn->data=value;
temp=head;
/* if(head==NULL)
{
head=newn;
head->next=NULL;
count++;
return 0;
}
else
{*/
while(temp->data!=loc)
{
temp=temp->next;
if(temp==NULL)
{
printf("\nSORRY...there is no %d element",loc);
return 0;
}
}
//var1=temp->next;
newn->next=temp->next;//var1;
temp->next=newn;
count++;
//}
}
else
{
printf("\nthe no of nodes must be >=2");
}
}
//----------------------------------------------------------------
int delete_from_middle()
{
if(count==0)
printf("\n List is Empty!!!! you can't delete elements\n");
19
else if(count>2)
{
struct node *temp,*var;
int value;
temp=head;
printf("\nenter the data that you want to delete from the list shown
above");
scanf("%d",&value);
while(temp->data!=value)
{
var=temp;
temp=temp->next;
if(temp==NULL)
{
printf("\nSORRY...there is no %d element",value);
return 0;
}
}
if(temp==head)
{
head=temp->next;
}
else{
var->next=temp->next;
temp->next=NULL;
}
count--;
if(temp==NULL)
printf("Element is not avilable in the list \n**enter only middle
elements..**");
else
printf("\ndata deleted from list is %d",value);
free(temp);
}
else
{
printf("\nthere no middle elemts..only %d elemts is avilable\n",count);
}
}
//------------------------------------------------------------------
int delete_from_front()
{
struct node *temp;
temp=head;
if(head==NULL)
{
printf("\nno elements for deletion in the list\n");
return 0;
}
else
20
{
printf("\ndeleted element is :%d",head->data);
if(temp->next==NULL)
{
head=NULL;
}
else{
head=temp->next;
temp->next=NULL;
}
count--;
free(temp);
}
}
//--------------------------------------------------------
int delete_from_end()
{
struct node *temp,*var;
temp=head;
if(head==NULL)
{
printf("\nno elemts in the list");
return 0;
}
else{
if(temp->next==NULL )
{
head=NULL;//temp->next;
}
else{
while(temp->next != NULL)
{
var=temp;
temp=temp->next;
}
var->next=NULL;
}
printf("\ndata deleted from list is %d",temp->data);
free(temp);
count--;
}
return 0;
}
//------------------------------------------------------
int display()
{
trav=head;
if(trav==NULL)
{
printf("\nList is Empty\n");
21
return 0;
}
else
{
printf("\n\nElements in the Single Linked List is %d:\n",count);
while(trav!=NULL)
{
printf(" -> %d ",trav->data);
trav=trav->next;
}
printf("\n");
}
}
//---------------------------------------------------------------
int main()
{
int ch=0;
char ch1;
head=NULL;
while(1)
{
printf("\n1.create linked list");
printf("\n2.insertion at begning of linked list");
printf("\n3.insertion at the end of linked list");
printf("\n4.insertion at the middle where you want");
printf("\n5.deletion from the front of linked list");
printf("\n6.deletion from the end of linked list ");
printf("\n7.deletion of the middle data that you want");
printf("\n8.display the linked list");
printf("\n9.exit\n");
printf("\nenter the choice of operation to perform on linked list");
scanf("%d",&ch);
switch(ch)
{
case 1:
{
do{
create_list();
display();
printf("do you want to create list ,y / n");
getchar();
scanf("%c",&ch1);
}while(ch1=='y');
break;
}
case 2:
{
int value;
printf("\nenter the value to be inserted");
scanf("%d",&value);
22
insert_at_begning(value);
display();
break;
}
case 3:
{
int value;
printf("\nenter value to be inserted");
scanf("%d",&value);
insert_at_end(value);
display();
break;
}
case 4:
{
insert_at_middle();
display();
break;
}
case 5:
{
delete_from_front();
display();
}break;
case 6:
{
delete_from_end();
display();
break;
}
case 7:
{
display();
delete_from_middle();
display();
break;
}
case 8:
{
display();
break;
}
case 9:
{
exit(1);
}
default:printf("\n****Please enter correct choice****\n");
}
}
getch();
23
}
Output:
1.create linked list
2.insertion at beginning of linked list
3.insertion at the end of linked list
4.insertion at the middle where you want
5.deletion from the front of linked list
6.deletion from the end of linked list
7.deletion of the middle data that you want
8.display the linked list
9.exit
SORRY...there is no 89 element
enter the data that you want to delete from the list shown above90
27
Ex. no.: 4 DOUBLY LINKED LIST
AIM:
To Write a C program to perform the operations on Doubly Linked
List
ALGORITHM:
1. Creation: Start with an empty doubly linked list. Allocate memory for
the head node. Set the prev and next pointers of the head node to
NULL. Optionally, assign initial data to the head node.
2. Insertion at the beginning: Create a new node with the given data.
If the list is empty, set the head pointer to the new node. Otherwise,
set the next pointer of the new node to the current head. Set the prev
pointer of the current head to the new node. Update the head pointer
to point to the new node.
3. Insertion at the end: Create a new node with the given data. If the
list is empty, set the head pointer to the new node. Otherwise, traverse
the list to find the last node. Set the next pointer of the last node to the
new node. Set the prev pointer of the new node to point to the last
node.
4. Deletion: Search for the node to be deleted by traversing the list. If
the node is found, update the next pointer of the previous node to skip
the node to be deleted. If the node to be deleted is the head node,
update the head pointer. Free the memory allocated for the node to be
deleted.
PROGRAM:
#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");
28
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)
{
29
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)
30
{
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");
31
}
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)
32
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;
}
33
else
{
flag=1;
}
i++;
ptr = ptr -> next;
}
if(flag==1)
{
printf("\nItem not found\n");
}
}
}
Output:
*********Main Menu*********
============================================
===
1.Insert in begining
2.Insert at last
3.Insert at any random location
4.Delete from Beginning
5.Delete from last
6.Delete the node after the given data
7.Search
8.Show
9.Exit
printing values...
*********Main Menu*********
============================================
===
1.Insert in begining
2.Insert at last
3.Insert at any random location
4.Delete from Beginning
5.Delete from last
34
6.Delete the node after the given data
7.Search
8.Show
9.Exit
Node inserted
*********Main Menu*********
============================================
===
1.Insert in begining
2.Insert at last
3.Insert at any random location
4.Delete from Beginning
5.Delete from last
6.Delete the node after the given data
7.Search
8.Show
9.Exit
Node inserted
*********Main Menu*********
============================================
===
1.Insert in begining
2.Insert at last
3.Insert at any random location
4.Delete from Beginning
5.Delete from last
6.Delete the node after the given data
7.Search
35
8.Show
9.Exit
Node inserted
*********Main Menu*********
============================================
===
1.Insert in begining
2.Insert at last
3.Insert at any random location
4.Delete from Beginning
5.Delete from last
6.Delete the node after the given data
7.Search
8.Show
9.Exit
printing values...
1234
123
12
*********Main Menu*********
============================================
===
1.Insert in begining
2.Insert at last
3.Insert at any random location
4.Delete from Beginning
5.Delete from last
6.Delete the node after the given data
7.Search
8.Show
36
9.Exit
Enter value89
node inserted
*********Main Menu*********
============================================
===
1.Insert in begining
2.Insert at last
3.Insert at any random location
4.Delete from Beginning
5.Delete from last
6.Delete the node after the given data
7.Search
8.Show
9.Exit
node inserted
*********Main Menu*********
============================================
===
1.Insert in begining
2.Insert at last
3.Insert at any random location
4.Delete from Beginning
5.Delete from last
6.Delete the node after the given data
7.Search
8.Show
9.Exit
37
Enter your choice?
8
printing values...
1234
123
12345
12
89
*********Main Menu*********
============================================
===
1.Insert in begining
2.Insert at last
3.Insert at any random location
4.Delete from Beginning
5.Delete from last
6.Delete the node after the given data
7.Search
8.Show
9.Exit
node deleted
*********Main Menu*********
============================================
===
1.Insert in begining
2.Insert at last
3.Insert at any random location
4.Delete from Beginning
5.Delete from last
6.Delete the node after the given data
7.Search
8.Show
9.Exit
node deleted
*********Main Menu*********
============================================
===
1.Insert in begining
2.Insert at last
3.Insert at any random location
4.Delete from Beginning
5.Delete from last
6.Delete the node after the given data
7.Search
8.Show
9.Exit
printing values...
123
12345
*********Main Menu*********
============================================
===
1.Insert in begining
2.Insert at last
3.Insert at any random location
4.Delete from Beginning
5.Delete from last
6.Delete the node after the given data
7.Search
8.Show
9.Exit
39
*********Main Menu*********
============================================
===
1.Insert in begining
2.Insert at last
3.Insert at any random location
4.Delete from Beginning
5.Delete from last
6.Delete the node after the given data
7.Search
8.Show
9.Exit
printing values...
123
*********Main Menu*********
============================================
===
1.Insert in begining
2.Insert at last
3.Insert at any random location
4.Delete from Beginning
5.Delete from last
6.Delete the node after the given data
7.Search
8.Show
9.Exit
1.Insert in begining
2.Insert at last
3.Insert at any random location
4.Delete from Beginning
5.Delete from last
6.Delete the node after the given data
7.Search
8.Show
9.Exit
Can't delete
*********Main Menu*********
============================================
===
1.Insert in begining
2.Insert at last
3.Insert at any random location
4.Delete from Beginning
5.Delete from last
6.Delete the node after the given data
7.Search
8.Show
9.Exit
Exited..
RESULT : -
41
Ex. no.: 5 CIRCULAR LINKED LIST
AIM:
To Write a C program to perform the operations on Circular Linked
List.
ALGORITHM:
1. Creation: Allocate memory for the head node and assign it the given
data. Set the next pointer of the head node to point to itself.
2. Insertion at the beginning: Create a new node with the given data.
If the list is empty, set the head pointer to the new node and make it
circular. Otherwise, traverse the list to find the last node. Set the next
pointer of the last node to the new node. Set the next pointer of the
new node to point to the head node. Update the head pointer to point
to the new node.
3. Deletion: If the list is empty, print a message indicating that there's
nothing to delete. Traverse the list to find the node with the given data
or until we reach the end of the list. If the node is not found, print a
message indicating that the element is not found in the list. If the node
to be deleted is the head node and the list contains only one node, set
the head pointer to NULL. If the node to be deleted is the head node,
traverse the list to find the last node and update its next pointer. If the
node to be deleted is not the head node and not the last node, update
the next pointer of the previous node to skip the node to be deleted.
Free the memory allocated for the node to be deleted.
PROGRAM:
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
};
struct node *head;
}
void lastinsert()
{
struct node *ptr,*temp;
int item;
ptr = (struct node *)malloc(sizeof(struct node));
if(ptr == NULL)
{
printf("\nOVERFLOW\n");
}
else
{
printf("\nEnter Data?");
scanf("%d",&item);
ptr->data = item;
if(head == NULL)
{
head = ptr;
ptr -> next = head;
}
else
{
temp = head;
while(temp -> next != head)
{
temp = temp -> next;
}
temp -> next = ptr;
ptr -> next = head;
}
44
printf("\nnode inserted\n");
}
void begin_delete()
{
struct node *ptr;
if(head == NULL)
{
printf("\nUNDERFLOW");
}
else if(head->next == head)
{
head = NULL;
free(head);
printf("\nnode deleted\n");
}
else
{ ptr = head;
while(ptr -> next != head)
ptr = ptr -> next;
ptr->next = head->next;
free(head);
head = ptr->next;
printf("\nnode deleted\n");
}
}
void last_delete()
{
struct node *ptr, *preptr;
if(head==NULL)
{
printf("\nUNDERFLOW");
}
else if (head ->next == head)
{
head = NULL;
free(head);
printf("\nnode deleted\n");
}
else
{
ptr = head;
while(ptr ->next != head)
{
preptr=ptr;
45
ptr = ptr->next;
}
preptr->next = ptr -> next;
free(ptr);
printf("\nnode deleted\n");
}
}
void search()
{
struct node *ptr;
int item,i=0,flag=1;
ptr = head;
if(ptr == NULL)
{
printf("\nEmpty List\n");
}
else
{
printf("\nEnter item which you want to search?\n");
scanf("%d",&item);
if(head ->data == item)
{
printf("item found at location %d",i+1);
flag=0;
}
else
{
while (ptr->next != head)
{
if(ptr->data == item)
{
printf("item found at location %d ",i+1);
flag=0;
break;
}
else
{
flag=1;
}
i++;
ptr = ptr -> next;
}
}
if(flag != 0)
{
printf("Item not found\n");
}
}
46
}
void display()
{
struct node *ptr;
ptr=head;
if(head == NULL)
{
printf("\nnothing to print");
}
else
{
printf("\n printing values ... \n");
}
Output:
*********Main Menu*********
============================================
===
1.Insert in begining
2.Insert at last
3.Delete from Beginning
4.Delete from last
5.Search for an element
6.Show
7.Exit
node inserted
*********Main Menu*********
47
Choose one option from the following list ...
============================================
===
1.Insert in begining
2.Insert at last
3.Delete from Beginning
4.Delete from last
5.Search for an element
6.Show
7.Exit
Enter Data?20
node inserted
*********Main Menu*********
============================================
===
1.Insert in begining
2.Insert at last
3.Delete from Beginning
4.Delete from last
5.Search for an element
6.Show
7.Exit
Enter Data?30
node inserted
*********Main Menu*********
============================================
===
48
1.Insert in begining
2.Insert at last
3.Delete from Beginning
4.Delete from last
5.Search for an element
6.Show
7.Exit
node deleted
*********Main Menu*********
============================================
===
1.Insert in begining
2.Insert at last
3.Delete from Beginning
4.Delete from last
5.Search for an element
6.Show
7.Exit
node deleted
*********Main Menu*********
============================================
===
1.Insert in begining
2.Insert at last
3.Delete from Beginning
4.Delete from last
5.Search for an element
6.Show
7.Exit
============================================
===
1.Insert in begining
2.Insert at last
3.Delete from Beginning
4.Delete from last
5.Search for an element
6.Show
7.Exit
*********Main Menu*********
============================================
===
1.Insert in begining
2.Insert at last
3.Delete from Beginning
4.Delete from last
5.Search for an element
6.Show
7.Exit
RESULT :-
50
51
Ex. no.: 6 BINARY TREE
AIM:
To Write a C program to perform the operations on binary tree.
ALGORITHM:
a. Creation
1. Read data and store in a variable called as key
2. Allocate memory for a new node using malloc, specifying the size
for a single struct Node.
3. Assign the input to the data variable of the new node.
4. Set the ltree and rtree pointers to NULL, indicating this is a leaf node
or a new node with no children.
b. Insert an element in the Binary Search Tree
1. If the value of the new node is less than the root node then, it will be
inserted to the left subtree.
2. If the value of the new node is greater than root node then, it will be
inserted to the right subtree.
PROGRAM:
#include<stdio.h>
#include<stdlib.h>
Include<conio.h>
#define MAX_SIZE 25
#define max(a, b) a>b ? a : b
struct TreeNode
{
int val;
struct TreeNode* left;
struct TreeNode* right;
};
// function prototyping
void insert(int);
void delete(int);
int search(int);
int height(struct TreeNode*);
void inorder(struct TreeNode*);
void preorder(struct TreeNode*);
void postorder(struct TreeNode*);
void levelorder();
53
int main()
{
int user_choice, node_data;
char g='Y';
do
{
printf("\n\n--- Binary Tree --\n\n");
printf("\n1. Insert ");
printf("\n2. Delete");
printf("\n3. Search");
printf("\n4. Height");
printf("\n5. Inorder Traversal");
printf("\n6. Preorder Traversal");
printf("\n7. Postorder Traversal");
printf("\n8. Level order Traversal");
printf("\n9. Exit");
printf("\n\nEnter Your Choice: ");
scanf("%d", &user_choice);
printf("\n");
switch(user_choice)
{
case 1:
printf("Enter data for new node: ");
scanf("%d", &node_data);
insert(node_data);
break;
case 2:
printf("Enter node data: ");
scanf("%d", &node_data);
delete(node_data);
break;
case 3:
printf("Enter node data: ");
scanf("%d", &node_data);
int has_found = search(node_data);
if(has_found == -1) {
printf("\nNode was not found!");
} else {
printf("\nNode was found");
}
break;
case 4:
printf("height of the tree is: %d", height(root));
break;
54
case 5:
printf("Inorder Traversal\n\n");
inorder(root);
break;
case 6:
printf("Preorder Traversal\n\n");
preorder(root);
break;
case 7:
printf("Postorder Traversal\n\n");
postorder(root);
break;
case 8:
printf("Level order Traversal\n\n");
levelorder();
break;
case 9:
printf("Program is terminating...\n\n");
exit(0);
default:
printf("Invalid choice");
}
new_node->left = NULL;
new_node->right = NULL;
new_node->val = data;
55
return new_node;
}
if(temp->left != NULL)
{
queue[++rear] = temp->left;
}
else
{
new_node = create(data);
if(new_node)
{
temp->left = new_node;
printf("\n* Node with data %d was inserted", data);
}
return;
}
if(temp->right != NULL)
{
queue[++rear] = temp->right;
}
else
{
56
new_node = create(data);
if(new_node)
{
temp->right = new_node;
printf("\n* Node with data %d was inserted", data);
}
return;
}
}
}
queue[front + 1] = root;
front = rear = 0;
57
if (temp->val == key)
{
key_node = temp;
}
if (temp->left != NULL)
{
last_node = temp;
queue[++rear] = temp->left;
}
if (temp->right != NULL)
{
last_node = temp;
queue[++rear] = temp->right;
}
}
if (key_node != NULL)
{
key_node->val = temp->val;
if (last_node->right == temp)
{
last_node->right = NULL;
}
else
{
last_node->left = NULL;
}
printf("\n* Node with data %d was deleted", key);
free(temp);
return;
}
printf("\n* Node with data %d was not found", key);
}
queue[front + 1] = root;
front = rear = 0;
58
while (front <= rear)
{
struct TreeNode* temp = queue[front];
front++;
if (temp->val == key)
{
return 1;
}
if (temp->left != NULL)
{
queue[++rear] = temp->left;
}
if (temp->right != NULL)
{
queue[++rear] = temp->right;
}
}
return -1;
}
inorder(root->left);
59
printf("%d ", root->val);
inorder(root->right);
}
postorder(root->left);
postorder(root->right);
printf("%d ", root->val);
}
void levelorder()
{
if (root == NULL)
{
printf("Tree is Empty!");
return;
}
queue[front + 1] = root;
front = rear = 0;
if (temp->left != NULL)
{
queue[++rear] = temp->left;
60
}
if (temp->right != NULL)
{
queue[++rear] = temp->right;
}
}
}
Output:
--- Binary Tree --
1. Insert
2. Delete
3. Search
4. Height
5. Inorder Traversal
6. Preorder Traversal
7. Postorder Traversal
8. Level order Traversal
9. Exit
1. Insert
2. Delete
3. Search
4. Height
5. Inorder Traversal
6. Preorder Traversal
7. Postorder Traversal
8. Level order Traversal
9. Exit
61
--- Binary Tree --
1. Insert
2. Delete
3. Search
4. Height
5. Inorder Traversal
6. Preorder Traversal
7. Postorder Traversal
8. Level order Traversal
9. Exit
1. Insert
2. Delete
3. Search
4. Height
5. Inorder Traversal
6. Preorder Traversal
7. Postorder Traversal
8. Level order Traversal
9. Exit
1. Insert
2. Delete
3. Search
4. Height
5. Inorder Traversal
6. Preorder Traversal
62
7. Postorder Traversal
8. Level order Traversal
9. Exit
1. Insert
2. Delete
3. Search
4. Height
5. Inorder Traversal
6. Preorder Traversal
7. Postorder Traversal
8. Level order Traversal
9. Exit
Inorder Traversal
7423
Do u want to continue:::
63
Ex. no.: 7 Tree Traversal - inorder, preorder and postorder
AIM:
ALGORITHM:-
Pre-order Traversal:
Visit the root node.
Recursively traverse left sub-tree(in pre-order).
Recursively traverse right sub-tree(in pre-order).
void preorder(Treenode T) {
if (T == NULL)
return;
printData(T->data);
preorder(T->left);
preorder(T->right);
return;
}
PROGRAM:-
#include <stdio.h>
#include <stdlib.h>
struct tnode {
int data;
struct tnode *left, *right;
};
struct tnode *root = NULL;
struct tnode * createNode(int data) {
struct tnode *newNode;
newNode = (struct tnode *) malloc(sizeof(struct tnode));
newNode->data = data;
newNode->left = NULL;
newNode->right = NULL;
return (newNode);
}
65
}
return;
}
void inOrder(struct tnode *node) {
if (node) {
inOrder(node->left);
printf("%d ", node->data);
inOrder(node->right);
}
return;
}
int main() {
int data, ch;
while (1) {
printf("\n1. Insertion\n2. Pre-order\n");
printf("3. Post-order\n4. In-order\n");
printf("5. Exit\nEnter your choice:");
scanf("%d", &ch);
switch (ch) {
case 1:
printf("Enter ur data:");
scanf("%d", &data);
insertion(&root, data);
break;
case 2:
preOrder(root);
break;
case 3:
postOrder(root);
break;
case 4:
inOrder(root);
break;
case 5:
exit(0);
default:
printf("U've entered wrong opetion\n");
break;
} }
return 0; }
Output
1. Insertion
2. Pre-order
3. Post-order
4. In-order
5. Exit
Enter your choice:1
Enter ur data:40
1. Insertion
2. Pre-order
66
3. Post-order
4. In-order
5. Exit
Enter your choice:2
20 15 8 10 30 25 40
1. Insertion
2. Pre-order
3. Post-order
4. In-order
5. Exit
Enter your choice:3
10 8 15 25 40 30 20
1. Insertion
2. Pre-order
3. Post-order
4. In-order
5. Exit
Enter your choice:4
8 10 15 20 25 30 40
1. Insertion
2. Pre-order
3. Post-order
4. In-order
5. Exit
RESULT :-
67
Ex. no.: 8.a Breadth First Search
AIM:
ALGORITHM:
Program:
include<stdio.h>
int queue[10];
int front=0,back=0;
void pop()
{
queue[front] = 0;
front++;
}
int main()
68
{
int v,n,i,j;
int graph[10][10];
printf("Enter the number of vertices: ");
scanf("%d", &n);
printf("Enter graph data in matrix form: \n");
for (i = 0; i < n; i++)
for (j = 0; j < n; j++)
scanf("%d", &graph[i][j]);
pop();
OUTPUT
Enter the number of vertices: 6
Enter graph data in matrix form:
011000
101000
110110
001000
001001
000010
Enter the starting vertex: 2
2132456
RESULT:
Thus the above c program for Graph Traversal Algorithm is
successfully completed
69
Ex. no.: 8.b Depth First search
AIM:
ALGORITHM:
1. First, create a stack with the total number of vertices in the graph.
2. Now, choose any vertex as the starting point of traversal, and push
that vertex into the stack.
4. Now, repeat steps 3 and 4 until no vertices are left to visit from the
vertex on the stack's top.
PROGRAM:
#include <stdio.h>
void dfs(int v)
int i;
visited[v] = 1;
dfs(i);
}
70
}
int main( )
scanf("%d", &n);
visited[i] = 0;
a[i][j] = 0;
scanf("%d", &a[i][j]);
scanf("%d", &v);
dfs(v);
return 0;
OUTPUT
71
011000
101000
110110
001000
001001
000010
2->1
1->3
3->4
3->5
5->6
72
Ex. no.:9.a Prim’s Algorithm
AIM:
ALGORITHM:
1. Declare an array visited[] to store the visited vertices and firstly, add
the arbitrary root, say S, to the visited array.
2. Check whether the adjacent vertices of the last visited vertex are
present in the visited[] array or not.
3. If the vertices are not in the visited[] array, compare the cost of edges
and add the least cost edge to the output spanning tree.
4. The adjacent unvisited vertex with the least cost edge is added into the
visited[] array and the least cost edge is added to the minimum
spanning tree output.
5. Steps 2 and 4 are repeated for all the unvisited vertices in the graph to
obtain the full minimum spanning tree output for the given graph.
# include<stdio.h>
int G[50][50],select[50], i, j, k, n, min_dist,total=0,u, v;
void Prim()
{
printf("\n\n The Minimal Spanning Tree Is :\n");
select[0] = 1;
for (k=1 ; k<n ; k++)
{
min_dist = 32767;
for (i=0 ; i<n ; i++)
for (j=0 ; j<n ; j++)
if (G[i][j] && ((select[i] && !select[j]) || (!select[i] && select[j])))
if (G[i][j] < min_dist)
{
min_dist = G[i][j];
u = i;
v = j;
}
printf("\n Edge (%d %d )and weight = %d",u,v,min_dist);
select[u] = select[v] = 1;
total =total+min_dist;
73
}
printf("\n\n\t Total Path Length Is = %d",total);
}
int main()
{
printf("\n Enter Number of Nodes in The Graph: ");
scanf("%d",&n);
for(i=0;i<n;i++)
{ printf("\n");
for(j=0;j<n;j++)
{
printf("a[%d][%d]: ",i,j);
scanf("%d",&G[i][j]);
}
}
Prim();
return 0;
}
Output:-
Enter Number of Nodes in The Graph: 6
a[0][0]: 0
a[0][1]: 3
a[0][2]: 1
a[0][3]: 6
a[0][4]: 0
a[0][5]: 0
a[1][0]: 3
a[1][1]: 0
a[1][2]: 5
a[1][3]: 0
a[1][4]: 3
a[1][5]: 0
a[2][0]: 1
a[2][1]: 5
a[2][2]: 0
a[2][3]: 5
a[2][4]: 6
a[2][5]: 4
a[3][0]: 6
a[3][1]: 0
a[3][2]: 5
a[3][3]: 0
a[3][4]: 0
a[3][5]: 2
74
a[4][0]: 0
a[4][1]: 3
a[4][2]: 6
a[4][3]: 0
a[4][4]: 0
a[4][5]: 6
a[5][0]: 0
a[5][1]: 0
a[5][2]: 4
a[5][3]: 2
a[5][4]: 6
a[5][5]: 0
RESULT:
Thus the above c program of Prim’s Algorithm implementation is
successfully completed.
75
Ex. no.:9.b Kruskal’s Algorithm
AIM:
ALGORITHM:
1. Sort all the edges in the graph in an ascending order and store it in
an array edge[].
2. Construct the forest of the graph on a plane with all the vertices in
it.
3. Select the least cost edge from the edge[] array and add it into the
forest of the graph. Mark the vertices visited by adding them into
the visited[] array.
4. Repeat the steps 2 and 3 until all the vertices are visited without
having any cycles forming in the graph
5. When all the vertices are visited, the minimum spanning tree is
formed.
#include <stdio.h>
#include <stdlib.h>
int k, a, b, u, v, n, ne = 1;
int mincost = 0;
int applyfind(int i)
while(p[i] != 0)
i=p[i];
return i;
76
}
if(i!=j) {
p[j]=i;
return 1;
return 0;
int main()
n = 3;
int i, j;
if (cost[i][j] == 0) {
cost[i][j] = inf;
while(ne < n) {
min_val = cost[i][j];
77
a = u = i;
b = v = j;
u = applyfind(u);
v = applyfind(v);
if(applyunion(u, v) != 0) {
mincost +=min_val;
ne++;
return 0;
Output
0 -> 1
1 -> 2
Minimum cost = 25
78
AIM:
Algorithm:
1. Mark the source node with a current distance of 0 and the rest with
infinity.
2. Set the non-visited node with the smallest current distance as the
current node.
3. For each neighbor, N of the current node adds the current distance
of the adjacent node with the weight of the edge connecting 0->1. If
it is smaller than the current distance of Node, set it as the new
current distance of N.
PROGRAM:
#include <stdio.h>
#include <limits.h>
return minIndex;
}
79
void dijkstra(int graph[MAX_VERTICES][MAX_VERTICES], int src, int
vertices)
{
int dist[MAX_VERTICES];
int sptSet[MAX_VERTICES];
dist[src] = 0;
sptSet[u] = 1;
printSolution(dist, vertices);
}
int main() {
int vertices;
80
int graph[MAX_VERTICES][MAX_VERTICES];
printf("Input the adjacency matrix for the graph (use INT_MAX for
infinity):\n");
for (int i = 0; i < vertices; i++) {
for (int j = 0; j < vertices; j++) {
scanf("%d", &graph[i][j]);
}
}
int source;
return 0;
}
Output:
Input the number of vertices: 5
Input the adjacency matrix for the graph (use INT_MAX for infinity):
03200
30010
20014
01102
00420
Input the source vertex: 0
Vertex Distance from Source
0 0
1 3
2 2
3 3
4 5
81
AIM:-
To arrange the list of numbers in ascending order using quick
sort
ALGORITHM:-
PROGRAM:
#include<stdio.h>
#include<conio.h>
void quicksort(int [10],int,int);
void main()
{
int a[20],n,i;
clrscr();
printf("Enter size of the array: ");
scanf("%d",&n);
printf("Enter elements: ");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
quicksort(a,0,n-1);
printf("Sorted elements: ");
for(i=0;i<n;i++)
printf(" %d",a[i]);
getch();
}
OUTPUT:
Enter size of array: 5
Enter Elements: 6 2 9 8 4
Sorted Elements: 2 4 6 8 9
RESULT:-
83
Ex. no.: 11b MERGE SORT
AIM:-
To arrange the list of numbers in ascending order using Merge
sort
ALGORITHM:-
STEP 1 : Divide Step If a given array A has zero or one element, simply
return; it is already sorted. Otherwise, split A[p .. r] into two subarrays A[p
.. q] and A[q + 1 .. r], each containing about half of the elements of A[p ..
r]. That is, q is the halfway point of A[p .. r].
PROGRAM:
#include<stdio.h>
#include<conio.h>
void main()
{
int i,n;
clrscr();
printf("\n\nMERGE SORT");
printf("\n\n*********");
printf("\n\nEnter the limit : ");
scanf("%d",&n);
printf("\nEnter the elements\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
merge_split(a,0,n-1);
printf("\n\nSorted list : ");
for(i=0;i<n;i++)
printf("\n %d",a[i]);
getch();
}
RESULT:-
85
Ex. no.: 12 a LINEAR SEARCH
AIM:-
To write a c program to implement linear search
ALGORITHM:-
STEP 1
:Start the program
STEP 2
:Enter the limit to n
STEP 3
:Read the values in an array upto n
STEP 4
:Enter the element m to be searched in an array
STEP 5
:Find whether the element is found in the list of values
STEP 6
:If it is present, then assign a flag.
STEP 7
:If the value of flag is 1,then print that the element is found
in the list of elements.
STEP 8 :Else the element is not found
STEP 9 :Stop the program.
PROGRAM:
#include <stdio.h>
#include<conio.h>
void main()
{
int a[100], search, i, n;
clrscr();
printf("Enter the number of elements in array\n");
scanf("%d",&n);
printf("Enter elements:");
for (i = 0; i < n; i++)
scanf("%d", &a[i]);
getch();
}
86
OUTPUT:
Enter the number of elements in array: 5
Enter elements
67
23
45
89
1
Enter the number to search: 23
23 is present at location 2
RESULT :-
87
Ex. no.: 12 b BINARY SEARCH
AIM:-
To write a c program to implement binary search
ALGORITHM:-
PROGRAM:
#include <stdio.h>
#include<conio.h>
void main()
{
int i, first, last, middle, n, search, a[100];
clrscr();
printf("Enter number of elements\n");
scanf("%d",&n);
printf("Enter Elements:");
first = 0;
last = n - 1;
middle = (first+last)/2;
getch();
}
OUTPUT:
Enter the number of elements in array: 5
Enter elements
1 2 3 4 5
Enter value to find: 3
3 found at location 3
RESULT : -
89