0% found this document useful (0 votes)
0 views52 pages

Data Structure using C 'lab' Practical File

The document outlines several practical programming tasks in C, focusing on array and linked list operations. It includes menu-driven programs for creating, displaying, inserting, deleting, and manipulating arrays and matrices, as well as recursive functions for mathematical operations. Each practical task is supported by appropriate functions and includes user interaction through a menu system.

Uploaded by

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

Data Structure using C 'lab' Practical File

The document outlines several practical programming tasks in C, focusing on array and linked list operations. It includes menu-driven programs for creating, displaying, inserting, deleting, and manipulating arrays and matrices, as well as recursive functions for mathematical operations. Each practical task is supported by appropriate functions and includes user interaction through a menu system.

Uploaded by

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

Practical No.

1
Design, develop and Implement a menu driven program in C for the following Array
operations
a) Creating an Array of N Integer Elements
b) Display of Array Elements with Suitable Headings
c) Inserting an Elements (ELEM) at a given valid Position (POS)
d) Deleting an Elements at a given valid Position (POS)
e) Exit.
Support the program with functions for each of the above operations.

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

#define MAX 100

int arr[MAX];
int n = 0;

void createArray() {
printf("Enter number of elements (max %d): ", MAX);
scanf("%d", &n);

if(n > MAX || n <= 0) {


printf("Invalid size. Try again.\n");
return;
}

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


for(int i = 0; i < n; i++) {
printf("Element %d: ", i + 1);
scanf("%d", &arr[i]);
}
}

void displayArray() {
if(n == 0) {
printf("Array is empty.\n");
return;
}

printf("Array Elements:\n");
printf("Position\tElement\n");
for(int i = 0; i < n; i++) {
printf("%d\t\t%d\n", i + 1, arr[i]);
}
}

void insertElement() {
if(n == MAX) {
printf("Array is full. Cannot insert more elements.\n");
return;
}

int pos, elem;


printf("Enter the position to insert (1 to %d): ", n + 1);
scanf("%d", &pos);

if(pos < 1 || pos > n + 1) {


printf("Invalid position!\n");
return;
}

printf("Enter the element to insert: ");


scanf("%d", &elem);

for(int i = n; i >= pos; i--) {


arr[i] = arr[i - 1];
}
arr[pos - 1] = elem;
n++;

printf("Element inserted successfully.\n");


}

void deleteElement() {
if(n == 0) {
printf("Array is empty. Nothing to delete.\n");
return;
}

int pos;
printf("Enter the position to delete (1 to %d): ", n);
scanf("%d", &pos);

if(pos < 1 || pos > n) {


printf("Invalid position!\n");
return;
}

int deleted = arr[pos - 1];


for(int i = pos - 1; i < n - 1; i++) {
arr[i] = arr[i + 1];
}
n--;

printf("Deleted element: %d\n", deleted);


}

int main() {
int choice;

do {
printf("\n=== Array Operations Menu ===\n");
printf("1. Create Array\n");
printf("2. Display Array\n");
printf("3. Insert Element\n");
printf("4. Delete Element\n");
printf("5. Exit\n");
printf("Enter your choice (1-5): ");
scanf("%d", &choice);

switch(choice) {
case 1: createArray(); break;
case 2: displayArray(); break;
case 3: insertElement(); break;
case 4: deleteElement(); break;
case 5: printf("Exiting program. Goodbye!\n"); break;
default: printf("Invalid choice. Try again.\n");
}
} while(choice != 5);

return 0;
}
Practical No. 2

Design, develop and Implement a menu driven program in C for the following Array
operations
a) Creating an Array of N Integer Elements
b) Reverse the elements of array
c) Find maximum and minimum of array
d) Find even and odd elements of array
e) Find sum of elements of an array
f) Exit.
Support the program with functions for each of the above operations

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

#define MAX 100

int arr[MAX];
int n = 0;

void createArray() {
printf("Enter the number of elements (max %d): ", MAX);
scanf("%d", &n);

if (n <= 0 || n > MAX) {


printf("Invalid size. Try again.\n");
return;
}

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


for (int i = 0; i < n; i++) {
printf("Element %d: ", i + 1);
scanf("%d", &arr[i]);
}
}

void reverseArray() {
if (n == 0) {
printf("Array is empty.\n");
return;
}

printf("Reversed Array:\n");
for (int i = n - 1; i >= 0; i--) {
printf("%d ", arr[i]);
}
printf("\n");
}
void findMaxMin() {
if (n == 0) {
printf("Array is empty.\n");
return;
}

int max = arr[0], min = arr[0];


for (int i = 1; i < n; i++) {
if (arr[i] > max)
max = arr[i];
if (arr[i] < min)
min = arr[i];
}

printf("Maximum element: %d\n", max);


printf("Minimum element: %d\n", min);
}

void findEvenOdd() {
if (n == 0) {
printf("Array is empty.\n");
return;
}

printf("Even elements: ");


for (int i = 0; i < n; i++) {
if (arr[i] % 2 == 0)
printf("%d ", arr[i]);
}

printf("\nOdd elements: ");


for (int i = 0; i < n; i++) {
if (arr[i] % 2 != 0)
printf("%d ", arr[i]);
}

printf("\n");
}

void findSum() {
if (n == 0) {
printf("Array is empty.\n");
return;
}

int sum = 0;
for (int i = 0; i < n; i++) {
sum += arr[i];
}
printf("Sum of elements: %d\n", sum);
}

int main() {
int choice;

do {
printf("\n=== Array Operations Menu ===\n");
printf("1. Create Array\n");
printf("2. Reverse Array\n");
printf("3. Find Max and Min\n");
printf("4. Find Even and Odd Elements\n");
printf("5. Find Sum of Elements\n");
printf("6. Exit\n");
printf("Enter your choice (1-6): ");
scanf("%d", &choice);

switch (choice) {
case 1: createArray(); break;
case 2: reverseArray(); break;
case 3: findMaxMin(); break;
case 4: findEvenOdd(); break;
case 5: findSum(); break;
case 6: printf("Exiting program.\n"); break;
default: printf("Invalid choice. Try again.\n");
}
} while (choice != 6);

return 0;
}
Practical No. 3
Design, develop and Implement a menu driven program in C for the following Array
operations on two-dimensional array of Integers
a) Find addition of two matrix
b) Find transpose of a matrix
c) Find multiplication of two matrix
d) Find addition of two matrix
e) Determine given matrix is sparse or not.
f) Exit.
Support the program with appropriate functions for each of the above operations.

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

#define MAX 10

int matrix1[MAX][MAX], matrix2[MAX][MAX], result[MAX][MAX];


int r1, c1, r2, c2;

void inputMatrix(int matrix[MAX][MAX], int rows, int cols, char name) {


printf("Enter elements of Matrix %c (%dx%d):\n", name, rows, cols);
for(int i = 0; i < rows; i++) {
for(int j = 0; j < cols; j++) {
printf("%c[%d][%d]: ", name, i + 1, j + 1);
scanf("%d", &matrix[i][j]);
}
}
}

void printMatrix(int matrix[MAX][MAX], int rows, int cols) {


for(int i = 0; i < rows; i++) {
for(int j = 0; j < cols; j++) {
printf("%d\t", matrix[i][j]);
}
printf("\n");
}
}

void addMatrices() {
if (r1 != r2 || c1 != c2) {
printf("Matrix addition not possible. Dimensions must match.\n");
return;
}

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


for(int j = 0; j < c1; j++) {
result[i][j] = matrix1[i][j] + matrix2[i][j];
}
}
printf("Resultant Matrix after Addition:\n");
printMatrix(result, r1, c1);
}

void transposeMatrix() {
int transpose[MAX][MAX];

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


for(int j = 0; j < c1; j++) {
transpose[j][i] = matrix1[i][j];
}
}

printf("Transpose of Matrix 1:\n");


printMatrix(transpose, c1, r1);
}

void multiplyMatrices() {
if (c1 != r2) {
printf("Matrix multiplication not possible. Columns of Matrix 1 must match rows of
Matrix 2.\n");
return;
}

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


for(int j = 0; j < c2; j++) {
result[i][j] = 0;
for(int k = 0; k < c1; k++) {
result[i][j] += matrix1[i][k] * matrix2[k][j];
}
}
}

printf("Resultant Matrix after Multiplication:\n");


printMatrix(result, r1, c2);
}

void checkSparse() {
int zeroCount = 0, total = r1 * c1;

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


for(int j = 0; j < c1; j++) {
if(matrix1[i][j] == 0) {
zeroCount++;
}
}
}

if(zeroCount > (total / 2)) {


printf("Matrix 1 is a Sparse Matrix.\n");
} else {
printf("Matrix 1 is NOT a Sparse Matrix.\n");
}
}

int main() {
int choice;

printf("Enter rows and columns for Matrix 1: ");


scanf("%d%d", &r1, &c1);
inputMatrix(matrix1, r1, c1, 'A');

printf("Enter rows and columns for Matrix 2: ");


scanf("%d%d", &r2, &c2);
inputMatrix(matrix2, r2, c2, 'B');

do {
printf("\n=== Matrix Operations Menu ===\n");
printf("1. Addition of Matrices\n");
printf("2. Transpose of Matrix A\n");
printf("3. Multiplication of Matrices\n");
printf("4. Addition of Matrices (Duplicate Option)\n");
printf("5. Check if Matrix A is Sparse\n");
printf("6. Exit\n");
printf("Enter your choice (1-6): ");
scanf("%d", &choice);

switch(choice) {
case 1:
case 4: addMatrices(); break;
case 2: transposeMatrix(); break;
case 3: multiplyMatrices(); break;
case 5: checkSparse(); break;
case 6: printf("Exiting program.\n"); break;
default: printf("Invalid choice. Try again.\n");
}
} while(choice != 6);

return 0;
}
Practical No. 4
Design, develop and Implement a menu driven program in C for the following Array
operations on RECURSION
a) Find factorial of an element
b) Find Fibonacci series
c) Find power of a number
d) Find sum of all digits
e) Exit
Support the program with appropriate functions for each of the above operations.

#include <stdio.h>

// a) Recursive function to find factorial


int factorial(int n) {
if (n == 0 || n == 1)
return 1;
else
return n * factorial(n - 1);
}

// b) Recursive function to find nth Fibonacci number


int fibonacci(int n) {
if (n == 0) return 0;
else if (n == 1) return 1;
else return fibonacci(n - 1) + fibonacci(n - 2);
}

// c) Recursive function to find power (base^exp)


int power(int base, int exp) {
if (exp == 0)
return 1;
else
return base * power(base, exp - 1);
}

// d) Recursive function to find sum of digits


int sumOfDigits(int n) {
if (n == 0)
return 0;
else
return (n % 10) + sumOfDigits(n / 10);
}

// Main menu-driven program


int main() {
int choice, n, result, base, exp;

do {
printf("\n====== Recursive Operations Menu ======\n");
printf("1. Find Factorial\n");
printf("2. Find Fibonacci Series\n");
printf("3. Find Power (base^exp)\n");
printf("4. Find Sum of Digits\n");
printf("5. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);

switch (choice) {
case 1:
printf("Enter number to find factorial: ");
scanf("%d", &n);
if (n < 0)
printf("Factorial is not defined for negative numbers.\n");
else
printf("Factorial of %d is %d\n", n, factorial(n));
break;

case 2:
printf("Enter number of terms for Fibonacci series: ");
scanf("%d", &n);
if (n <= 0)
printf("Please enter a positive number.\n");
else {
printf("Fibonacci series: ");
for (int i = 0; i < n; i++) {
printf("%d ", fibonacci(i));
}
printf("\n");
}
break;

case 3:
printf("Enter base and exponent: ");
scanf("%d%d", &base, &exp);
if (exp < 0)
printf("Only non-negative exponents are supported.\n");
else
printf("%d^%d = %d\n", base, exp, power(base, exp));
break;

case 4:
printf("Enter number to find sum of digits: ");
scanf("%d", &n);
if (n < 0) n = -n;
printf("Sum of digits: %d\n", sumOfDigits(n));
break;

case 5:
printf("Exiting program. Goodbye!\n");
break;

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

} while (choice != 5);

return 0;
}
Practical No.5.
Design, develop and Implement a menu driven program in C for the following operations on
Singly Linked List (SLL).
a) Create a Singly Linked Lists N Node.
b) Display the status of SLL and count the number of nodes in it
c) Perform Insertion and Deletion at End of SLL
d) Perform Insertion and Deletion at Front of SLL
e) Perform Insertion and Deletion at given position of SLL
f) Reverse the elements of SLL
g) Exit

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

// Define node structure


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

struct Node* head = NULL;

// a) Create list with N nodes


void createList(int n) {
struct Node *newNode, *temp;
int data;

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


newNode = (struct Node*)malloc(sizeof(struct Node));
if (!newNode) {
printf("Memory allocation failed.\n");
return;
}

printf("Enter data for node %d: ", i + 1);


scanf("%d", &data);
newNode->data = data;
newNode->next = NULL;

if (head == NULL) {
head = newNode;
} else {
temp = head;
while (temp->next != NULL)
temp = temp->next;
temp->next = newNode;
}
}
}
// b) Display list and count nodes
void displayList() {
struct Node* temp = head;
int count = 0;

if (head == NULL) {
printf("List is empty.\n");
return;
}

printf("Linked List Elements: ");


while (temp != NULL) {
printf("%d -> ", temp->data);
temp = temp->next;
count++;
}
printf("NULL\nTotal nodes: %d\n", count);
}

// c) Insertion at end
void insertAtEnd(int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
struct Node* temp = head;

if (!newNode) {
printf("Memory allocation failed.\n");
return;
}

newNode->data = data;
newNode->next = NULL;

if (head == NULL)
head = newNode;
else {
while (temp->next != NULL)
temp = temp->next;
temp->next = newNode;
}
}

// c) Deletion at end
void deleteAtEnd() {
struct Node *temp = head, *prev = NULL;

if (head == NULL) {
printf("List is empty.\n");
return;
}
if (head->next == NULL) {
free(head);
head = NULL;
} else {
while (temp->next != NULL) {
prev = temp;
temp = temp->next;
}
prev->next = NULL;
free(temp);
}
}

// d) Insertion at front
void insertAtFront(int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));

if (!newNode) {
printf("Memory allocation failed.\n");
return;
}

newNode->data = data;
newNode->next = head;
head = newNode;
}

// d) Deletion at front
void deleteAtFront() {
struct Node* temp = head;

if (head == NULL) {
printf("List is empty.\n");
return;
}

head = head->next;
free(temp);
}

// e) Insertion at given position


void insertAtPosition(int pos, int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
struct Node* temp = head;

if (pos < 1) {
printf("Invalid position.\n");
return;
}
if (!newNode) {
printf("Memory allocation failed.\n");
return;
}

newNode->data = data;

if (pos == 1) {
newNode->next = head;
head = newNode;
return;
}

for (int i = 1; i < pos - 1 && temp != NULL; i++)


temp = temp->next;

if (temp == NULL) {
printf("Position out of range.\n");
free(newNode);
} else {
newNode->next = temp->next;
temp->next = newNode;
}
}

// e) Deletion at given position


void deleteAtPosition(int pos) {
struct Node *temp = head, *prev = NULL;

if (pos < 1 || head == NULL) {


printf("Invalid position or empty list.\n");
return;
}

if (pos == 1) {
head = head->next;
free(temp);
return;
}

for (int i = 1; i < pos && temp != NULL; i++) {


prev = temp;
temp = temp->next;
}

if (temp == NULL) {
printf("Position out of range.\n");
} else {
prev->next = temp->next;
free(temp);
}
}

// f) Reverse the list


void reverseList() {
struct Node *prev = NULL, *curr = head, *next = NULL;

while (curr != NULL) {


next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}

head = prev;
printf("List has been reversed.\n");
}

// Main program
int main() {
int choice, data, pos, n;

do {
printf("\n==== Singly Linked List Menu ====\n");
printf("1. Create List with N Nodes\n");
printf("2. Display and Count Nodes\n");
printf("3. Insert/Delete at End\n");
printf("4. Insert/Delete at Front\n");
printf("5. Insert/Delete at Position\n");
printf("6. Reverse List\n");
printf("7. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);

switch(choice) {
case 1:
printf("Enter number of nodes: ");
scanf("%d", &n);
createList(n);
break;

case 2:
displayList();
break;

case 3:
printf("1. Insert at End\n2. Delete at End\nChoice: ");
scanf("%d", &n);
if (n == 1) {
printf("Enter data: ");
scanf("%d", &data);
insertAtEnd(data);
} else {
deleteAtEnd();
}
break;

case 4:
printf("1. Insert at Front\n2. Delete at Front\nChoice: ");
scanf("%d", &n);
if (n == 1) {
printf("Enter data: ");
scanf("%d", &data);
insertAtFront(data);
} else {
deleteAtFront();
}
break;

case 5:
printf("1. Insert at Position\n2. Delete at Position\nChoice: ");
scanf("%d", &n);
if (n == 1) {
printf("Enter position and data: ");
scanf("%d %d", &pos, &data);
insertAtPosition(pos, data);
} else {
printf("Enter position to delete: ");
scanf("%d", &pos);
deleteAtPosition(pos);
}
break;

case 6:
reverseList();
break;

case 7:
printf("Exiting program.\n");
break;

default:
printf("Invalid choice. Try again.\n");
}

} while (choice != 7);

return 0;
}
Practical No.6
Design, develop and Implement a menu driven program in C for the following operations on
Doubly Linked List (DLL).
a) Create a Doubly Linked Lists N Node.
b) Display the status of DLL and count the number of nodes in it
c) Perform Insertion and Deletion at End of DLL
d) Perform Insertion and Deletion at Front of DLL
e) Perform Insertion and Deletion at given position DLL
f) Exit

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

// Node structure for DLL


struct Node {
int data;
struct Node* prev;
struct Node* next;
};

struct Node* head = NULL;

// a) Create DLL with N nodes


void createDLL(int n) {
struct Node *newNode, *temp;
int data;

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


newNode = (struct Node*)malloc(sizeof(struct Node));
if (!newNode) {
printf("Memory allocation failed.\n");
return;
}

printf("Enter data for node %d: ", i + 1);


scanf("%d", &data);

newNode->data = data;
newNode->prev = newNode->next = NULL;

if (head == NULL) {
head = newNode;
} else {
temp = head;
while (temp->next != NULL)
temp = temp->next;

temp->next = newNode;
newNode->prev = temp;
}
}
}

// b) Display DLL and count nodes


void displayDLL() {
struct Node* temp = head;
int count = 0;

if (head == NULL) {
printf("DLL is empty.\n");
return;
}

printf("Doubly Linked List: ");


while (temp != NULL) {
printf("%d <-> ", temp->data);
temp = temp->next;
count++;
}
printf("NULL\nTotal nodes: %d\n", count);
}

// c) Insert at end
void insertAtEnd(int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
struct Node* temp = head;

if (!newNode) {
printf("Memory allocation failed.\n");
return;
}

newNode->data = data;
newNode->next = newNode->prev = NULL;

if (head == NULL) {
head = newNode;
} else {
while (temp->next != NULL)
temp = temp->next;

temp->next = newNode;
newNode->prev = temp;
}
}

// c) Delete at end
void deleteAtEnd() {
struct Node* temp = head;
if (head == NULL) {
printf("DLL is empty.\n");
return;
}

if (head->next == NULL) {
free(head);
head = NULL;
} else {
while (temp->next != NULL)
temp = temp->next;

temp->prev->next = NULL;
free(temp);
}
}

// d) Insert at front
void insertAtFront(int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));

if (!newNode) {
printf("Memory allocation failed.\n");
return;
}

newNode->data = data;
newNode->prev = NULL;
newNode->next = head;

if (head != NULL)
head->prev = newNode;

head = newNode;
}

// d) Delete at front
void deleteAtFront() {
struct Node* temp = head;

if (head == NULL) {
printf("DLL is empty.\n");
return;
}

head = head->next;
if (head != NULL)
head->prev = NULL;

free(temp);
}

// e) Insert at given position


void insertAtPosition(int pos, int data) {
struct Node *newNode, *temp = head;

if (pos < 1) {
printf("Invalid position.\n");
return;
}

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


if (!newNode) {
printf("Memory allocation failed.\n");
return;
}

newNode->data = data;
newNode->prev = newNode->next = NULL;

if (pos == 1) {
insertAtFront(data);
return;
}

for (int i = 1; i < pos - 1 && temp != NULL; i++)


temp = temp->next;

if (temp == NULL) {
printf("Position out of range.\n");
free(newNode);
} else {
newNode->next = temp->next;
newNode->prev = temp;

if (temp->next != NULL)
temp->next->prev = newNode;

temp->next = newNode;
}
}

// e) Delete at given position


void deleteAtPosition(int pos) {
struct Node* temp = head;

if (pos < 1 || head == NULL) {


printf("Invalid position or list is empty.\n");
return;
}
if (pos == 1) {
deleteAtFront();
return;
}

for (int i = 1; i < pos && temp != NULL; i++)


temp = temp->next;

if (temp == NULL) {
printf("Position out of range.\n");
} else {
if (temp->prev != NULL)
temp->prev->next = temp->next;
if (temp->next != NULL)
temp->next->prev = temp->prev;
free(temp);
}
}

// Main Menu
int main() {
int choice, data, pos, n;

do {
printf("\n=== Doubly Linked List Menu ===\n");
printf("1. Create DLL with N Nodes\n");
printf("2. Display and Count Nodes\n");
printf("3. Insert/Delete at End\n");
printf("4. Insert/Delete at Front\n");
printf("5. Insert/Delete at Given Position\n");
printf("6. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);

switch(choice) {
case 1:
printf("Enter number of nodes: ");
scanf("%d", &n);
createDLL(n);
break;

case 2:
displayDLL();
break;

case 3:
printf("1. Insert at End\n2. Delete at End\nChoice: ");
scanf("%d", &n);
if (n == 1) {
printf("Enter data to insert: ");
scanf("%d", &data);
insertAtEnd(data);
} else {
deleteAtEnd();
}
break;

case 4:
printf("1. Insert at Front\n2. Delete at Front\nChoice: ");
scanf("%d", &n);
if (n == 1) {
printf("Enter data to insert: ");
scanf("%d", &data);
insertAtFront(data);
} else {
deleteAtFront();
}
break;

case 5:
printf("1. Insert at Position\n2. Delete at Position\nChoice: ");
scanf("%d", &n);
if (n == 1) {
printf("Enter position and data: ");
scanf("%d %d", &pos, &data);
insertAtPosition(pos, data);
} else {
printf("Enter position to delete: ");
scanf("%d", &pos);
deleteAtPosition(pos);
}
break;

case 6:
printf("Exiting program.\n");
break;

default:
printf("Invalid choice. Try again.\n");
}

} while (choice != 6);

return 0;
}
Practical No.7
Design, develop and Implement a menu driven program in C for the following operations on
Circular Linked List (CLL).
a) Create a Circular Linked Lists N Node.
b) Display the Circular Linked List.
c) Perform Insertion and Deletion at End of CLL
d) Perform Insertion and Deletion at Front of CLL
e) Exit

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

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

// Global head pointer


struct Node* head = NULL;

// Function to create N nodes in the circular linked list


void createCLL(int n) {
if (n <= 0) {
printf("Number of nodes must be greater than 0.\n");
return;
}

struct Node *newNode, *temp;


int data, i;

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


printf("Enter data for node %d: ", i + 1);
scanf("%d", &data);
newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = NULL;

if (head == NULL) {
head = newNode;
head->next = head; // Point to itself
} else {
temp = head;
while (temp->next != head)
temp = temp->next;
temp->next = newNode;
newNode->next = head;
}
}
}
// Function to display the CLL
void displayCLL() {
if (head == NULL) {
printf("List is empty.\n");
return;
}

struct Node* temp = head;


printf("Circular Linked List: ");
do {
printf("%d -> ", temp->data);
temp = temp->next;
} while (temp != head);
printf("(head)\n");
}

// Insert at end
void insertEnd(int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;

if (head == NULL) {
head = newNode;
newNode->next = head;
} else {
struct Node* temp = head;
while (temp->next != head)
temp = temp->next;
temp->next = newNode;
newNode->next = head;
}
}

// Delete at end
void deleteEnd() {
if (head == NULL) {
printf("List is empty.\n");
return;
}

struct Node *temp = head, *prev = NULL;

// Only one node


if (head->next == head) {
free(head);
head = NULL;
return;
}
while (temp->next != head) {
prev = temp;
temp = temp->next;
}

prev->next = head;
free(temp);
}

// Insert at front
void insertFront(int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;

if (head == NULL) {
head = newNode;
newNode->next = head;
} else {
struct Node* temp = head;
while (temp->next != head)
temp = temp->next;
temp->next = newNode;
newNode->next = head;
head = newNode;
}
}

// Delete at front
void deleteFront() {
if (head == NULL) {
printf("List is empty.\n");
return;
}

// Only one node


if (head->next == head) {
free(head);
head = NULL;
return;
}

struct Node* temp = head;


struct Node* last = head;

while (last->next != head)


last = last->next;
last->next = head->next;
head = head->next;
free(temp);
}
// Main menu
int main() {
int choice, n, data;
while (1) {
printf("\n--- Circular Linked List Menu ---\n");
printf("1. Create Circular Linked List\n");
printf("2. Display Circular Linked List\n");
printf("3. Insert at End\n");
printf("4. Delete from End\n");
printf("5. Insert at Front\n");
printf("6. Delete from Front\n");
printf("7. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Enter number of nodes: ");
scanf("%d", &n);
createCLL(n);
break;
case 2:
displayCLL();
break;
case 3:
printf("Enter data to insert at end: ");
scanf("%d", &data);
insertEnd(data);
break;
case 4:
deleteEnd();
break;
case 5:
printf("Enter data to insert at front: ");
scanf("%d", &data);
insertFront(data);
break;
case 6:
deleteFront();
break;
case 7:
printf("Exiting program.\n");
exit(0);
default:
printf("Invalid choice. Try again.\n");
}
}

return 0;
}
Practical No. 8
Design, develop and Implement a menu driven program in C for the following operations on
STACK of Integers (Array Implementation of Stack with maximum size MAX)
a) Push an Element on to Stack
b) Pop an Element from Stack
c) Demonstrate how Stack can be used to check Palindrome
d) Demonstrate Overflow and Underflow situations on Stack
e) Display the status of Stack
f) Exit

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

#define MAX 100

int stack[MAX];
int top = -1;

// Push operation
void push(int value) {
if (top == MAX - 1) {
printf("Stack Overflow! Cannot push %d\n", value);
return;
}
stack[++top] = value;
printf("%d pushed onto the stack.\n", value);
}

// Pop operation
int pop() {
if (top == -1) {
printf("Stack Underflow! Cannot pop.\n");
return -1;
}
int popped = stack[top--];
printf("%d popped from the stack.\n", popped);
return popped;
}

// Display stack status


void displayStack() {
if (top == -1) {
printf("Stack is empty.\n");
return;
}
printf("Stack contents (top to bottom): ");
for (int i = top; i >= 0; i--) {
printf("%d ", stack[i]);
}
printf("\n");
}

// Check Palindrome using Stack


void checkPalindrome(char str[]) {
int tempTop = -1;
char tempStack[MAX];

// Push all characters into the stack


for (int i = 0; str[i] != '\0'; i++) {
if (isalnum(str[i])) {
tempStack[++tempTop] = tolower(str[i]);
}
}

// Compare characters
for (int i = 0; str[i] != '\0'; i++) {
if (isalnum(str[i])) {
if (tolower(str[i]) != tempStack[tempTop--]) {
printf("'%s' is NOT a palindrome.\n", str);
return;
}
}
}
printf("'%s' is a palindrome.\n", str);
}

// Demonstrate Overflow and Underflow


void demoOverflow() {
printf("Demonstrating Stack Overflow:\n");
while (top < MAX - 1) {
push(1);
}
// One extra push to overflow
push(1);
}

void demoUnderflow() {
printf("Demonstrating Stack Underflow:\n");
while (top >= 0) {
pop();
}
// One extra pop to underflow
pop();
}

// Main menu
int main() {
int choice, value;
char str[100];

while (1) {
printf("\n--- Stack Menu (Array Implementation) ---\n");
printf("1. Push Element onto Stack\n");
printf("2. Pop Element from Stack\n");
printf("3. Check Palindrome using Stack\n");
printf("4. Demonstrate Overflow and Underflow\n");
printf("5. Display Stack Status\n");
printf("6. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
getchar(); // Consume newline character after scanf

switch (choice) {
case 1:
printf("Enter an integer to push: ");
scanf("%d", &value);
push(value);
break;
case 2:
pop();
break;
case 3:
printf("Enter a string to check for palindrome: ");
fgets(str, sizeof(str), stdin);
str[strcspn(str, "\n")] = '\0'; // Remove newline
checkPalindrome(str);
break;
case 4:
demoOverflow();
demoUnderflow();
break;
case 5:
displayStack();
break;
case 6:
printf("Exiting program.\n");
exit(0);
default:
printf("Invalid choice. Try again.\n");
}
}

return 0;
}
Practical No. 9
Design, develop and Implement a menu driven program in C for the following operations on
STACK of Integers using Linked List
a) Push an Element on to Stack
b) Pop an Element from Stack
c) Demonstrate Overflow and Underflow situations on Stack
d) Display the status of Stack
e) Exit
Support the program with appropriate functions for each of the above operations

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

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

// Top of stack
struct Node* top = NULL;

// Push operation
void push(int value) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
if (newNode == NULL) {
printf("Stack Overflow! Memory allocation failed.\n");
return;
}
newNode->data = value;
newNode->next = top;
top = newNode;
printf("%d pushed onto the stack.\n", value);
}

// Pop operation
int pop() {
if (top == NULL) {
printf("Stack Underflow! Stack is empty.\n");
return -1;
}
struct Node* temp = top;
int popped = temp->data;
top = top->next;
free(temp);
printf("%d popped from the stack.\n", popped);
return popped;
}

// Display stack status


void displayStack() {
if (top == NULL) {
printf("Stack is empty.\n");
return;
}
struct Node* temp = top;
printf("Stack contents (top to bottom): ");
while (temp != NULL) {
printf("%d ", temp->data);
temp = temp->next;
}
printf("\n");
}

// Demonstrate Overflow (only simulated due to dynamic memory)


void simulateOverflow() {
printf("Simulating Stack Overflow (keep pushing until malloc fails)...\n");
while (1) {
struct Node* temp = (struct Node*)malloc(sizeof(struct Node));
if (temp == NULL) {
printf("Stack Overflow! Memory allocation failed.\n");
break;
}
temp->data = 0;
temp->next = top;
top = temp;
}
}

// Demonstrate Underflow
void simulateUnderflow() {
printf("Simulating Stack Underflow (popping all elements)...\n");
while (top != NULL) {
pop();
}
pop(); // One extra to trigger underflow
}

// Main menu
int main() {
int choice, value;

while (1) {
printf("\n--- Stack Menu (Linked List Implementation) ---\n");
printf("1. Push Element onto Stack\n");
printf("2. Pop Element from Stack\n");
printf("3. Demonstrate Overflow and Underflow\n");
printf("4. Display Stack Status\n");
printf("5. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);

switch (choice) {
case 1:
printf("Enter integer to push: ");
scanf("%d", &value);
push(value);
break;
case 2:
pop();
break;
case 3:
simulateOverflow();
simulateUnderflow();
break;
case 4:
displayStack();
break;
case 5:
printf("Exiting program.\n");
exit(0);
default:
printf("Invalid choice. Try again.\n");
}
}

return 0;
}
Practical No. 10
Design, develop and Implement a Program in C for converting an Infix Expression to Postfix
Expression. Program should support for both parenthesized and free parenthesized
expressions with the operators: + ,-,*,/,% (Remainder), ^ (Power) and alphanumeric operands

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <math.h>

#define MAX 100

// Stack for operators


char stack[MAX];
int top = -1;

// Function prototypes
void push(char c);
char pop();
char peek();
int isOperator(char c);
int precedence(char c);
int isRightAssociative(char c);
int isHigher(char op1, char op2);
void infixToPostfix(char infix[], char postfix[]);

// Push to stack
void push(char c) {
if (top == MAX - 1) {
printf("Stack Overflow\n");
return;
}
stack[++top] = c;
}

// Pop from stack


char pop() {
if (top == -1)
return '\0'; // Stack Underflow
return stack[top--];
}

// Peek top of stack


char peek() {
if (top == -1)
return '\0';
return stack[top];
}
// Check if character is an operator
int isOperator(char c) {
return c == '+' || c == '-' || c == '*' || c == '/' || c == '%' || c == '^';
}

// Operator precedence
int precedence(char c) {
switch (c) {
case '^': return 3;
case '*':
case '/':
case '%': return 2;
case '+':
case '-': return 1;
default: return 0;
}
}

// Associativity: 1 if right-associative
int isRightAssociative(char c) {
return c == '^';
}

// Compare precedence
int isHigher(char op1, char op2) {
int p1 = precedence(op1);
int p2 = precedence(op2);

if (p1 > p2) return 1;


if (p1 < p2) return 0;
// Equal precedence
return !isRightAssociative(op1);
}

// Convert Infix to Postfix


void infixToPostfix(char infix[], char postfix[]) {
int i, k = 0;
char ch;

for (i = 0; infix[i] != '\0'; i++) {


ch = infix[i];

if (isalnum(ch)) {
postfix[k++] = ch;
} else if (ch == '(') {
push(ch);
} else if (ch == ')') {
while (top != -1 && peek() != '(') {
postfix[k++] = pop();
}
if (top == -1 || peek() != '(') {
printf("Error: Mismatched parentheses\n");
exit(1);
} else {
pop(); // Discard '('
}
} else if (isOperator(ch)) {
while (top != -1 && peek() != '(' && isHigher(peek(), ch)) {
postfix[k++] = pop();
}
push(ch);
}
}

// Pop remaining operators


while (top != -1) {
if (peek() == '(') {
printf("Error: Mismatched parentheses\n");
exit(1);
}
postfix[k++] = pop();
}

postfix[k] = '\0';
}

// Main driver
int main() {
char infix[MAX], postfix[MAX];

printf("Enter Infix Expression: ");


fgets(infix, MAX, stdin);
infix[strcspn(infix, "\n")] = '\0'; // Remove newline

infixToPostfix(infix, postfix);

printf("Postfix Expression: %s\n", postfix);

return 0;
}
Practical No. 11
Design, develop and Implement a menu driven Program in C for the following operations on
Linear QUEUE of Characters (Array Implementation of Queue with maximum size MAX)
a) Insert an Element on to Linear QUEUE
b) Delete an Element from Linear QUEUE
c) Demonstrate Overflow and Underflow situations on Linear QUEUE
d) Display the status of Linear QUEUE
e) Exit
Support the program with appropriate functions for each of the above operations

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

#define MAX 100

char queue[MAX];
int front = -1, rear = -1;

// Function to insert an element into the queue


void enqueue(char element) {
if (rear == MAX - 1) {
printf("Queue Overflow! Cannot insert '%c'\n", element);
return;
}
if (front == -1) front = 0; // First element
queue[++rear] = element;
printf("Inserted '%c' into the queue.\n", element);
}

// Function to delete an element from the queue


char dequeue() {
if (front == -1 || front > rear) {
printf("Queue Underflow! Cannot delete.\n");
return '\0';
}
char deleted = queue[front++];
printf("Deleted '%c' from the queue.\n", deleted);
return deleted;
}

// Display current queue status


void displayQueue() {
if (front == -1 || front > rear) {
printf("Queue is empty.\n");
return;
}
printf("Queue contents: ");
for (int i = front; i <= rear; i++) {
printf("%c ", queue[i]);
}
printf("\n");
}

// Demonstrate Overflow
void demoOverflow() {
front = 0;
rear = MAX - 1;
printf("Demonstrating Queue Overflow:\n");
enqueue('Z'); // Attempting overflow
}

// Demonstrate Underflow
void demoUnderflow() {
front = rear = -1;
printf("Demonstrating Queue Underflow:\n");
dequeue(); // Attempting underflow
}

// Main menu
int main() {
int choice;
char ch;

while (1) {
printf("\n--- Linear Queue Menu (Array Implementation) ---\n");
printf("1. Insert (Enqueue)\n");
printf("2. Delete (Dequeue)\n");
printf("3. Demonstrate Overflow and Underflow\n");
printf("4. Display Queue Status\n");
printf("5. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
getchar(); // Consume newline

switch (choice) {
case 1:
printf("Enter a character to insert: ");
scanf("%c", &ch);
enqueue(ch);
break;
case 2:
dequeue();
break;
case 3:
demoOverflow();
demoUnderflow();
break;
case 4:
displayQueue();
break;
case 5:
printf("Exiting program.\n");
exit(0);
default:
printf("Invalid choice. Try again.\n");
}
}

return 0;
}

Practical No.12

develop and Implement a menu driven Program in C for the following operations on Circular
QUEUE of Characters (Array Implementation of Queue with maximum size MAX)
a) Insert an Element on to Circular QUEUE
b) Delete an Element from Circular QUEUE
c) Demonstrate Overflow and Underflow situations on Circular QUEUE
d) Display the status of Circular
e) Exit
Support the program with appropriate functions for each of the above operations

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

#define MAX 5 // You can change this as needed

char queue[MAX];
int front = -1, rear = -1;

// Check if queue is full


int isFull() {
return ((rear + 1) % MAX == front);
}

// Check if queue is empty


int isEmpty() {
return (front == -1);
}

// Insert element
void enqueue(char ch) {
if (isFull()) {
printf("Queue Overflow! Cannot insert '%c'\n", ch);
return;
}
if (isEmpty()) {
front = rear = 0;
} else {
rear = (rear + 1) % MAX;
}
queue[rear] = ch;
printf("Inserted '%c' into the queue.\n", ch);
}

// Delete element
char dequeue() {
if (isEmpty()) {
printf("Queue Underflow! Cannot delete.\n");
return '\0';
}

char deleted = queue[front];


if (front == rear) {
// Queue had one element
front = rear = -1;
} else {
front = (front + 1) % MAX;
}

printf("Deleted '%c' from the queue.\n", deleted);


return deleted;
}

// Display queue status


void displayQueue() {
if (isEmpty()) {
printf("Queue is empty.\n");
return;
}

printf("Queue contents: ");


int i = front;
while (1) {
printf("%c ", queue[i]);
if (i == rear)
break;
i = (i + 1) % MAX;
}
printf("\n");
}

// Demonstrate Overflow
void demoOverflow() {
front = 0;
rear = MAX - 2; // Fill queue except one
for (int i = 0; i < MAX - 1; i++)
queue[i] = 'A' + i;
rear = (rear + 1) % MAX;
enqueue('Z'); // This should cause overflow
}

// Demonstrate Underflow
void demoUnderflow() {
front = rear = -1;
dequeue(); // This should cause underflow
}

// Main menu
int main() {
int choice;
char ch;

while (1) {
printf("\n--- Circular Queue Menu (Array Implementation) ---\n");
printf("1. Insert (Enqueue)\n");
printf("2. Delete (Dequeue)\n");
printf("3. Demonstrate Overflow and Underflow\n");
printf("4. Display Queue Status\n");
printf("5. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
getchar(); // Consume newline

switch (choice) {
case 1:
printf("Enter a character to insert: ");
scanf("%c", &ch);
enqueue(ch);
break;
case 2:
dequeue();
break;
case 3:
demoOverflow();
demoUnderflow();
break;
case 4:
displayQueue();
break;
case 5:
printf("Exiting program.\n");
exit(0);
default:
printf("Invalid choice. Try again.\n");
}
}

return 0;
}
Practical No.13
Design, develop and Implement a menu driven Program in C for the following Searching
operations using Array
a) Perform Linear Search
b) Perform Binary Search
c) Exit

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

// Function to perform Linear Search


void linearSearch(int arr[], int n, int key) {
int found = 0;
for (int i = 0; i < n; i++) {
if (arr[i] == key) {
printf("Element %d found at position %d (index %d).\n", key, i + 1, i);
found = 1;
break;
}
}
if (!found)
printf("Element %d not found in the array.\n", key);
}

// Function to perform Binary Search


void binarySearch(int arr[], int n, int key) {
int low = 0, high = n - 1, mid, found = 0;
while (low <= high) {
mid = (low + high) / 2;
if (arr[mid] == key) {
printf("Element %d found at position %d (index %d).\n", key, mid + 1, mid);
found = 1;
break;
} else if (arr[mid] < key) {
low = mid + 1;
} else {
high = mid - 1;
}
}
if (!found)
printf("Element %d not found in the array.\n", key);
}

// Utility function to input array


void inputArray(int arr[], int *n) {
printf("Enter the number of elements in the array: ");
scanf("%d", n);

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


for (int i = 0; i < *n; i++) {
scanf("%d", &arr[i]);
}
}

// Main Menu
int main() {
int arr[100], n = 0, choice, key;

while (1) {
printf("\n--- Array Searching Menu ---\n");
printf("1. Perform Linear Search\n");
printf("2. Perform Binary Search (on sorted array)\n");
printf("3. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);

switch (choice) {
case 1:
inputArray(arr, &n);
printf("Enter the element to search (Linear Search): ");
scanf("%d", &key);
linearSearch(arr, n, key);
break;

case 2:
inputArray(arr, &n);
printf("Enter the element to search (Binary Search): ");
scanf("%d", &key);
// Ensure the array is sorted
printf("Make sure the array is sorted for binary search.\n");
binarySearch(arr, n, key);
break;

case 3:
printf("Exiting program.\n");
exit(0);

default:
printf("Invalid choice. Try again.\n");
}
}

return 0;
}
Practical No.14
Design, develop and Implement a menu driven Program in C for the following Sorting
operations using Array
a) Demonstrate Selection Sorting operations
b) Demonstrate Bubble Sorting operations
c) Demonstrate Insertion Sorting operations
d) Demonstrate Quick Sorting operations
e) Exit
Support the program with appropriate functions for each of the above operations

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

#define MAX 100

// Utility function to input array


void inputArray(int arr[], int *n) {
printf("Enter the number of elements: ");
scanf("%d", n);
printf("Enter %d elements:\n", *n);
for (int i = 0; i < *n; i++)
scanf("%d", &arr[i]);
}

// Utility function to display array


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

// Selection Sort
void selectionSort(int arr[], int n) {
int i, j, min, temp;
for (i = 0; i < n - 1; i++) {
min = i;
for (j = i + 1; j < n; j++)
if (arr[j] < arr[min])
min = j;
// Swap
temp = arr[i];
arr[i] = arr[min];
arr[min] = temp;
}
printf("Array sorted using Selection Sort:\n");
displayArray(arr, n);
}

// Bubble Sort
void bubbleSort(int arr[], int n) {
int i, j, temp;
for (i = 0; i < n - 1; i++) {
for (j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
// Swap
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
printf("Array sorted using Bubble Sort:\n");
displayArray(arr, n);
}

// Insertion Sort
void insertionSort(int arr[], int n) {
int i, key, j;
for (i = 1; i < n; i++) {
key = arr[i];
j = i - 1;

// Move elements greater than key


while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = key;
}
printf("Array sorted using Insertion Sort:\n");
displayArray(arr, n);
}

// Quick Sort - Helper functions


int partition(int arr[], int low, int high) {
int pivot = arr[high];
int i = (low - 1), temp;

for (int j = low; j < high; j++) {


if (arr[j] < pivot) {
i++;
// Swap
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
// Swap pivot to correct position
temp = arr[i + 1];
arr[i + 1] = arr[high];
arr[high] = temp;
return (i + 1);
}

void quickSort(int arr[], int low, int high) {


if (low < high) {
int pi = partition(arr, low, high);

quickSort(arr, low, pi - 1);


quickSort(arr, pi + 1, high);
}
}

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


quickSort(arr, 0, n - 1);
printf("Array sorted using Quick Sort:\n");
displayArray(arr, n);
}

// Main menu
int main() {
int choice, arr[MAX], n;

while (1) {
printf("\n--- Sorting Menu ---\n");
printf("1. Selection Sort\n");
printf("2. Bubble Sort\n");
printf("3. Insertion Sort\n");
printf("4. Quick Sort\n");
printf("5. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);

switch (choice) {
case 1:
inputArray(arr, &n);
selectionSort(arr, n);
break;
case 2:
inputArray(arr, &n);
bubbleSort(arr, n);
break;
case 3:
inputArray(arr, &n);
insertionSort(arr, n);
break;
case 4:
inputArray(arr, &n);
quickSortHandler(arr, n);
break;
case 5:
printf("Exiting program.\n");
exit(0);
default:
printf("Invalid choice. Try again.\n");
}
}

return 0;
}
Practical No.15
Design, develop and Implement a menu driven Program in C for the following operations on
Binary Search Tree (BST) of Integers:
a) Create a BST of N Integers:6,9,5,2,8,15,24,14,7,8,5,2
b) Traverse the BST in In order, Preorder and Post Order
c) Search the BST for a given element (KEY) and report the appropriate message
d) Delete an element (ELEM) from BST
e) Exit

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

// Node structure
struct Node {
int data;
struct Node *left, *right;
};

// Create a new node


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

// Insert node into BST (ignore duplicates)


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

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

// Preorder Traversal
void preorder(struct Node* root) {
if (root != NULL) {
printf("%d ", root->data);
preorder(root->left);
preorder(root->right);
}
}
// Postorder Traversal
void postorder(struct Node* root) {
if (root != NULL) {
postorder(root->left);
postorder(root->right);
printf("%d ", root->data);
}
}

// Search in BST
struct Node* search(struct Node* root, int key) {
if (root == NULL || root->data == key)
return root;
if (key < root->data)
return search(root->left, key);
return search(root->right, key);
}

// Find minimum node (used in deletion)


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

// Delete a node from BST


struct Node* deleteNode(struct Node* root, int key) {
if (root == NULL) return root;

if (key < root->data)


root->left = deleteNode(root->left, key);
else if (key > root->data)
root->right = deleteNode(root->right, key);
else {
// Node found
if (root->left == NULL) {
struct Node* temp = root->right;
free(root);
return temp;
}
else if (root->right == NULL) {
struct Node* temp = root->left;
free(root);
return temp;
}
struct Node* temp = findMin(root->right);
root->data = temp->data; // Replace with inorder successor
root->right = deleteNode(root->right, temp->data);
}
return root;
}
// Main menu
int main() {
struct Node* root = NULL;
int choice, key;
// a) Create BST with fixed data (ignores duplicates)
int elements[] = {6, 9, 5, 2, 8, 15, 24, 14, 7, 8, 5, 2};
int n = sizeof(elements) / sizeof(elements[0]);
for (int i = 0; i < n; i++)
root = insert(root, elements[i]);
while (1) {
printf("\n--- Binary Search Tree Menu ---\n");
printf("1. Inorder Traversal\n");
printf("2. Preorder Traversal\n");
printf("3. Postorder Traversal\n");
printf("4. Search an Element\n");
printf("5. Delete an Element\n");
printf("6. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Inorder Traversal: ");
inorder(root);
printf("\n");
break;
case 2:
printf("Preorder Traversal: ");
preorder(root);
printf("\n");
break;
case 3:
printf("Postorder Traversal: ");
postorder(root);
printf("\n");
break;
case 4:
printf("Enter element to search: ");
scanf("%d", &key);
if (search(root, key))
printf("Element %d found in the BST.\n", key);
else
printf("Element %d NOT found in the BST.\n", key);
break;
case 5:
printf("Enter element to delete: ");
scanf("%d", &key);
root = deleteNode(root, key);
printf("Element %d deleted if it existed.\n", key);
break;
case 6:
printf("Exiting program.\n");
exit(0);
default:
printf("Invalid choice. Try again.\n");
}
}
return 0;
}

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy