0% found this document useful (0 votes)
11 views92 pages

Data Structure Lab Manual

The document is a laboratory manual for a Data Structures course (SECE2221) at P P Savani School of Engineering, detailing practical assignments completed by a student named Shruthi. It includes various programming tasks, algorithms, and coding examples related to memory allocation, array manipulation, data structures, and student information management. Each practical section outlines the aim, algorithm, coding, output, and results of the exercises performed.

Uploaded by

riteshsingh1706v
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)
11 views92 pages

Data Structure Lab Manual

The document is a laboratory manual for a Data Structures course (SECE2221) at P P Savani School of Engineering, detailing practical assignments completed by a student named Shruthi. It includes various programming tasks, algorithms, and coding examples related to memory allocation, array manipulation, data structures, and student information management. Each practical section outlines the aim, algorithm, coding, output, and results of the exercises performed.

Uploaded by

riteshsingh1706v
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

School of LABORATORY MANUAL

Engineering
Department of Information Technology &Engineering

DATA STRUCTURES
(SECE2221)|[Link].

SHRUTHI
Name of Student:

EnrollmentNo.: 23SE02IE030 AcademicYear: 2024-2025


P P Savani School of
Engineering

This is to certify that

Mr./Ms. SHRUTHI

of INFORMATION TECHNOLOGY & ENGINEERING

Engineering having

EnrollmentNo. 23SE02IE030 has completed

his/her Term work in the subject of


DATA STRUCTURES

(SECE2221).

Marks Obtained: out of

Sign of Faculty Sign of Head of Department

Date: Date:
CONTENTS

Sr. Name of the practical Page Date Marks Sign.


No
No
1. Memory Allocation 1 21.06.2024

2. One-dimensional array
4 28.06.2024
3. Data Structure -
7 28.06.2024
4. Structure and Function. 12 05.07.2024

5. Storing student information using 16 05.07.2024


structures
6. Insertion Sort 21
12.07.2024
7. Selection Sort 24
19.07.2024
8. Bubble Sort 27

9. Linear search 30 26.07.2024

10. Binary search 32 02.08.2024

11. Stack implementation 34 09.08.2024

12. Linear Queue Implementation 37 23.08.2024

13. Singly Linked List Implementation 41 30.08.2024

14. Circular Linked List Operations 48 06.09.2024

15. Doubly Linked List Operations 55 13.09.2024

16. Linked Stack Implementation 64 20.09.2024

17. Implementing a Linked Queue 72 27.09.2024

Implementing a Binary Search Tree


18. (BST) 77 04.10,2024

Binary Tree Operations: Creation,


19. Insertion, 85 11.10.2024
and Deletion
23SE02IT030

PRACTICAL NO: - 1
AIM:
Write a program to create memory for int, char, and float variables at a run time.

ALGORITHM:

Here's a simple algorithm to create memory for int, char, and float variables at runtime:

1. Start
2. Include Required Header: Include the <stdlib.h> header file for memory
allocation functions and <stdio.h> for input/output functions.
3. Allocate Memory:

 Use malloc or calloc to allocate memory for each variable type.


 Check if the allocation was successful by verifying that the returned
pointer is not NULL.

4. Use the Allocated Memory:

 Assign values to the allocated memory.


 Use the values as needed in your program.

5. Free the Memory:

 Once you're done using the allocated memory, use free to release it.

[Link]

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

int main() {
// 1. Allocate memory for an int
int *intPtr = (int *)malloc(sizeof(int));
if (intPtr == NULL) {
printf("Memory allocation failed for int.\n");
return 1; // Exit the program with an error code

// 2. Allocate memory for a char


SHRUTI KATARIYA 1
23SE02IT030

char *charPtr = (char *)malloc(sizeof(char));


if (charPtr == NULL) {
printf("Memory allocation failed for char.\n");
free(intPtr); // Free previously allocated memory before exiting
return 1;
}

// 3. Allocate memory for a float


float *floatPtr = (float *)malloc(sizeof(float));
if (floatPtr == NULL) {
printf("Memory allocation failed for float.\n");
free(intPtr); // Free previously allocated memory before exiting
free(charPtr);
return 1;
}

// 4. Use the allocated memory


*intPtr = 42; // Assign a value to int
*charPtr = 'A'; // Assign a value to char
*floatPtr = 3.14f; // Assign a value to float

// Print the values


printf("Integer value: %d\n", *intPtr);
printf("Char value: %c\n", *charPtr);
printf("Float value: %.2f\n", *floatPtr);

// 5. Free the allocated memory


free(intPtr);
free(charPtr);
free(floatPtr);

return 0; // Successful execution


}

OUTPUT:

SHRUTI KATARIYA 2
23SE02IT030

RESULT:

Above program is executed successfully.

SHRUTI KATARIYA 3
23SE02IT030

PRACTICAL NO: - 2

AIM:
C program to read a one-dimensional array, and print sum of all elements along with
inputted array elements.

ALGORITHM:

1. Start
2. Input the Size of the Array
 Prompt the user to enter the number of elements for the array.
 Read the integer value provided by the user and store it in a variable n.
3. Declare the Array
 Declare an integer array array with a size of n.
4. Input Array Elements
 Print a prompt asking the user to enter n elements for the array.
 Use a loop to read n integer values from the user and store each value in
the array.
5. Compute the Sum of Array Elements
 Initialize a variable sum to zero.
 Use a loop to iterate through each element of the array and add each
element's value to sum.
6. Print Array Elements
 Print a message indicating that the array elements are being displayed.
 Use a loop to print each element of the array on the same line.
7. Print the Sum
 Print a message indicating the sum of the array elements.
 Display the computed sum.
8. End

CODING:

#include <stdio.h>

int main() {

int n; // Number of elements in the array

int i; // Loop index

SHRUTI KATARIYA 4
23SE02IT030

int sum = 0; // Variable to store the sum of array elements

// Input number of elements

printf("Enter the number of elements in the array: ");

scanf("%d", &n);

// Declare the array with the size specified by the user

int array[n];

// Input array elements

printf("Enter %d elements:\n", n);

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

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

// Calculate the sum of array elements

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

sum += array[i];

// Print the array elements

printf("Array elements:\n");

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

printf("%d ", array[i]);

SHRUTI KATARIYA 5
23SE02IT030

printf("\n");

// Print the sum of the array elements

printf("Sum of all elements: %d\n", sum);

return 0;

OUTPUT:

RESULT:

Above program of one-dimensional array is excuted successfully.

SHRUTI KATARIYA 6
23SE02IT030

PRACTICAL NO: -3
AIM:
Develop a structure to represent planets in the solar system. Each planet has the
fieldfor the planets name, its distance from the sun in miles and the number of moons it
[Link] a program to read the data for each planet and store. Also print the name of
theplanet that has the highest number of moons.

ALGORITHM:

1. Start

2. Define a Structure for Planets:

 Create a struct to represent each planet, with fields for the planet's name,
distance from the sun (in miles), and the number of moons.

3. Input Data for Each Planet:

 Prompt the user to input data for each planet: name, distance from the sun, and
number of moons.

4. Store the Data:

 Use an array of structures to store the data for each planet.

5. Determine the Planet with the Most Moons:

 Traverse the array of structures to find the planet with the highest number of
moons.

6. Output the Results:

 Print the name of the planet with the highest number of moons.

CODING:

#include <stdio.h>

#include <string.h>

SHRUTI KATARIYA 7
23SE02IT030

// Define a structure to represent a planet

struct Planet {

char name[50];

double distance_from_sun; // in miles

int number_of_moons;

};

// Function to input data for a planet

void inputPlanetData(struct Planet *p) {

printf("Enter the planet's name: ");

scanf("%s", p->name);

printf("Enter the distance from the sun in miles: ");

scanf("%lf", &p->distance_from_sun);

printf("Enter the number of moons: ");

scanf("%d", &p->number_of_moons);

// Function to find the planet with the most moons

struct Planet findPlanetWithMostMoons(struct Planet planets[], int num_planets) {

struct Planet max_moons_planet = planets[0];

for (int i = 1; i < num_planets; i++) {

if (planets[i].number_of_moons > max_moons_planet.number_of_moons) {

max_moons_planet = planets[i];

SHRUTI KATARIYA 8
23SE02IT030

return max_moons_planet;

int main() {

int num_planets;

// Input the number of planets

printf("Enter the number of planets: ");

scanf("%d", &num_planets);

// Create an array to store planets

struct Planet planets[num_planets];

// Input data for each planet

for (int i = 0; i < num_planets; i++) {

printf("\nEntering data for planet %d:\n", i + 1);

inputPlanetData(&planets[i]);

// Find the planet with the most moons

struct Planet most_moons_planet = findPlanetWithMostMoons(planets,


num_planets);

// Print the result

SHRUTI KATARIYA 9
23SE02IT030

printf("\nThe planet with the most moons is %s with %d moons.\n",

most_moons_planet.name, most_moons_planet.number_of_moons);

return 0;

OUTPUT:

SHRUTI KATARIYA 10
23SE02IT030

RESULT:

Abovr program of Planetary data structure is excuted successfully.

SHRUTI KATARIYA 11
23SE02IT030

PRACTICAL NO: - 4
AIM;
Write a c program to Add Two Complex Numbers by Passing Structure to a Function.

ALGORITHM:

1. Start

2. Define a Structure for Complex Numbers:

 Create a struct to represent a complex number, with fields for the real and
imaginary parts.

3. Function to Add Complex Numbers:

 Define a function that takes two struct parameters representing complex


numbers, adds them, and returns the result.

4. Input Complex Numbers:

 Prompt the user to enter the real and imaginary parts of two complex numbers.

5. Call the Addition Function:

 Pass the complex numbers to the addition function and get the result.

6. Display the Result:

 Print the sum of the complex numbers.

CODING:

#include <stdio.h>

#include <string.h>

// Define a structure to represent a planet

struct Planet {

SHRUTI KATARIYA 12
23SE02IT030

char name[50];

double distance_from_sun; // in miles

int number_of_moons;

};

// Function to input data for a planet

void inputPlanetData(struct Planet *p) {

printf("Enter the planet's name: ");

scanf("%s", p->name);

printf("Enter the distance from the sun in miles: ");

scanf("%lf", &p->distance_from_sun);

printf("Enter the number of moons: ");

scanf("%d", &p->number_of_moons);

// Function to find the planet with the most moons

struct Planet findPlanetWithMostMoons(struct Planet planets[], int num_planets) {

struct Planet max_moons_planet = planets[0];

for (int i = 1; i < num_planets; i++) {

if (planets[i].number_of_moons > max_moons_planet.number_of_moons) {

max_moons_planet = planets[i];

return max_moons_planet;

SHRUTI KATARIYA 13
23SE02IT030

int main() {

int num_planets;

// Input the number of planets

printf("Enter the number of planets: ");

scanf("%d", &num_planets);

// Create an array to store planets

struct Planet planets[num_planets];

// Input data for each planet

for (int i = 0; i < num_planets; i++) {

printf("\nEntering data for planet %d:\n", i + 1);

inputPlanetData(&planets[i]);

// Find the planet with the most moons

struct Planet most_moons_planet = findPlanetWithMostMoons(planets,


num_planets);

// Print the result

printf("\nThe planet with the most moons is %s with %d moons.\n",

most_moons_planet.name, most_moons_planet.number_of_moons);

SHRUTI KATARIYA 14
23SE02IT030

return 0;

OUTPUT:

RESULT:

Above program of adding two complex numbers using structures and functions is
executed successfully.

SHRUTI KATARIYA 15
23SE02IT030

PRACTICAL NO: -5

AIM:
Write a c program to store Student Information using Structures

ALGORITHM:

1. Start

2. Define a Structure for Student Information:

 Create a struct to represent a student with fields for the student’s name, roll
number, and grade.

3. Input Student Information:

 Write a function to prompt the user to enter the student's details and store them
in a struct.

4. Store Multiple Student Records:

 Use an array of struct to store the information for multiple students.

5. Display Student Information:

 Write a function to display the information of each student.

6. Main Function:

 In the main() function, use the above functions to input and display student
information.

7. End

CODING:

#include <stdio.h>

#include <string.h>

// Define a structure to represent a student

SHRUTI KATARIYA 16
23SE02IT030

struct Student {

char name[100];

int roll_number;

char grade;

};

// Function to input student information

void inputStudentInfo(struct Student *s) {

printf("Enter student's name: ");

scanf(" %[^\n]%*c", s->name); // Read string with spaces

printf("Enter student's roll number: ");

scanf("%d", &s->roll_number);

printf("Enter student's grade (A/B/C/D/F): ");

scanf(" %c", &s->grade); // Read a single character

// Function to display student information

void displayStudentInfo(struct Student s) {

printf("\nStudent Information:\n");

printf("Name: %s\n", [Link]);

printf("Roll Number: %d\n", s.roll_number);

printf("Grade: %c\n", [Link]);

SHRUTI KATARIYA 17
23SE02IT030

int main() {

int num_students;

// Input the number of students

printf("Enter the number of students: ");

scanf("%d", &num_students);

// Create an array to store student information

struct Student students[num_students];

// Input information for each student

for (int i = 0; i < num_students; i++) {

printf("\nEntering data for student %d:\n", i + 1);

inputStudentInfo(&students[i]);

// Display information for each student

for (int i = 0; i < num_students; i++) {

printf("\nStudent %d:\n", i + 1);

displayStudentInfo(students[i]);

return 0;

SHRUTI KATARIYA 18
23SE02IT030

OUTPUT:

SHRUTI KATARIYA 19
23SE02IT030

RESULT:

Above program storing student information using structures is excuted successfully.

SHRUTI KATARIYA 20
23SE02IT030

PRACTICAL NO: - 6

AIM:
Write program to perform Insertion sort.

ALGORITHM:

1. Initialize:

 Start with the second element (index 1) as the key.

2. Compare and Shift:

 Compare the key with the elements before it. If the key is smaller than
the compared element, shift the compared element one position to the
right.

3. Insert Key:

 Insert the key where the shifting of elements stops.

4. Repeat:

 Repeat steps 2-3 for all elements in the unsorted part of the list

CODING:

#include <stdio.h>

// Function to perform insertion sort


void insertionSort(int arr[], int n) {
int i, j, key;

// Traverse through 1 to n-1


for (i = 1; i < n; i++) {
key = arr[i]; // Element to be inserted
j = i - 1;

// Move elements of arr[0..i-1] that are greater than key


// to one position ahead of their current position
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];

SHRUTI KATARIYA 21
23SE02IT030

j = j - 1;
}
arr[j + 1] = key;
}
}

// Function to print an array


void printArray(int arr[], int size) {
int i;
for (i = 0; i < size; i++)
printf("%d ", arr[i]);
printf("\n");
}

int main() {
int arr[] = {12, 11, 13, 5, 6};
int n = sizeof(arr) / sizeof(arr[0]);

printf("Original array: \n");


printArray(arr, n);

insertionSort(arr, n);

printf("Sorted array: \n");


printArray(arr, n);

return 0;
}

OUTPUT:

SHRUTI KATARIYA 22
23SE02IT030

RESULT:

Above program of insertion sort algorithm and implementation is executed


successfully.

SHRUTI KATARIYA 23
23SE02IT030

PRACTICAL NO: -7
AIM:

Write a program to perform Selection sort.

ALGORITHM:

1. Initialize:

 Start with the first element of the array.

2. Find the Minimum Element:

 For the current position, find the minimum element in the unsorted portion of
the array (from the current position to the end).

3. Swap:

 Swap the found minimum element with the element at the current position.

4. Move to the Next Position:

 Move to the next position and repeat the process until the entire array is sorted.

CODING:

#include <stdio.h>

// Function to perform selection sort

void selectionSort(int arr[], int n) {

int i, j, min_index, temp;

// Traverse through all array elements

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

// Find the minimum element in the unsorted portion of the array

SHRUTI KATARIYA 24
23SE02IT030

min_index = i;

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

if (arr[j] < arr[min_index]) {

min_index = j;

// Swap the found minimum element with the first element of the unsorted portion

if (min_index != i) {

temp = arr[i];

arr[i] = arr[min_index];

arr[min_index] = temp;

// Function to print an array

void printArray(int arr[], int size) {

int i;

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

printf("%d ", arr[i]);

printf("\n");

int main() {

SHRUTI KATARIYA 25
23SE02IT030

int arr[] = {64, 25, 12, 22, 11};

int n = sizeof(arr) / sizeof(arr[0]);

printf("Original array: \n");

printArray(arr, n);

selectionSort(arr, n);

printf("Sorted array: \n");

printArray(arr, n);

return 0;

OUTPUT:

RESULT:

Above program of selection sort algorithm and implementation is executed


successfully.

SHRUTI KATARIYA 26
23SE02IT030

PRACTICAL NO: -8
AIM:
Write a program to perform Bubble sort.

ALGORITHM:

1. Start at the beginning of the list.

2. Compare the current element with the next element.

3. If the current element is greater than the next element, swap them.

4. Move to the next pair of adjacent elements.

5. Repeat steps 2-4 for each pair of adjacent elements, until the end of the list is
reached. This completes one pass.

6. Repeat the entire process for the remaining elements (excluding the last sorted
elements) until no more swaps are needed.

7. End when no swaps are made in a full pass through the list, indicating the list is
sorted.

CODING:

#include <stdio.h>

// Function to perform Bubble Sort


void bubbleSort(int arr[], int n) {
int i, j, temp;
int swapped;

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


swapped = 0; // Reset the swap flag
for (j = 0; j < n - i - 1; j++) {
// Compare the adjacent elements
if (arr[j] > arr[j + 1]) {
// Swap if they are in the wrong order

SHRUTI KATARIYA 27
23SE02IT030

temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
swapped = 1; // A swap has occurred
}
}
// If no two elements were swapped by the inner loop, then the array is sorted
if (swapped == 0) {
break;
}
}
}

// Function to print an array


void printArray(int arr[], int size) {
int i;
for (i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}

int main() {
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int n = sizeof(arr) / sizeof(arr[0]);

printf("Original array: \n");


printArray(arr, n);

bubbleSort(arr, n);

printf("Sorted array: \n");


printArray(arr, n);

return 0;
}

OUTPUT:

SHRUTI KATARIYA 28
23SE02IT030

RESULT:

Above program of Bubble Sort Algorithm and Implementation is executed successfully.

SHRUTI KATARIYA 29
23SE02IT030

PRACTICAL NO: - 9

AIM:
Write a program to perform linear search.

ALGORITHM:

1. Start

2. Input: Array arr of size n and the key to be searched.

3. Initialize: i = 0

4. Repeat steps 5-6 while i < n

5. If arr[i] == key, then:

 Output: “Key found at index i”


 Exit

[Link] i by 1

[Link]: “Key not found”

[Link]

CODING:

#include <stdio.h>

// Function to perform linear search


int linearSearch(int arr[], int size, int target) {
for (int i = 0; i < size; i++) {
if (arr[i] == target) {
return i; // Return the index where the target is found
}
}
return -1; // Return -1 if the target is not found
}

SHRUTI KATARIYA 30
23SE02IT030

int main() {
int arr[] = {5, 7, 12, 23, 34, 45, 56}; // Example array
int size = sizeof(arr) / sizeof(arr[0]); // Calculate the size of the array
int target;

// Get the target value from the user


printf("Enter the number to search: ");
scanf("%d", &target);

// Perform linear search


int result = linearSearch(arr, size, target);

// Check if the result is valid


if (result != -1) {
printf("Element %d found at index %d.\n", target, result);
} else {
printf("Element %d not found in the array.\n", target);
}

return 0;
}

OUTPUT:

RESULT:

Above program of linear search is executed successfully.

SHRUTI KATARIYA 31
23SE02IT030

PRACTICAL NO: -10


AIM:
Write a program to perform binary search.

ALGORITHM:

1. Initialize:

 Set low to the first index (0).


 Set high to the last index (length of array - 1).

2. While Loop:

 Calculate mid as the average of low and high indices.


 If the mid element is equal to the target, return mid.
 If the target is less than the mid element, adjust high to mid - 1.
 Otherwise, adjust low to mid + 1.

3. Return:

 If the loop exits, return an indication that the target is not in the array (e.g., -1).

CODING:

#include <stdio.h>

// Function to perform binary search


int binarySearch(int arr[], int size, int target) {
int low = 0;
int high = size - 1;

while (low <= high) {


int mid = low + (high - low) / 2; // Calculate the mid index

// Check if target is present at mid


if (arr[mid] == target) {
return mid; // Target found
}

// If target is greater, ignore the left half


if (arr[mid] < target) {
low = mid + 1;
}

SHRUTI KATARIYA 32
23SE02IT030

// If target is smaller, ignore the right half


else {
high = mid - 1;
}
}

// Target is not present in the array


return -1;
}

int main() {
// Example usage
int arr[] = {2, 3, 4, 10, 40}; // Must be sorted
int size = sizeof(arr) / sizeof(arr[0]);
int target = 10;

int result = binarySearch(arr, size, target);

if (result != -1) {
printf("Element found at index %d\n", result);
} else {
printf("Element not found in array\n");
}

return 0;
}

OUTPUT:

RESULT:
Above program of binary search is executed successfully.

SHRUTI KATARIYA 33
23SE02IT030

PRACTICAL NO: -11

AIM:
Write a program to implement stack and perform push, pop operation.

ALGORITHM:

1. Initialization

 Create a stack with a fixed size (if using an array) or a dynamic size (if using a linked
list).
 Initialize the stack's top index (or pointer) to indicate an empty stack.

2. Push Operation

 Check if the stack is full (for a fixed-size stack).


 If not full, increment the top index (or pointer) and place the new element at this
position.

3. Pop Operation

 Check if the stack is empty.


 If not empty, retrieve the element at the top index (or pointer) and then decrement the
top index (or pointer).

CODING:

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

#define MAX 100 // Define the maximum size of the stack

// Structure to represent a stack


typedef struct {
int top;
int array[MAX];
} Stack;

// Function to initialize the stack


void initialize(Stack *s) {
s->top = -1;
}

// Function to check if the stack is full


int isFull(Stack *s) {

SHRUTI KATARIYA 34
23SE02IT030

return s->top == MAX - 1;


}

// Function to check if the stack is empty


int isEmpty(Stack *s) {
return s->top == -1;
}

// Function to push an element onto the stack


void push(Stack *s, int value) {
if (isFull(s)) {
printf("Stack overflow! Cannot push %d\n", value);
} else {
s->array[++(s->top)] = value;
printf("%d pushed onto stack\n", value);
}
}

// Function to pop an element from the stack


int pop(Stack *s) {
if (isEmpty(s)) {
printf("Stack underflow! Cannot pop\n");
return -1; // Return -1 or another sentinel value to indicate error
} else {
return s->array[(s->top)--];
}
}

// Function to display the elements of the stack


void display(Stack *s) {
if (isEmpty(s)) {
printf("Stack is empty\n");
} else {
printf("Stack elements are:\n");
for (int i = s->top; i >= 0; i--) {
printf("%d\n", s->array[i]);
}
}
}

int main() {
Stack s;
initialize(&s);

// Test the stack operations


push(&s, 10);
push(&s, 20);
push(&s, 30);

SHRUTI KATARIYA 35
23SE02IT030

printf("Popped element: %d\n", pop(&s));

display(&s);

return 0;
}

OUTPUT:

RESULT:
Above program stack and perform push, pop operation is executed successfully

SHRUTI KATARIYA 36
23SE02IT030

PRACTICAL NO: - 12
AIM:
Write a program to perform the following operations in linear queue – Addition,
Deletion and Traversing

ALGORITHM:

1. Initialization

 Set front and rear to -1 (indicating an empty queue).


 Define the maximum size of the queue.

2. Addition (Enqueue)

 Check if the queue is full. If rear is equal to MAX_SIZE - 1, print "Queue is full."
 Otherwise, increment rear and add the new element to the position pointed to
by rear.
 If front is -1, set front to 0.

3. Deletion (Dequeue)

 Check if the queue is empty. If front is -1, print "Queue is empty."


 Otherwise, retrieve the element at the position pointed to by front and
increment front.
 If front exceeds rear, reset front and rear to -1 (queue is empty).

4. Traversal

 Start from front and go up to rear, printing each element.

CODING:

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

#define MAX_SIZE 100

typedef struct {
int items[MAX_SIZE];
int front, rear;
} Queue;

// Function to initialize the queue


void initializeQueue(Queue *q) {

SHRUTI KATARIYA 37
23SE02IT030

q->front = -1;
q->rear = -1;
}

// Function to check if the queue is empty


int isEmpty(Queue *q) {
return q->front == -1;
}

// Function to check if the queue is full


int isFull(Queue *q) {
return q->rear == MAX_SIZE - 1;
}

// Function to add an element to the queue


void enqueue(Queue *q, int value) {
if (isFull(q)) {
printf("Queue is full\n");
return;
}
if (isEmpty(q)) {
q->front = 0;
}
q->rear++;
q->items[q->rear] = value;
printf("Inserted %d\n", value);
}

// Function to remove an element from the queue


void dequeue(Queue *q) {
if (isEmpty(q)) {
printf("Queue is empty\n");
return;
}
printf("Removed %d\n", q->items[q->front]);
q->front++;
if (q->front > q->rear) {
initializeQueue(q); // Reset queue if it's empty
}
}

// Function to traverse the queue


void traverse(Queue *q) {
if (isEmpty(q)) {
printf("Queue is empty\n");
return;
}
printf("Queue elements are:\n");

SHRUTI KATARIYA 38
23SE02IT030

for (int i = q->front; i <= q->rear; i++) {


printf("%d ", q->items[i]);
}
printf("\n");
}

int main() {
Queue q;
initializeQueue(&q);

// Perform some operations


enqueue(&q, 10);
enqueue(&q, 20);
enqueue(&q, 30);

traverse(&q);

dequeue(&q);
traverse(&q);

enqueue(&q, 40);
traverse(&q);

return 0;
}

OUTPUT:

SHRUTI KATARIYA 39
23SE02IT030

RESULT:

Above program is executed successfully.

SHRUTI KATARIYA 40
23SE02IT030

PRACTICAL NO: -13


AIM:

Write a program to perform the following operations in singly linked list – Creation,
Insertion, and Deletion.

ALGORITHM:

1. Creation

1. Initialize the head pointer to NULL, indicating an empty list.


2. To create the list, repeatedly read data from the user and insert nodes until the
user decides to stop.

2. Insertion

 At the Beginning:
o Create a new node.
o Set its data to the new value.
o Set its next to the current head.
o Update the head to the new node.
 At the End:
o Create a new node.
o Set its data to the new value.
o Traverse the list to find the last node.
o Set the next of the last node to the new node.
 At a Given Position:
o Create a new node.
o Traverse the list to the position before where you want to insert the new
node.
o Set the new node’s next to the next node of the current node.
o Update the next of the current node to the new node.

3. Deletion

 From the Beginning:


o Check if the list is empty.
o Update the head to the next node of the current head.
o Free the memory of the old head node.
 From the End:
o Traverse the list to find the second last node.
o Set its next to NULL.
o Free the memory of the last node.

SHRUTI KATARIYA 41
23SE02IT030

 At a Given Position:
o Traverse the list to the node before the position to be deleted.
o Set the next of this node to the node after the node to be deleted.
o Free the memory of the node to be deleted.

CODING:

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

// Define the node structure


struct node {
int data;
struct node* next;
};

struct node* head = NULL;

// Function to create a new node


struct node* createNode(int data) {
struct node* newNode = (struct node*)malloc(sizeof(struct node));
newNode->data = data;
newNode->next = NULL;
return newNode;
}

// Function to insert at the beginning


void insertAtBeginning(int data) {
struct node* newNode = createNode(data);
newNode->next = head;
head = newNode;
}

// Function to insert at the end


void insertAtEnd(int data) {
struct node* newNode = createNode(data);
if (head == NULL) {
head = newNode;
} else {
struct node* temp = head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newNode;
}
}

SHRUTI KATARIYA 42
23SE02IT030

// Function to delete from the beginning


void deleteFromBeginning() {
if (head == NULL) {
printf("List is empty.\n");
} else {
struct node* temp = head;
head = head->next;
free(temp);
}
}

// Function to delete from the end


void deleteFromEnd() {
if (head == NULL) {
printf("List is empty.\n");
} else if (head->next == NULL) {
free(head);
head = NULL;
} else {
struct node* temp = head;
while (temp->next->next != NULL) {
temp = temp->next;
}
free(temp->next);
temp->next = NULL;
}
}

// Function to display the list


void displayList() {
if (head == NULL) {
printf("List is empty.\n");
} else {
struct node* temp = head;
while (temp != NULL) {
printf("%d -> ", temp->data);
temp = temp->next;
}
printf("NULL\n");
}
}

int main() {
int choice, data;
while (1) {
printf("\nMenu:\n");
printf("1. Insert at beginning\n");
printf("2. Insert at end\n");

SHRUTI KATARIYA 43
23SE02IT030

printf("3. Delete from beginning\n");


printf("4. Delete from end\n");
printf("5. Display list\n");
printf("6. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Enter data to insert: ");
scanf("%d", &data);
insertAtBeginning(data);
break;
case 2:
printf("Enter data to insert: ");
scanf("%d", &data);
insertAtEnd(data);
break;
case 3:
deleteFromBeginning();
break;
case 4:
deleteFromEnd();
break;
case 5:
displayList();
break;
case 6:
exit(0);
default:
printf("Invalid choice. Please try again.\n");
}
}
return 0;
}
OUTPUT:

SHRUTI KATARIYA 44
23SE02IT030

SHRUTI KATARIYA 45
23SE02IT030

SHRUTI KATARIYA 46
23SE02IT030

RESULT:

Above program of singly linked list implementation is executed successfully.

SHRUTI KATARIYA 47
23SE02IT030

PRACTICAL NO: -14


AIM:
Write a program to perform the following operations in circular linked list – Creation,
Insertion, and Deletion.

ALGORITHM:

1. Creation of Circular Linked List

1. Initialize:

 Start with an empty list.


 Set head to NULL.

2. Create Nodes:

 For each element in the provided data list:

o Allocate memory for a new node.


o Set the node's data.
o If the list is empty, set head to this node and point its next to itself.
o Otherwise, traverse the list to find the last node, and update its
next to the new node. Set the new node's next to head.

2. Insertion in Circular Linked List

 Search for Target Node:


o Traverse the list starting from head to find the node containing the target
data.
o If found, create a new node with the new data.
o Update the next pointer of the new node to point to the target node's
next.
o Update the next pointer of the target node to point to the new node.
o If the target node is the last node in the list, ensure that the new node's
next is updated to head.

3. Deletion from Circular Linked List

 Search for Node to Delete:


o Traverse the list starting from head to find the node with the data to
delete.
o If the node to delete is the only node (head points to itself), set head to
NULL.

SHRUTI KATARIYA 48
23SE02IT030

o If the node to delete is the head, update the head to the next node and
update the last node's next to point to the new head.
o For any other node, update the next pointer of the previous node to skip
the node being deleted.

CODING:

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

// Define the node structure


struct node {
int data;
struct node* next;
};

struct node* last = NULL;

// Function to create a new node


struct node* createNode(int data) {
struct node* newNode = (struct node*)malloc(sizeof(struct node));
newNode->data = data;
newNode->next = NULL;
return newNode;
}

// Function to insert at the beginning


void insertAtBeginning(int data) {
struct node* newNode = createNode(data);
if (last == NULL) {
last = newNode;
last->next = last;
} else {
newNode->next = last->next;
last->next = newNode;
}
}

// Function to insert at the end


void insertAtEnd(int data) {
struct node* newNode = createNode(data);
if (last == NULL) {
last = newNode;
last->next = last;
} else {
newNode->next = last->next;
last->next = newNode;
last = newNode;

SHRUTI KATARIYA 49
23SE02IT030

}
}

// Function to delete from the beginning


void deleteFromBeginning() {
if (last == NULL) {
printf("List is empty.\n");
} else if (last->next == last) {
free(last);
last = NULL;
} else {
struct node* temp = last->next;
last->next = temp->next;
free(temp);
}
}

// Function to delete from the end


void deleteFromEnd() {
if (last == NULL) {
printf("List is empty.\n");
} else if (last->next == last) {
free(last);
last = NULL;
} else {
struct node* temp = last->next;
while (temp->next != last) {
temp = temp->next;
}
temp->next = last->next;
free(last);
last = temp;
}
}

// Function to display the list


void displayList() {
if (last == NULL) {
printf("List is empty.\n");
} else {
struct node* temp = last->next;
do {
printf("%d -> ", temp->data);
temp = temp->next;
} while (temp != last->next);
printf("HEAD\n");
}
}

SHRUTI KATARIYA 50
23SE02IT030

int main() {
int choice, data;
while (1) {
printf("\nMenu:\n");
printf("1. Insert at beginning\n");
printf("2. Insert at end\n");
printf("3. Delete from beginning\n");
printf("4. Delete from end\n");
printf("5. Display list\n");
printf("6. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Enter data to insert: ");
scanf("%d", &data);
insertAtBeginning(data);
break;
case 2:
printf("Enter data to insert: ");
scanf("%d", &data);
insertAtEnd(data);
break;
case 3:
deleteFromBeginning();
break;
case 4:
deleteFromEnd();
break;
case 5:
displayList();
break;
case 6:
exit(0);
default:
printf("Invalid choice. Please try again.\n");
}
}
return 0;
}

OUTPUT:

SHRUTI KATARIYA 51
23SE02IT030

SHRUTI KATARIYA 52
23SE02IT030

SHRUTI KATARIYA 53
23SE02IT030

RESULT:
Above program of Circular linekd list operation is executed successfully.

SHRUTI KATARIYA 54
23SE02IT030

PRACTICAL NO: -15


AIM:
Write a program to perform the following operations in doubly linked list – Creation, Insertion,
and Deletion.

ALGORITHM:

1. Creation of Doubly Linked List

 Initialize:
o Start with an empty list.
o Set head and tail to NULL.
 Create Nodes:
o For each element in the provided data list:
1. Allocate memory for a new node.
2. Set the node's data.
3. Update the next pointer of the previous node to point to the new
node.
4. Update the prev pointer of the new node to point to the previous
node.
5. Update the tail to point to the new node.
6. Ensure the next pointer of the new tail is NULL.

2. Insertion in Doubly Linked List

 Insertion at the Beginning:


o Allocate memory for a new node.
o Set the new node's next pointer to the current head.
o Set the prev pointer of the current head (if not NULL) to the new node.
o Update head to point to the new node.
o Set the prev pointer of the new node to NULL.
 Insertion at the End:
o Allocate memory for a new node.
o Set the new node's next pointer to NULL.
o Set the prev pointer of the new node to the current tail.
o Update the next pointer of the current tail (if not NULL) to the new node.
o Update tail to point to the new node.
 Insertion after a Given Node:
o Traverse the list to find the given node.
o Allocate memory for a new node.
o Update pointers to insert the new node after the given node.

SHRUTI KATARIYA 55
23SE02IT030

3. Deletion from Doubly Linked List

 Deletion at the Beginning:


o Update head to point to the next node.
o Update the prev pointer of the new head (if not NULL) to NULL.
o Free the memory of the old head node.
 Deletion at the End:
o Update tail to point to the previous node.
o Update the next pointer of the new tail (if not NULL) to NULL.
o Free the memory of the old tail node.
 Deletion of a Specific Node:
o Traverse the list to find the node to delete.
o Update the next pointer of the previous node.
o Update the prev pointer of the next node.
o Free the memory of the node to delete.

CODING:

#include <stdio.h>

#include <stdlib.h>

// Define the node structure

struct node {

int data;

struct node* prev;

struct node* next;

};

struct node* head = NULL;

// Function to create a new node

struct node* createNode(int data) {

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

SHRUTI KATARIYA 56
23SE02IT030

newNode->data = data;

newNode->prev = NULL;

newNode->next = NULL;

return newNode;

// Function to insert at the beginning

void insertAtBeginning(int data) {

struct node* newNode = createNode(data);

if (head == NULL) {

head = newNode;

} else {

newNode->next = head;

head->prev = newNode;

head = newNode;

// Function to insert at the end

void insertAtEnd(int data) {

struct node* newNode = createNode(data);

if (head == NULL) {

head = newNode;

} else {

SHRUTI KATARIYA 57
23SE02IT030

struct node* temp = head;

while (temp->next != NULL) {

temp = temp->next;

temp->next = newNode;

newNode->prev = temp;

// Function to delete from the beginning

void deleteFromBeginning() {

if (head == NULL) {

printf("List is empty.\n");

} else {

struct node* temp = head;

head = head->next;

if (head != NULL) {

head->prev = NULL;

free(temp);

// Function to delete from the end

SHRUTI KATARIYA 58
23SE02IT030

void deleteFromEnd() {

if (head == NULL) {

printf("List is empty.\n");

} else if (head->next == NULL) {

free(head);

head = NULL;

} else {

struct node* temp = head;

while (temp->next != NULL) {

temp = temp->next;

temp->prev->next = NULL;

free(temp);

// Function to display the list

void displayList() {

if (head == NULL) {

printf("List is empty.\n");

} else {

struct node* temp = head;

while (temp != NULL) {

printf("%d <-> ", temp->data);

SHRUTI KATARIYA 59
23SE02IT030

temp = temp->next;

printf("NULL\n");

int main() {

int choice, data;

while (1) {

printf("\nMenu:\n");

printf("1. Insert at beginning\n");

printf("2. Insert at end\n");

printf("3. Delete from beginning\n");

printf("4. Delete from end\n");

printf("5. Display list\n");

printf("6. Exit\n");

printf("Enter your choice: ");

scanf("%d", &choice);

switch (choice) {

case 1:

printf("Enter data to insert: ");

scanf("%d", &data);

insertAtBeginning(data);

break;

SHRUTI KATARIYA 60
23SE02IT030

case 2:

printf("Enter data to insert: ");

scanf("%d", &data);

insertAtEnd(data);

break;

case 3:

deleteFromBeginning();

break;

case 4:

deleteFromEnd();

break;

case 5:

displayList();

break;

case 6:

exit(0);

default:

printf("Invalid choice. Please try again.\n");

return 0;

OUTPUT:

SHRUTI KATARIYA 61
23SE02IT030

SHRUTI KATARIYA 62
23SE02IT030

SHRUTI KATARIYA 63
23SE02IT030

RESULT:

Above program of doubly linked list operation is executed successfully.

SHRUTI KATARIYA 64
23SE02IT030

PRACTICAL NO: -16


AIM:

Write programs to implement linked stack.

ALGORITHM:

1. Stack Operations Using Linked List

 Push Operation (Add Element to Stack):


o Step 1: Allocate memory for a new node.
o Step 2: Set the new node’s data to the value to be pushed.
o Step 3: Set the new node’s next pointer to the current top node.
o Step 4: Update the top pointer to point to the new node.
 Pop Operation (Remove Element from Stack):
o Step 1: Check if the stack is empty (i.e., top is NULL).
o Step 2: If the stack is not empty, store the current top node in a
temporary variable.
o Step 3: Update the top pointer to point to the next node of the current
top.
o Step 4: Free the memory of the old top node.
 Peek Operation (Get Top Element):
o Step 1: Check if the stack is empty.
o Step 2: If not empty, return the data of the top node.
 Display Operation (Print Stack Elements):
o Step 1: Initialize a pointer to traverse the stack from top.
o Step 2: Traverse the stack, printing the data of each node.
o Step 3: Continue until the end of the stack is reached (i.e., pointer is
NULL).

CODING:

#include <stdio.h>

#include <stdlib.h>

// Define the node structure

struct node {

int data;

SHRUTI KATARIYA 65
23SE02IT030

struct node* next;

};

struct node* top = NULL;

// Function to create a new node

struct node* createNode(int data) {

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

newNode->data = data;

newNode->next = NULL;

return newNode;

// Function to push an element onto the stack

void push(int data) {

struct node* newNode = createNode(data);

if (top == NULL) {

top = newNode;

} else {

newNode->next = top;

top = newNode;

printf("%d pushed to stack\n", data);

SHRUTI KATARIYA 66
23SE02IT030

// Function to pop an element from the stack

void pop() {

if (top == NULL) {

printf("Stack is empty.\n");

} else {

struct node* temp = top;

top = top->next;

printf("%d popped from stack\n", temp->data);

free(temp);

// Function to display the stack

void display() {

if (top == NULL) {

printf("Stack is empty.\n");

} else {

struct node* temp = top;

while (temp != NULL) {

printf("%d -> ", temp->data);

temp = temp->next;

printf("NULL\n");

SHRUTI KATARIYA 67
23SE02IT030

int main() {

int choice, data;

while (1) {

printf("\nMenu:\n");

printf("1. Push\n");

printf("2. Pop\n");

printf("3. Display\n");

printf("4. Exit\n");

printf("Enter your choice: ");

scanf("%d", &choice);

switch (choice) {

case 1:

printf("Enter data to push: ");

scanf("%d", &data);

push(data);

break;

case 2:

pop();

break;

case 3:

display();

SHRUTI KATARIYA 68
23SE02IT030

break;

case 4:

exit(0);

default:

printf("Invalid choice. Please try again.\n");

return 0;

OUTPUT:

SHRUTI KATARIYA 69
23SE02IT030

SHRUTI KATARIYA 70
23SE02IT030

RESULT:

Above program is executed successfully.

SHRUTI KATARIYA 71
23SE02IT030

PRACTICAL NO: -17


AIM:

Write programs to implement linked queue.

ALGORITHM:

1. Initialize the Queue:

 Create a structure for the queue node.


 Define pointers for the front and rear of the queue.

2. Enqueue (Add Element to the Rear):

 Create a new node.


 Set the new node's data and make its next pointer NULL.
 If the queue is empty, set both the front and rear pointers to the new node.
 Otherwise, link the current rear node to the new node and update the rear
pointer.

3. Dequeue (Remove Element from the Front):

 Check if the queue is empty.


 Store the data of the front node.
 Move the front pointer to the next node.
 Free the memory of the old front node.
 If the queue becomes empty after this operation, set the rear pointer to NULL.

4. Display the Queue:

 Start from the front pointer and traverse through the nodes, printing their data

CODING:

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

// Node structure
struct Node {
int data;
struct Node* next;
};

// Queue structure

SHRUTI KATARIYA 72
23SE02IT030

struct Queue {
struct Node *front, *rear;
};

// Function to create a new node


struct Node* newNode(int k) {
struct Node* temp = (struct Node*)malloc(sizeof(struct Node));
temp->data = k;
temp->next = NULL;
return temp;
}

// Function to create a queue


struct Queue* createQueue() {
struct Queue* q = (struct Queue*)malloc(sizeof(struct Queue));
q->front = q->rear = NULL;
return q;
}

// Function to add an element to the queue


void enqueue(struct Queue* q, int k) {
struct Node* temp = newNode(k);

if (q->rear == NULL) {
q->front = q->rear = temp;
return;
}

q->rear->next = temp;
q->rear = temp;
}

// Function to remove an element from the queue


void dequeue(struct Queue* q) {
if (q->front == NULL) {
printf("Queue Underflow\n");
return;
}

struct Node* temp = q->front;


q->front = q->front->next;

if (q->front == NULL)
q->rear = NULL;

free(temp);
}

SHRUTI KATARIYA 73
23SE02IT030

// Function to display the queue


void display(struct Queue* q) {
struct Node* temp = q->front;
if (temp == NULL) {
printf("Queue is empty\n");
return;
}
while (temp != NULL) {
printf("%d -> ", temp->data);
temp = temp->next;
}
printf("NULL\n");
}

int main() {
struct Queue* q = createQueue();
int choice, value;

while (1) {
printf("\n1. Enqueue\n2. Dequeue\n3. Display\n4. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);

switch (choice) {
case 1:
printf("Enter the value to be inserted: ");
scanf("%d", &value);
enqueue(q, value);
break;
case 2:
dequeue(q);
break;
case 3:
display(q);
break;
case 4:
exit(0);
default:
printf("Invalid choice\n");
}
}

return 0;
}
OUTPUT:

SHRUTI KATARIYA 74
23SE02IT030

SHRUTI KATARIYA 75
23SE02IT030

RESULT:

Above program of linked queue is executed successfully.

SHRUTI KATARIYA 76
23SE02IT030

PRACTICAL NO: -18

AIM:
Write a program to create a binary search tree and perform – Insertion, Deletion, and
Traversal.

ALGORITHM:

1. Insertion:

 Start at the root node.


 Compare the value to be inserted with the current node's value.
 If the value is less, move to the left child; if greater, move to the right
child.
 Repeat until you find an empty spot where the new node can be inserted.

2. Deletion:

 Find the node to be deleted.


 If the node is a leaf (has no children), simply remove it.
 If the node has one child, replace it with its child.
 If the node has two children, find the in-order successor (smallest value
in the right subtree), copy its value to the node to be deleted, and then
delete the in-order successor.

3. Traversal:

 In-order Traversal: Visit the left subtree, then the current node, then
the right subtree.
 Pre-order Traversal: Visit the current node, then the left subtree, then
the right subtree.
 Post-order Traversal: Visit the left subtree, then the right subtree, then
the current node

CODING:

#include <stdio.h>

#include <stdlib.h>

SHRUTI KATARIYA 77
23SE02IT030

// Definition of a tree node

typedef struct TreeNode {

int data;

struct TreeNode* left;

struct TreeNode* right;

} TreeNode;

// Function to create a new tree node

TreeNode* createNode(int data) {

TreeNode* newNode = (TreeNode*)malloc(sizeof(TreeNode));

newNode->data = data;

newNode->left = newNode->right = NULL;

return newNode;

// Function to insert a new node into the BST

TreeNode* insert(TreeNode* root, int data) {

if (root == NULL) {

return createNode(data);

if (data < root->data) {

root->left = insert(root->left, data);

} else {

root->right = insert(root->right, data);

SHRUTI KATARIYA 78
23SE02IT030

return root;

// Function to find the minimum value node in the subtree

TreeNode* findMin(TreeNode* root) {

while (root->left != NULL) {

root = root->left;

return root;

// Function to delete a node from the BST

TreeNode* deleteNode(TreeNode* root, int data) {

if (root == NULL) {

return root;

if (data < root->data) {

root->left = deleteNode(root->left, data);

} else if (data > root->data) {

root->right = deleteNode(root->right, data);

} else {

if (root->left == NULL) {

TreeNode* temp = root->right;

SHRUTI KATARIYA 79
23SE02IT030

free(root);

return temp;

} else if (root->right == NULL) {

TreeNode* temp = root->left;

free(root);

return temp;

TreeNode* temp = findMin(root->right);

root->data = temp->data;

root->right = deleteNode(root->right, temp->data);

return root;

// Function to perform in-order traversal of the BST

void inorderTraversal(TreeNode* root) {

if (root != NULL) {

inorderTraversal(root->left);

printf("%d ", root->data);

inorderTraversal(root->right);

int main() {

SHRUTI KATARIYA 80
23SE02IT030

TreeNode* root = NULL;

int choice, data;

while (1) {

printf("\nBinary Search Tree Operations\n");

printf("1. Insert\n");

printf("2. Delete\n");

printf("3. In-order Traversal\n");

printf("4. Exit\n");

printf("Enter your choice: ");

scanf("%d", &choice);

switch (choice) {

case 1:

printf("Enter value to insert: ");

scanf("%d", &data);

root = insert(root, data);

printf("Inserted %d into the BST\n", data);

break;

case 2:

printf("Enter value to delete: ");

scanf("%d", &data);

root = deleteNode(root, data);

printf("Deleted %d from the BST\n", data);

SHRUTI KATARIYA 81
23SE02IT030

break;

case 3:

printf("In-order Traversal: ");

inorderTraversal(root);

printf("\n");

break;

case 4:

printf("Exiting...\n");

exit(0);

default:

printf("Invalid choice. Please try again.\n");

return 0;

OUTPUT:

SHRUTI KATARIYA 82
23SE02IT030

SHRUTI KATARIYA 83
23SE02IT030

RESULT:

Above program of Binary Search Tree (BST) is executed successfully.

SHRUTI KATARIYA 84
23SE02IT030

PRACTICAL NO: -19


AIM:
Write a program to perform the following operations in binary tree – Creation, Insertion and
Deletion.

ALGORITHM:

1. Creation:

 Define a Node structure with data, left, and right pointers.


 Initialize the binary tree with a NULL root.

2. Insertion:

 To insert a node, traverse the tree to find the correct location (based on binary search
tree properties if it's a binary search tree).
 Insert the node in the appropriate position (left or right of the current node).

3. Deletion:

 To delete a node, find the node to be deleted.


 Handle three cases:
o Node has no children: Simply remove the node.
o Node has one child: Replace the node with its child.
o Node has two children: Find the in-order successor (smallest value in the
right subtree) or in-order predecessor (largest value in the left subtree) and
replace the node with it. Then, delete the successor/predecessor node.

CODING:

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

// Define the structure for a tree node


struct Node {
int data;
struct Node* left;
struct Node* right;
};

SHRUTI KATARIYA 85
23SE02IT030

// Function to create a new node


struct Node* createNode(int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}

// Function to insert a node in the binary tree


struct Node* insertNode(struct Node* root, int data) {
if (root == NULL) {
return createNode(data);
}
if (data < root->data) {
root->left = insertNode(root->left, data);
} else if (data > root->data) {
root->right = insertNode(root->right, data);
}
return root;
}

// Function to find the minimum value node in the tree


struct Node* findMin(struct Node* root) {
while (root->left != NULL) {
root = root->left;
}
return root;
}

// Function to delete a node from the binary tree


struct Node* deleteNode(struct Node* root, int data) {
if (root == NULL) {
return root;
}
if (data < root->data) {
root->left = deleteNode(root->left, data);
} else if (data > root->data) {
root->right = deleteNode(root->right, data);
} else {
// Node with only one child or no child
if (root->left == NULL) {
struct Node* temp = root->right;
free(root);
return temp;
} else if (root->right == NULL) {
struct Node* temp = root->left;

SHRUTI KATARIYA 86
23SE02IT030

free(root);
return temp;
}
// Node with two children: Get the inorder successor (smallest in the right
subtree)
struct Node* temp = findMin(root->right);
root->data = temp->data;
root->right = deleteNode(root->right, temp->data);
}
return root;
}

// Function to perform inorder traversal of the tree


void inorderTraversal(struct Node* root) {
if (root != NULL) {
inorderTraversal(root->left);
printf("%d ", root->data);
inorderTraversal(root->right);
}
}

int main() {
struct Node* root = NULL;
int choice, data;

while (1) {
printf("\n1. Insert\n2. Delete\n3. Inorder Traversal\n4. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);

switch (choice) {
case 1:
printf("Enter data to insert: ");
scanf("%d", &data);
root = insertNode(root, data);
break;
case 2:
printf("Enter data to delete: ");
scanf("%d", &data);
root = deleteNode(root, data);
break;
case 3:
printf("Inorder Traversal: ");
inorderTraversal(root);
printf("\n");
break;
case 4:
exit(0);

SHRUTI KATARIYA 87
23SE02IT030

default:
printf("Invalid choice!\n");
}
}

return 0;
}
OUTPUT:

SHRUTI KATARIYA 88
23SE02IT030

RESULT:

Above program of binary tree opration is executed successfully.

SHRUTI KATARIYA 89

You might also like