0% found this document useful (0 votes)
20 views

Lab File

Uploaded by

pranav
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

Lab File

Uploaded by

pranav
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 96

Delhi Technological University

IT DATA STRUCTURE G2 LAB

Practical File

Name: Prabhav Kumar


Roll no.: 2k22/ec/167
Teachers Name: Mrs. Bindu Verma
Index

Date
S.no Title

Programs on Strings and Passing Pointers to


1. Functions & Array 2 Aug 2024

Dynamic Memory Allocation and File


2. 19 Aug 2024
Operations

Searching and Sorting in Non-decreasing


3. 1 Sept 2024
order

4. Sparse Arrays and Matrix Operations 13 Sept 2024

5. Stacks and Queues 20 Sept 2024

6. Linear Linked List 4 Oct 2024

7. Circular and double Linked List 18 Oct 2024


Experiment 1
Q1: Write a function that accepts as input a string and determines the frequency of
occurrences of each of the distinct characters in the string. Test your function using
suitable data.
Code :
#include <iostream>
#include <unordered_map>
#include <string>
void charFrequency(const std::string& str) {
std::unordered_map<char, int> freq;
for (char ch : str) {
freq[ch]++;
}
for (const auto& pair : freq) {
std::cout << pair.first << " appears " << pair.second << " times\n";}}
int main() {
std::string str;
std::cout << "Enter a string: ";
std::getline(std::cin, str);
charFrequency(str);
return 0;
}

Output:

Q2: Write a function, strmdel, that accepts a string and two integers, start and length.
Return a new string that is equivalent to the original string, except that length
characters beginning at start have been removed.
Code:
#include <iostream>
#include <string>
using namespace std;
void strmdel(string &str, int start, int length) {
str.erase(start, length);}
int main() {
string str;
int start, length;
cout << "Enter a string: ";
getline(cin, str);
cout << "Enter start index and length: ";
cin >> start >> length;
strmdel(str, start, length);
cout << "Updated string: " << str << endl;
return 0;
}

Output:

Q3: Write a function, strdel, that accepts a string and a character. The function
returns the string with the first occurrence of the character removed.
Code :
#include <iostream>
#include <string>
using namespace std;
void strdel(string &str, char ch) {
size_t pos = str.find(ch);
if (pos != string::npos) {
str.erase(pos, 1);}}
int main() {
string str;
char ch;
cout << "Enter a string: ";
getline(cin, str);
cout << "Enter a character to remove: ";
cin >> ch;
strdel(str, ch);
cout << "Updated string: " << str << endl;
return 0;}
Output:
Q4: Write a program (WAP) with a function to swap two numbers using call by
reference.
Code:
#include <iostream>
using namespace std;
void swap(int &a, int &b) {
int temp = a;
a = b;
b = temp;}
int main() {
int x, y;
cout << "Enter two numbers: ";
cin >> x >> y;
swap(x, y);
cout << "After swapping: x = " << x << ", y = " << y << endl;
return 0;}

Output:

Q5: Write a program (WAP) with a function to swap two integer arrays of the same
size using call by reference.
Code:
#include <iostream>
using namespace std;
void swapArrays(int arr1[], int arr2[], int size) {
for (int i = 0; i < size; i++) {
int temp = arr1[i];
arr1[i] = arr2[i];
arr2[i] = temp;
}}
int main() {
int n;
cout << "Enter the size of arrays: ";
cin >> n;
int arr1[n], arr2[n];
cout << "Enter elements of first array:\n";
for (int i = 0; i < n; i++) {
cin >> arr1[i];
}
cout << "Enter elements of second array:\n";
for (int i = 0; i < n; i++) {
cin >> arr2[i];
}
swapArrays(arr1, arr2, n);
cout << "After swapping:\nFirst array: ";
for (int i = 0; i < n; i++) {
cout << arr1[i] << " ";
}
cout << "\nSecond array: ";
for (int i = 0; i < n; i++) {
cout << arr2[i] << " ";
}
return 0;
}
Output:
Q6: Write a program (WAP) to reverse an array by swapping (without using
additional memory).
Code:
#include <iostream>
using namespace std;

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


for (int i = 0; i < n / 2; i++) {
int temp = arr[i];
arr[i] = arr[n - i - 1];
arr[n - i - 1] = temp;
}
}
int main() {
int n;
cout << "Enter the size of array: ";
cin >> n;
int arr[n];
cout << "Enter the elements of the array:\n";
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
reverseArray(arr, n);
cout << "Reversed array: ";
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
return 0;
}
Output:

Q7: Write a program (WAP) with a function to swap two strings using pointers.
Code:
#include <iostream>
#include <string>
using namespace std;
void swapStrings(string *str1, string *str2) {
string temp = *str1;
*str1 = *str2;
*str2 = temp;
}
int main() {
string str1, str2;
cout << "Enter first string: ";
getline(cin, str1);
cout << "Enter second string: ";
getline(cin, str2);
swapStrings(&str1, &str2);
cout << "After swapping:\nFirst string: " << str1 << "\nSecond string: " << str2 <<
endl;
return 0;
}
Output:

Q8: Write a program (WAP) to find the number of non-repeated elements in an array.
Code:
#include <iostream>
using namespace std;
void findNonRepeated(int arr[], int n) {
for (int i = 0; i < n; i++) {
int count = 0;
for (int j = 0; j < n; j++) {
if (arr[i] == arr[j]) {
count++;}}
if (count == 1) {
cout << arr[i] << " ";}}
cout << endl;}
int main() {
int n;
cout << "Enter size of array: ";
cin >> n;
int arr[n];
cout << "Enter the elements of the array:\n";
for (int i = 0; i < n; i++) {
cin >> arr[i];}
cout << "Non-repeated elements: ";
findNonRepeated(arr, n);
return 0;}
Output:

Q9: Write a program (WAP) to identify the missing numbers in a given array within
the range [1…N].
#include <iostream>
using namespace std;

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


bool present[n + 1] = {false};
for (int i = 0; i < n; i++) {
if (arr[i] <= n && arr[i] > 0) {
present[arr[i]] = true;
}
}
cout << "Missing numbers: ";
for (int i = 1; i <= n; i++) {
if (!present[i]) {
cout << i << " ";
}
}
cout << endl;
}

int main() {
int n;
cout << "Enter the size of the array: ";
cin >> n;
int arr[n];
cout << "Enter the elements of the array:\n";
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
findMissingNumbers(arr, n);
return 0;
}
Output:
Experiment 2

Q1: Write a program (WAP) to find the median of the elements after merging two
sorted arrays of the same size.
Code:
#include <iostream>
#include <algorithm>
using namespace std;

void findMedian(int arr1[], int arr2[], int size) {


int merged[2 * size];

// Merge both arrays


for (int i = 0; i < size; i++) {
merged[i] = arr1[i];
merged[size + i] = arr2[i];
}

// Sort the merged array


sort(merged, merged + 2 * size);

// Find the median


double median;
if (2 * size % 2 == 0) {
median = (merged[size - 1] + merged[size]) / 2.0;
} else {
median = merged[size];
}

cout << "Median of merged array: " << median << endl;
}

int main() {
int n;
cout << "Enter the size of both arrays: ";
cin >> n;

int arr1[n], arr2[n];


cout << "Enter elements of first sorted array:\n";
for (int i = 0; i < n; i++) {
cin >> arr1[i];
}

cout << "Enter elements of second sorted array:\n";


for (int i = 0; i < n; i++) {
cin >> arr2[i];
}
findMedian(arr1, arr2, n);
return 0;
}
Output:

Q2: Write a program (WAP) to store information in an array of structures


dynamically, and also give a function to display the current information. The program
should give the user a choice for inserting data or displaying the current data.
Implement the program for Student structures (contains student_name,
student_roll_no, total_marks).
Code:
#include <iostream>
#include <string>
using namespace std;

struct Student {
string name;
int roll_no;
float total_marks;
};

void displayStudents(Student* students, int count) {


cout << "Student Information:\n";
for (int i = 0; i < count; i++) {
cout << "Name: " << students[i].name
<< ", Roll No: " << students[i].roll_no
<< ", Total Marks: " << students[i].total_marks << endl;
}
}

int main() {
int count = 0;
int capacity = 2; // Initial capacity
Student* students = new Student[capacity];

while (true) {
cout << "1. Insert student data\n2. Display student data\n3. Exit\nChoose an
option: ";
int choice;
cin >> choice;
if (choice == 1) {
if (count == capacity) {
capacity *= 2;
Student* newStudents = new Student[capacity];
for (int i = 0; i < count; i++) {
newStudents[i] = students[i];
}
delete[] students;
students = newStudents;
}

cout << "Enter student name: ";


cin.ignore();
getline(cin, students[count].name);
cout << "Enter roll number: ";
cin >> students[count].roll_no;
cout << "Enter total marks: ";
cin >> students[count].total_marks;
count++;
}
else if (choice == 2) {
displayStudents(students, count);
}
else if (choice == 3) {
break;
}
}

delete[] students;
return 0;
}
Output:
Q3: Implement the above program for Employee structures (contains
employee_name, emp_no, emp_salary).
Code:
#include <iostream>
#include <string>
using namespace std;
struct Employee {
string name;
int emp_no;
float emp_salary;
};
void displayEmployees(Employee* employees, int count) {
cout << "Employee Information:\n";
for (int i = 0; i < count; i++) {
cout << "Name: " << employees[i].name
<< ", Employee No: " << employees[i].emp_no
<< ", Salary: " << employees[i].emp_salary << endl;
}
}
int main() {
int count = 0;
int capacity = 2;
Employee* employees = new Employee[capacity];
while (true) {
cout << "1. Insert employee data\n2. Display employee data\n3. Exit\nChoose
an option: ";
int choice;
cin >> choice;
if (choice == 1) {
if (count == capacity) {
capacity *= 2;
Employee* newEmployees = new Employee[capacity];
for (int i = 0; i < count; i++) {
newEmployees[i] = employees[i];
}
delete[] employees;
employees = newEmployees;
}
cout << "Enter employee name: ";
cin.ignore();
getline(cin, employees[count].name);
cout << "Enter employee number: ";
cin >> employees[count].emp_no;
cout << "Enter employee salary: ";
cin >> employees[count].emp_salary;
count++;
}
else if (choice == 2) {
displayEmployees(employees, count);
}
else if (choice == 3) {
break;
}
}
delete[] employees;
return 0;
}

Output:
Q4: Implement the above program for Faculty structures (contains faculty_name,
faculty_ID, subject_codes, class_names).
Code:
#include <iostream>
#include <string>
using namespace std;

struct Faculty {
string name;
int faculty_ID;
string subject_codes;
string class_names;
};

void displayFaculty(Faculty* faculties, int count) {


cout << "Faculty Information:\n";
for (int i = 0; i < count; i++) {
cout << "Name: " << faculties[i].name
<< ", Faculty ID: " << faculties[i].faculty_ID
<< ", Subject Codes: " << faculties[i].subject_codes
<< ", Class Names: " << faculties[i].class_names << endl;
}
}

int main() {
int count = 0;
int capacity = 2;
Faculty* faculties = new Faculty[capacity];

while (true) {
cout << "1. Insert faculty data\n2. Display faculty data\n3. Exit\nChoose an
option: ";
int choice;
cin >> choice;

if (choice == 1) {
if (count == capacity) {
capacity *= 2;
Faculty* newFaculties = new Faculty[capacity];
for (int i = 0; i < count; i++) {
newFaculties[i] = faculties[i];
}
delete[] faculties;
faculties = newFaculties;
}

cout << "Enter faculty name: ";


cin.ignore();
getline(cin, faculties[count].name);
cout << "Enter faculty ID: ";
cin >> faculties[count].faculty_ID;
cout << "Enter subject codes: ";
cin.ignore();
getline(cin, faculties[count].subject_codes);
cout << "Enter class names: ";
getline(cin, faculties[count].class_names);
count++;
}
else if (choice == 2) {
displayFaculty(faculties, count);
}
else if (choice == 3) {
break;
}
}
delete[] faculties;
return 0;
}
Output:
Q5: Write a program (WAP) to create a new file, open an existing file, read the file to search
for a given word, write into the file, and close the file.

Code:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

// Function to create a file and write to it


void createAndWriteFile(const string &filename) {
ofstream outfile(filename); // Open the file in write mode
if (outfile.is_open()) {
// Write some data to the file
outfile << "This is a sample text file.\n";
outfile << "It contains multiple lines of text.\n";
outfile << "This line is to test the search functionality.\n";
outfile.close(); // Close the file after writing
cout << "File created and written successfully.\n";
} else {
cout << "Error creating the file.\n";
}
}

// Function to search for a word in the file


void readFileAndSearchWord(const string &filename, const string &word) {
ifstream infile(filename); // Open the file in read mode
if (infile.is_open()) {
string line;
bool found = false;
while (getline(infile, line)) { // Read each line of the file
if (line.find(word) != string::npos) { // Search for the word
cout << "Found the word \"" << word << "\" in the file.\n";
found = true;
break;
}
}
if (!found) {
cout << "The word \"" << word << "\" was not found in the file.\n";
}
infile.close(); // Close the file after reading
} else {
cout << "Error opening the file.\n";
}
}

int main() {
string filename = "example.txt"; // Filename to work with

// Create and write to the file


createAndWriteFile(filename);

// Search for a word in the file


string word;
cout << "Enter the word to search in the file: ";
cin >> word;
readFileAndSearchWord(filename, word);

return 0;
}
Output:
Experiment 3

Q1: Write a program (WAP) to implement Linear Search and Binary Search on a 1D
array of integers.

Code:
#include <iostream>
#include <algorithm>
using namespace std;

// Linear search function


int linearSearch(int arr[], int n, int key) {
for (int i = 0; i < n; i++) {
if (arr[i] == key)
return i;
}
return -1;
}

// Binary search function (array must be sorted)


int binarySearch(int arr[], int n, int key) {
int left = 0, right = n - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == key) return mid;
else if (arr[mid] < key) left = mid + 1;
else right = mid - 1;
}
return -1;
}

int main() {
int n, key;
cout << "Enter the size of the array: ";
cin >> n;
int arr[n];

cout << "Enter the elements of the array: ";


for (int i = 0; i < n; i++) {
cin >> arr[i];
}

cout << "Enter the element to search: ";


cin >> key;

// Perform Linear Search


int linResult = linearSearch(arr, n, key);
if (linResult != -1)
cout << "Linear Search: Element found at index " << linResult << endl;
else
cout << "Linear Search: Element not found." << endl;

// Sort the array for Binary Search


sort(arr, arr + n);

// Perform Binary Search


int binResult = binarySearch(arr, n, key);
if (binResult != -1)
cout << "Binary Search: Element found at index " << binResult << endl;
else
cout << "Binary Search: Element not found." << endl;

return 0;
}
Output:

Q2: Write a program (WAP) to implement Insertion Sort and Selection Sort on a 1D
array of strings.

Code:
#include <iostream>
#include <string>
using namespace std;

// Insertion Sort function


void insertionSort(string arr[], int n) {
for (int i = 1; i < n; i++) {
string key = arr[i];
int j = i - 1;
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = key;
}
}

// Selection Sort function


void selectionSort(string arr[], int n) {
for (int i = 0; i < n - 1; i++) {
int minIdx = i;
for (int j = i + 1; j < n; j++) {
if (arr[j] < arr[minIdx]) {
minIdx = j;
}
}
swap(arr[i], arr[minIdx]);
}
}

void printArray(string arr[], int n) {


for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
cout << endl;
}

int main() {
int n;
cout << "Enter the number of strings: ";
cin >> n;
string arr[n];

cout << "Enter the strings:\n";


for (int i = 0; i < n; i++) {
cin >> arr[i];
}

// Insertion Sort
insertionSort(arr, n);
cout << "Array after Insertion Sort: ";
printArray(arr, n);

// Selection Sort
selectionSort(arr, n);
cout << "Array after Selection Sort: ";
printArray(arr, n);

return 0;
}
Output:

Q3: Write a program (WAP) to implement Quick Sort on a 1D array of characters.

Code:
#include <iostream>
using namespace std;

// Partition function for Quick Sort


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

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


if (arr[j] < pivot) {
i++;
swap(arr[i], arr[j]);
}
}
swap(arr[i + 1], arr[high]);
return i + 1;
}

// Quick Sort function


void quickSort(char 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 printArray(char arr[], int n) {


for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
cout << endl;
}

int main() {
int n;
cout << "Enter the number of characters: ";
cin >> n;
char arr[n];

cout << "Enter the characters: ";


for (int i = 0; i < n; i++) {
cin >> arr[i];
}

quickSort(arr, 0, n - 1);

cout << "Array after Quick Sort: ";


printArray(arr, n);

return 0;
}

Output:

Q4:
Write a program (WAP) to implement Merge Sort on a 1D array of Student structures
(contains student_name, student_roll_no, total_marks) with the key as
student_roll_no.

Code:
#include <iostream>
#include <string>
using namespace std;

// Student structure
struct Student {
string name;
int roll_no;
float total_marks;
};

// Merge function for Merge Sort


void merge(Student arr[], int left, int mid, int right) {
int n1 = mid - left + 1;
int n2 = right - mid;

Student L[n1], R[n2];

for (int i = 0; i < n1; i++) L[i] = arr[left + i];


for (int i = 0; i < n2; i++) R[i] = arr[mid + 1 + i];

int i = 0, j = 0, k = left;

while (i < n1 && j < n2) {


if (L[i].roll_no <= R[j].roll_no) {
arr[k] = L[i];
i++;
} else {
arr[k] = R[j];
j++;
}
k++;
}

while (i < n1) {


arr[k] = L[i];
i++;
k++;
}

while (j < n2) {


arr[k] = R[j];
j++;
k++;
}
}

// Merge Sort function


void mergeSort(Student arr[], int left, int right) {
if (left < right) {
int mid = left + (right - left) / 2;
mergeSort(arr, left, mid);
mergeSort(arr, mid + 1, right);
merge(arr, left, mid, right);
}
}
void printArray(Student arr[], int n) {
for (int i = 0; i < n; i++) {
cout << "Name: " << arr[i].name << ", Roll No: " << arr[i].roll_no << ", Marks: "
<< arr[i].total_marks << endl;
}
}

int main() {
int n;
cout << "Enter the number of students: ";
cin >> n;
Student arr[n];

cout << "Enter student details (Name Roll_No Total_Marks):\n";


for (int i = 0; i < n; i++) {
cin >> arr[i].name >> arr[i].roll_no >> arr[i].total_marks;
}

mergeSort(arr, 0, n - 1);

cout << "Sorted students by Roll No:\n";


printArray(arr, n);

return 0;
}

Output:
Q5: Write a program (WAP) to implement Bubble Sort and Radix Sort on a 1D array
of Faculty structures (contains faculty_name, faculty_ID, subject_codes,
class_names) with the key as faculty_ID.

Code:
#include <iostream>
#include <string>
using namespace std;

// Faculty structure
struct Faculty {
string name;
int faculty_ID;
string subject_codes;
string class_names;
};

// Bubble Sort function


void bubbleSort(Faculty arr[], int n) {
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j].faculty_ID > arr[j + 1].faculty_ID) {
swap(arr[j], arr[j + 1]);
}
}
}
}

void printArray(Faculty arr[], int n) {


for (int i = 0; i < n; i++) {
cout << "Name: " << arr[i].name << ", Faculty ID: " << arr[i].faculty_ID << endl;
}
}

int main() {
int n;
cout << "Enter the number of faculty members: ";
cin >> n;
Faculty arr[n];

cout << "Enter faculty details (Name Faculty_ID Subject_Codes


Class_Names):\n";
for (int i = 0; i < n; i++) {
cin >> arr[i].name >> arr[i].faculty_ID >> arr[i].subject_codes >>
arr[i].class_names;
}

bubbleSort(arr, n);

cout << "Sorted faculty by Faculty ID:\n";


printArray(arr, n);

return 0;
}

Output:
Experiment 4

Q1: WAP to store and display a Lower-Right triangular matrix in RMO and CMO
fashion.

Code:
#include <iostream>
using namespace std;

void displayRMO(int matrix[], int size) {


cout << "Matrix in RMO: ";
for (int i = 0; i < size; i++) {
cout << matrix[i] << " ";
}
cout << endl;
}

void displayCMO(int matrix[], int size) {


cout << "Matrix in CMO: ";
for (int i = 0; i < size; i++) {
cout << matrix[i] << " ";
}
cout << endl;
}

void storeLowerRightTriangularRMO(int n, int matrix[][10], int store[]) {


int index = 0;
for (int i = 0; i < n; i++) {
for (int j = i; j < n; j++) {
store[index++] = matrix[i][j];
}
}
}

void storeLowerRightTriangularCMO(int n, int matrix[][10], int store[]) {


int index = 0;
for (int j = 0; j < n; j++) {
for (int i = 0; i <= j; i++) {
store[index++] = matrix[i][j];
}
}
}

int main() {
int n = 4;
int matrix[10][10] = {
{1, 2, 3, 4},
{0, 5, 6, 7},
{0, 0, 8, 9},
{0, 0, 0, 10}
};

int storeRMO[10], storeCMO[10];

storeLowerRightTriangularRMO(n, matrix, storeRMO);


storeLowerRightTriangularCMO(n, matrix, storeCMO);

displayRMO(storeRMO, 10);
displayCMO(storeCMO, 10);

return 0;
}
Output:

Q2: WAP to store and display an Upper-Right triangular matrix in RMO and CMO
fashion.

Code:
#include <iostream>
using namespace std;

// Function to store an Upper-Right triangular matrix in RMO


void storeUpperRightRMO(int n, int matrix[][10], int store[]) {
int index = 0;
for (int i = 0; i < n; i++) {
for (int j = i; j < n; j++) {
store[index++] = matrix[i][j]; // Only store upper-right part
}
}
}

// Function to store an Upper-Right triangular matrix in CMO


void storeUpperRightCMO(int n, int matrix[][10], int store[]) {
int index = 0;
for (int j = 0; j < n; j++) {
for (int i = 0; i <= j; i++) {
store[index++] = matrix[i][j]; // Store column-major
}
}
}

// Function to display Upper-Right matrix from RMO storage


void displayUpperRightRMO(int n, int store[]) {
int index = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (i <= j) {
cout << store[index++] << " ";
} else {
cout << "0 "; // Fill with zeroes
}
}
cout << endl;
}
}

// Function to display Upper-Right matrix from CMO storage


void displayUpperRightCMO(int n, int store[]) {
int index = 0;
for (int j = 0; j < n; j++) {
for (int i = 0; i <= j; i++) {
cout << store[index++] << " ";
}
cout << endl;
}
}

int main() {
int n = 3; // Size of matrix
int matrix[10][10] = {
{1, 2, 3},
{0, 4, 5},
{0, 0, 6}
};

int storeRMO[6], storeCMO[6];

// Store in RMO
storeUpperRightRMO(n, matrix, storeRMO);
cout << "Upper-Right Triangular Matrix in RMO:" << endl;
displayUpperRightRMO(n, storeRMO);

// Store in CMO
storeUpperRightCMO(n, matrix, storeCMO);
cout << "Upper-Right Triangular Matrix in CMO:" << endl;
displayUpperRightCMO(n, storeCMO);
return 0;
}

Output:

Q3: WAP to store and display a Tri-Diagonal matrix in RMO and CMO fashion.

Code:
#include <iostream>
using namespace std;

// Function to store Tri-Diagonal matrix in RMO


void storeTriDiagonalRMO(int n, int matrix[][10], int store[]) {
int index = 0;
for (int i = 0; i < n; i++) {
store[index++] = matrix[i][i]; // Main diagonal
if (i < n - 1) {
store[index++] = matrix[i][i + 1]; // Upper diagonal
store[index++] = matrix[i + 1][i]; // Lower diagonal
}
}
}

// Function to display Tri-Diagonal matrix from RMO storage


void displayTriDiagonalRMO(int n, int store[]) {
int index = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (i == j) {
cout << store[index++] << " "; // Main diagonal
} else if (i == j + 1 || i + 1 == j) {
cout << store[index++] << " "; // Upper and lower diagonal
} else {
cout << "0 "; // Fill with zeroes
}
}
cout << endl;
}
}

int main() {
int n = 3; // Size of matrix
int matrix[10][10] = {
{1, 2, 0},
{3, 4, 5},
{0, 6, 7}
};

int storeRMO[9];

// Store in RMO
storeTriDiagonalRMO(n, matrix, storeRMO);
cout << "Tri-Diagonal Matrix in RMO:" << endl;
displayTriDiagonalRMO(n, storeRMO);

return 0;
}

Output:
Q4: WAP to store and display a Lower-Left triangular matrix in RMO and CMO
fashion.

Code:
#include <iostream>
using namespace std;

// Function to store Lower-Left triangular matrix in RMO


void storeLowerLeftRMO(int n, int matrix[][10], int store[]) {
int index = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j <= i; j++) {
store[index++] = matrix[i][j]; // Only store lower-left part
}
}
}

// Function to display Lower-Left matrix from RMO storage


void displayLowerLeftRMO(int n, int store[]) {
int index = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (i >= j) {
cout << store[index++] << " ";
} else {
cout << "0 "; // Fill with zeroes
}
}
cout << endl;
}
}

int main() {
int n = 3; // Size of matrix
int matrix[10][10] = {
{1, 0, 0},
{2, 3, 0},
{4, 5, 6}
};

int storeRMO[6];

// Store in RMO
storeLowerLeftRMO(n, matrix, storeRMO);
cout << "Lower-Left Triangular Matrix in RMO:" << endl;
displayLowerLeftRMO(n, storeRMO);

return 0;
}
Output:

Q5: WAP to store and display an Upper-Left triangular matrix in RMO and CMO
fashion.

Code:
#include <iostream>
using namespace std;

// Function to store Upper-Left triangular matrix in RMO


void storeUpperLeftRMO(int n, int matrix[][10], int store[]) {
int index = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j <= i; j++) {
store[index++] = matrix[j][i]; // Only store upper-left part
}
}
}

// Function to display Upper-Left matrix from RMO storage


void displayUpperLeftRMO(int n, int store[]) {
int index = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (i >= j) {
cout << store[index++] << " ";
} else {
cout << "0 "; // Fill with zeroes
}
}
cout << endl;
}
}

int main() {
int n = 3; // Size of matrix
int matrix[10][10] = {
{1, 0, 0},
{2, 3, 0},
{4, 5, 6}
};

int storeRMO[6];

// Store in RMO
storeUpperLeftRMO(n, matrix, storeRMO);
cout << "Upper-Left Triangular Matrix in RMO:" << endl;
displayUpperLeftRMO(n, storeRMO);

return 0;
}

Output:

Q6: WAP to store and display a C matrix in RMO and CMO fashion. (C matrix
contains non-zero elements in the first row, last row, and first column only).

Code:
#include <iostream>
using namespace std;

void storeCMatrixRMO(int n, int matrix[][10], int store[]) {


int index = 0;

// Store the first row


for (int i = 0; i < n; i++) {
store[index++] = matrix[0][i];
}

// Store first column, skipping the first row


for (int i = 1; i < n - 1; i++) {
store[index++] = matrix[i][0];
}

// Store the last row


for (int i = 0; i < n; i++) {
store[index++] = matrix[n - 1][i];
}
}

void storeCMatrixCMO(int n, int matrix[][10], int store[]) {


int index = 0;

// Store the first column


for (int i = 0; i < n; i++) {
store[index++] = matrix[i][0];
}

// Store the first row, skipping the first element


for (int j = 1; j < n; j++) {
store[index++] = matrix[0][j];
}

// Store the last row, skipping the first element


for (int j = 1; j < n; j++) {
store[index++] = matrix[n - 1][j];
}
}

void displayMatrix(int store[], int size) {


for (int i = 0; i < size; i++) {
cout << store[i] << " ";
}
cout << endl;
}

int main() {
int n = 4;
int matrix[10][10] = {
{1, 2, 3, 4},
{5, 0, 0, 0},
{6, 0, 0, 0},
{7, 8, 9, 10}
};

int storeRMO[12], storeCMO[12];

storeCMatrixRMO(n, matrix, storeRMO);


storeCMatrixCMO(n, matrix, storeCMO);

cout << "C Matrix in RMO: ";


displayMatrix(storeRMO, 12);
cout << "C Matrix in CMO: ";
displayMatrix(storeCMO, 12);

return 0;
}

Q7: WAP to store and display a Z matrix in RMO and CMO fashion. (Z matrix
contains non-zero elements in the first row, last row, and right diagonal only).

Code:
#include <iostream>
using namespace std;

// Function to store Z Matrix in RMO


void storeZMatrixRMO(int n, int matrix[][10], int store[]) {
int index = 0;

// First row
for (int j = 0; j < n; j++) {
store[index++] = matrix[0][j];
}

// Right diagonal excluding the first and last element


for (int i = 1; i < n-1; i++) {
store[index++] = matrix[i][n-i-1];
}

// Last row
for (int j = 0; j < n; j++) {
store[index++] = matrix[n-1][j];
}
}

// Function to store Z Matrix in CMO


void storeZMatrixCMO(int n, int matrix[][10], int store[]) {
int index = 0;

// First row
for (int j = 0; j < n; j++) {
store[index++] = matrix[0][j];
}

// Right diagonal excluding the first and last element


for (int i = 1; i < n-1; i++) {
store[index++] = matrix[i][n-i-1];
}

// Last row
for (int j = 0; j < n; j++) {
store[index++] = matrix[n-1][j];
}
}

// Function to display Z Matrix stored in RMO


void displayZMatrixRMO(int n, int store[]) {
int index = 0;

// First row
for (int j = 0; j < n; j++) {
cout << store[index++] << " ";
}
cout << endl;

// Rest of the rows


for (int i = 1; i < n-1; i++) {
for (int j = 0; j < n; j++) {
if (j == n-i-1) {
cout << store[index++] << " ";
} else {
cout << "0 ";
}
}
cout << endl;
}

// Last row
for (int j = 0; j < n; j++) {
cout << store[index++] << " ";
}
cout << endl;
}

// Function to display Z Matrix stored in CMO


void displayZMatrixCMO(int n, int store[]) {
int index = 0;

// First row
for (int j = 0; j < n; j++) {
cout << store[index++] << " ";
}
cout << endl;

// Rest of the rows


for (int i = 1; i < n-1; i++) {
for (int j = 0; j < n; j++) {
if (j == n-i-1) {
cout << store[index++] << " ";
} else {
cout << "0 ";
}
}
cout << endl;
}

// Last row
for (int j = 0; j < n; j++) {
cout << store[index++] << " ";
}
cout << endl;
}

int main() {
int n = 4; // Size of matrix
int matrix[10][10] = {
{1, 2, 3, 4},
{0, 0, 5, 0},
{0, 6, 0, 0},
{7, 8, 9, 10}
};

int storeRMO[10], storeCMO[10];

// Store in RMO
storeZMatrixRMO(n, matrix, storeRMO);
cout << "Z Matrix in RMO:" << endl;
displayZMatrixRMO(n, storeRMO);

// Store in CMO
storeZMatrixCMO(n, matrix, storeCMO);
cout << "Z Matrix in CMO:" << endl;
displayZMatrixCMO(n, storeCMO);

return 0;
}
Output:

Q8: WAP using switch statement to perform the following functions: 1. Transpose of
a matrix. 2. Computing determinant of a matrix. 3. Addition of two matrices. 4.
Multiplication of two matrices. The program should handle wrong input exceptions
such as size mismatch, etc.

Code:
#include <iostream>
using namespace std;

// Function to transpose a matrix


void transposeMatrix(int n, int matrix[][10], int result[][10]) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
result[j][i] = matrix[i][j];
}
}
}

// Helper function to get the determinant of a matrix (recursive for n > 2)


int determinantMatrix(int n, int matrix[][10]) {
int det = 0;
if (n == 1) {
return matrix[0][0];
}
if (n == 2) {
return (matrix[0][0] * matrix[1][1]) - (matrix[0][1] * matrix[1][0]);
}

int submatrix[10][10];
for (int x = 0; x < n; x++) {
// Forming the submatrix
int subi = 0;
for (int i = 1; i < n; i++) {
int subj = 0;
for (int j = 0; j < n; j++) {
if (j == x) continue;
submatrix[subi][subj] = matrix[i][j];
subj++;
}
subi++;
}
// Recursive call for determinant calculation
det += (x % 2 == 0 ? 1 : -1) * matrix[0][x] * determinantMatrix(n - 1, submatrix);
}
return det;
}

// Function to add two matrices


void addMatrices(int n, int matrix1[][10], int matrix2[][10], int result[][10]) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
result[i][j] = matrix1[i][j] + matrix2[i][j];
}
}
}

// Function to multiply two matrices


void multiplyMatrices(int n, int matrix1[][10], int matrix2[][10], int result[][10]) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
result[i][j] = 0;
for (int k = 0; k < n; k++) {
result[i][j] += matrix1[i][k] * matrix2[k][j];
}
}
}
}

// Function to print a matrix


void printMatrix(int n, int matrix[][10]) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cout << matrix[i][j] << " ";
}
cout << endl;
}
}

int main() {
int choice;
int n = 2; // You can change this to test larger matrices
int matrix1[10][10] = {{1, 2}, {3, 4}};
int matrix2[10][10] = {{5, 6}, {7, 8}};
int result[10][10];

cout << "Enter your choice: \n1. Transpose\n2. Determinant\n3. Addition\n4.


Multiplication\n";
cin >> choice;

switch (choice) {
case 1:
transposeMatrix(n, matrix1, result);
cout << "Transpose Matrix:\n";
printMatrix(n, result);
break;
case 2:
cout << "Determinant: " << determinantMatrix(n, matrix1) << endl;
break;
case 3:
addMatrices(n, matrix1, matrix2, result);
cout << "Matrix Addition Result:\n";
printMatrix(n, result);
break;
case 4:
multiplyMatrices(n, matrix1, matrix2, result);
cout << "Matrix Multiplication Result:\n";
printMatrix(n, result);
break;
default:
cout << "Invalid choice!";
}

return 0;
}
Output:

Q9: WAP for addition and multiplication of two sparse matrices. The matrices can be
of any of the following types: - a. Lower-Right triangular matrix. - b. Upper-Right
triangular matrix. - c. Tri-Diagonal matrix. - d. Lower-Left triangular matrix. - e.
Upper-Left triangular matrix. Firstly, the program should ask the user about the
type(s) of input matrices, store the given matrices either in RMO or CMO fashion in a
1D array, and then perform the respective operation and display the result.

Code:
#include <iostream>
using namespace std;

// Function to store Lower-Right triangular matrix in RMO


void storeLowerRightRMO(int n, int matrix[][10], int store[]) {
int index = 0;
for (int i = 0; i < n; i++) {
for (int j = i; j < n; j++) {
store[index++] = matrix[i][j]; // Only store the lower-right part
}
}
}

// Function to add two Lower-Right triangular matrices in RMO


void addLowerRightRMO(int n, int store1[], int store2[], int result[]) {
int size = n * (n + 1) / 2; // Total elements in the lower-right triangular part
for (int i = 0; i < size; i++) {
result[i] = store1[i] + store2[i];
}
}

// Function to multiply two Lower-Right triangular matrices in RMO


void multiplyLowerRightRMO(int n, int store1[], int store2[], int result[]) {
int index = 0;
for (int i = 0; i < n; i++) {
for (int j = i; j < n; j++) {
result[index] = 0;
for (int k = i; k <= j; k++) {
result[index] += store1[i * (i + 1) / 2 + k] * store2[k * (k + 1) / 2 + j];
}
index++;
}
}
}

// Function to display the result of the 1D array


void displayMatrix(int n, int store[]) {
int index = 0;
for (int i = 0; i < n; i++) {
for (int j = i; j < n; j++) {
cout << store[index++] << " ";
}
cout << endl;
}
}

int main() {
int n = 3; // Size of the matrix

// Lower-Right Triangular Matrix


int matrix1[10][10] = {
{1, 2, 3},
{0, 4, 5},
{0, 0, 6}
};

int matrix2[10][10] = {
{7, 8, 9},
{0, 10, 11},
{0, 0, 12}
};

int store1[6], store2[6], result[6];

// Store matrices in RMO


storeLowerRightRMO(n, matrix1, store1);
storeLowerRightRMO(n, matrix2, store2);

// Perform addition
addLowerRightRMO(n, store1, store2, result);
cout << "Addition of Lower-Right Matrices in RMO:" << endl;
displayMatrix(n, result);

// Perform multiplication
multiplyLowerRightRMO(n, store1, store2, result);
cout << "Multiplication of Lower-Right Matrices in RMO:" << endl;
displayMatrix(n, result);

return 0;
}
Output:
Experiment 5

Q1a: Write a program (WAP) to implement Stack Abstract Data Type (ADT) using
arrays, which has basic operations as: Create(), IsEmpty(), Push(), Pop(), IsFull()

Code:
#include<iostream>
using namespace std;
#define MAX 100

class Stack {
int top;
int arr[MAX];

public:
Stack() { top = -1; }

bool IsFull() {
return top >= MAX - 1;
}

bool IsEmpty() {
return top == -1;
}

void Push(int x) {
if (IsFull()) {
cout << "Stack Overflow\n";
} else {
arr[++top] = x;
cout << x << " pushed into stack\n";
}
}

int Pop() {
if (IsEmpty()) {
cout << "Stack Underflow\n";
return -1;
} else {
int val = arr[top--];
cout << val << " popped from stack\n";
return val;
}
}
};

int main() {
Stack s;
s.Push(10);
s.Push(20);
s.Pop();
s.Pop();
return 0;
}
Output:

Q2a: WAP to evaluate a given postfix expression using Stack ADT.

Code:
#include<iostream>
using namespace std;

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


int last = arr[n-1];
for (int i = n-1; i > 0; i--) {
arr[i] = arr[i-1];
}
arr[0] = last;
}

int main() {
int arr[] = {1, 2, 3, 4, 5};
int n = sizeof(arr)/sizeof(arr[0]);

cyclicPermute(arr, n);

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


cout << arr[i] << " ";
}
cout << endl;
return 0;
}
Output:

Q2b: WAP to check if the given string is a palindrome using stack.

Code:
#include<iostream>
#include<stack>
using namespace std;

bool isPalindrome(string str) {


stack<char> s;
for (int i = 0; i < str.length(); i++) {
s.push(str[i]);
}

for (int i = 0; i < str.length(); i++) {


if (str[i] != s.top()) return false;
s.pop();
}
return true;
}

int main() {
string str = "madam";
if (isPalindrome(str)) {
cout << str << " is a palindrome\n";
} else {
cout << str << " is not a palindrome\n";
}
return 0;
}

Output:
Q3a: WAP to check if the given expression is correctly parenthesized.

Code:
#include<iostream>
#include<stack>
using namespace std;

bool isBalanced(string expr) {


stack<char> s;
for (char ch : expr) {
if (ch == '(' || ch == '{' || ch == '[') {
s.push(ch);
} else {
if (s.empty()) return false;
char top = s.top();
s.pop();
if ((ch == ')' && top != '(') ||
(ch == '}' && top != '{') ||
(ch == ']' && top != '[')) return false;
}
}
return s.empty();
}

int main() {
string expr = "{[()]}";
if (isBalanced(expr)) {
cout << "Balanced\n";
} else {
cout << "Not Balanced\n";
}
return 0;
}

Output:
Q3b: WAP to implement two overlapping stacks, facing in opposite directions, using
an array and check for overflow and underflow conditions.

Code:
#include<iostream>
using namespace std;
#define MAX 100

class TwoStacks {
int arr[MAX];
int top1, top2;

public:
TwoStacks() {
top1 = -1;
top2 = MAX;
}

void Push1(int x) {
if (top1 < top2 - 1) {
arr[++top1] = x;
} else {
cout << "Stack Overflow\n";
}
}

void Push2(int x) {
if (top1 < top2 - 1) {
arr[--top2] = x;
} else {
cout << "Stack Overflow\n";
}
}

int Pop1() {
if (top1 >= 0) {
return arr[top1--];
} else {
cout << "Stack Underflow\n";
return -1;
}
}

int Pop2() {
if (top2 < MAX) {
return arr[top2++];
} else {
cout << "Stack Underflow\n";
return -1;
}
}
};

int main() {
TwoStacks ts;
ts.Push1(5);
ts.Push2(10);
ts.Push1(15);
ts.Push2(20);

cout << "Popped from Stack1: " << ts.Pop1() << endl;
cout << "Popped from Stack2: " << ts.Pop2() << endl;

return 0;
}

Output:

Q4: WAP to implement 3-stacks of size m in an array of size n, with all basic
operations: IsEmpty(), Push(), Pop(), IsFull()

Code:
#include<iostream>
using namespace std;
#define MAX 100

class ThreeStacks {
int arr[MAX];
int top1, top2, top3, n;

public:
ThreeStacks(int n) {
this->n = n;
top1 = -1;
top2 = n / 3 - 1;
top3 = 2 * n / 3 - 1;
}

void Push1(int x) {
if (top1 < n / 3 - 1) {
arr[++top1] = x;
} else {
cout << "Stack 1 Overflow\n";
}
}

void Push2(int x) {
if (top2 < 2 * n / 3 - 1) {
arr[++top2] = x;
} else {
cout << "Stack 2 Overflow\n";
}
}

void Push3(int x) {
if (top3 < n - 1) {
arr[++top3] = x;
} else {
cout << "Stack 3 Overflow\n";
}
}

int Pop1() {
if (top1 >= 0) {
return arr[top1--];
} else {
cout << "Stack 1 Underflow\n";
return -1;
}
}

int Pop2() {
if (top2 >= n / 3) {
return arr[top2--];
} else {
cout << "Stack 2 Underflow\n";
return -1;
}
}

int Pop3() {
if (top3 >= 2 * n / 3) {
return arr[top3--];
} else {
cout << "Stack 3 Underflow\n";
return -1;
}
}
};
int main() {
ThreeStacks ts(9);
ts.Push1(5);
ts.Push2(10);
ts.Push3(15);

cout << "Popped from Stack 1: " << ts.Pop1() << endl;
cout << "Popped from Stack 2: " << ts.Pop2() << endl;
cout << "Popped from Stack 3: " << ts.Pop3() << endl;

return 0;
}

Output:

Q5a: WAP to transform an infix expression into an equivalent postfix expression


using stack.

Code:
#include<iostream>
#include<stack>
using namespace std;

int precedence(char op) {


if (op == '+' || op == '-') return 1;
if (op == '*' || op == '/') return 2;
return 0;
}

string infixToPostfix(string exp) {


stack<char> s;
string result;

for (int i = 0; i < exp.length(); i++) {


if (isalnum(exp[i])) {
result += exp[i];
} else if (exp[i] == '(') {
s.push(exp[i]);
} else if (exp[i] == ')') {
while (!s.empty() && s.top() != '(') {
result += s.top();
s.pop();
}
s.pop(); // Remove '(' from the stack
} else {
while (!s.empty() && precedence(s.top()) >= precedence(exp[i])) {
result += s.top();
s.pop();
}
s.push(exp[i]);
}
}

while (!s.empty()) {
result += s.top();
s.pop();
}

return result;
}

int main() {
string exp = "A+B*C";
cout << "Postfix Expression: " << infixToPostfix(exp) << endl;
return 0;
}

Output:
Q5b: WAP to transform infix expression into equivalent prefix expression using
stack, similar to above.

Code:
#include<iostream>
#include<stack>
#include<algorithm>
using namespace std;

int precedence(char op) {


if (op == '+' || op == '-') return 1;
if (op == '*' || op == '/') return 2;
return 0;
}

string infixToPostfix(string exp) {


stack<char> s;
string result;

for (int i = 0; i < exp.length(); i++) {


if (isalnum(exp[i])) {
result += exp[i];
} else if (exp[i] == '(') {
s.push(exp[i]);
} else if (exp[i] == ')') {
while (!s.empty() && s.top() != '(') {
result += s.top();
s.pop();
}
s.pop(); // Remove '(' from the stack
} else {
while (!s.empty() && precedence(s.top()) >= precedence(exp[i])) {
result += s.top();
s.pop();
}
s.push(exp[i]);
}
}

while (!s.empty()) {
result += s.top();
s.pop();
}

return result;
}

string infixToPrefix(string exp) {


reverse(exp.begin(), exp.end());
for (int i = 0; i < exp.length(); i++) {
if (exp[i] == '(') exp[i] = ')';
else if (exp[i] == ')') exp[i] = '(';
}

string postfix = infixToPostfix(exp);


reverse(postfix.begin(), postfix.end());

return postfix;
}

int main() {
string exp = "(A-B/C)*(A/K-L)";
cout << "Prefix Expression: " << infixToPrefix(exp) << endl;
return 0;
}

Output:

Q6a: WAP that gives the solution to the Tower of Hanoi problem for n disks. Test the
program using: - n = 3, n = 4.

Code:
#include<iostream>
using namespace std;

void towerOfHanoi(int n, char from_rod, char to_rod, char aux_rod) {


if (n == 1) {
cout << "Move disk 1 from " << from_rod << " to " << to_rod << endl;
return;
}
towerOfHanoi(n-1, from_rod, aux_rod, to_rod);
cout << "Move disk " << n << " from " << from_rod << " to " << to_rod << endl;
towerOfHanoi(n-1, aux_rod, to_rod, from_rod);
}

int main() {
int n = 4; // Number of disks
towerOfHanoi(n, 'A', 'C', 'B'); // A, B, C are names of rods
return 0;
}

Output:

Q6b: WAP to solve the maze problem of size m x m.

Code:
#include<iostream>
using namespace std;

#define N 4

bool isSafe(int maze[N][N], int x, int y) {


return (x >= 0 && x < N && y >= 0 && y < N && maze[x][y] == 1);
}

bool solveMazeUtil(int maze[N][N], int x, int y, int sol[N][N]);

bool solveMaze(int maze[N][N]) {


int sol[N][N] = { {0, 0, 0, 0},
{0, 0, 0, 0},
{0, 0, 0, 0},
{0, 0, 0, 0} };

if (!solveMazeUtil(maze, 0, 0, sol)) {
cout << "No solution exists" << endl;
return false;
}

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


for (int j = 0; j < N; j++) {
cout << sol[i][j] << " ";
}
cout << endl;
}
return true;
}

bool solveMazeUtil(int maze[N][N], int x, int y, int sol[N][N]) {


if (x == N - 1 && y == N - 1 && maze[x][y] == 1) {
sol[x][y] = 1;
return true;
}

if (isSafe(maze, x, y)) {
if (sol[x][y] == 1) return false;

sol[x][y] = 1;

if (solveMazeUtil(maze, x + 1, y, sol)) return true;


if (solveMazeUtil(maze, x, y + 1, sol)) return true;
if (solveMazeUtil(maze, x - 1, y, sol)) return true;
if (solveMazeUtil(maze, x, y - 1, sol)) return true;

sol[x][y] = 0;
return false;
}
return false;
}

int main() {
int maze[N][N] = { {1, 0, 0, 0},
{1, 1, 0, 1},
{0, 1, 0, 0},
{1, 1, 1, 1} };

solveMaze(maze);
return 0;
}
Output:

Q7a: WAP to implement Queue ADT using arrays with the basic functions of:
Create(), IsEmpty(), Insert(), Delete(), IsFull()

Code:
#include<iostream>
using namespace std;
#define MAX 5

class Queue {
int front, rear;
int arr[MAX];

public:
Queue() {
front = -1;
rear = -1;
}

bool IsFull() {
return (rear + 1) % MAX == front;
}

bool IsEmpty() {
return front == -1;
}

void Insert(int x) {
if (IsFull()) {
cout << "Queue is Full\n";
return;
}
if (IsEmpty()) {
front = rear = 0;
} else {
rear = (rear + 1) % MAX;
}
arr[rear] = x;
cout << x << " inserted into queue\n";
}

void Delete() {
if (IsEmpty()) {
cout << "Queue is Empty\n";
return;
}
cout << arr[front] << " deleted from queue\n";
if (front == rear) {
front = rear = -1;
} else {
front = (front + 1) % MAX;
}
}

void Display() {
if (IsEmpty()) {
cout << "Queue is Empty\n";
return;
}
int i = front;
while (i != rear) {
cout << arr[i] << " ";
i = (i + 1) % MAX;
}
cout << arr[rear] << endl;
}
};

int main() {
Queue q;
q.Insert(10);
q.Insert(20);
q.Insert(30);
q.Display();
q.Delete();
q.Display();
return 0;
}
Output:

Q7b: WAP to implement queue using stacks.


#include<iostream>
#include<stack>
using namespace std;

class QueueUsingStacks {
stack<int> s1, s2;

public:
void Insert(int x) {
s1.push(x);
cout << x << " inserted into queue\n";
}

void Delete() {
if (s2.empty()) {
if (s1.empty()) {
cout << "Queue is Empty\n";
return;
}
while (!s1.empty()) {
s2.push(s1.top());
s1.pop();
}
}
cout << s2.top() << " deleted from queue\n";
s2.pop();
}
};

int main() {
QueueUsingStacks q;
q.Insert(10);
q.Insert(20);
q.Delete();
q.Insert(30);
q.Delete();
return 0;
}

Output:

Q8a : WAP to implement 2 overlapping queues in an array of size n. There are two
queues facing in opposite directions with basic operations: IsEmpty(), Insert(),
Delete(), IsFull().

Code:
#include<iostream>
using namespace std;
#define MAX 10

class TwoQueues {
int arr[MAX];
int front1, rear1, front2, rear2;

public:
TwoQueues() {
front1 = rear1 = -1;
front2 = rear2 = MAX;
}

void Insert1(int x) {
if (rear1 < rear2 - 1) {
if (front1 == -1) front1 = 0;
arr[++rear1] = x;
cout << x << " inserted into Queue 1\n";
} else {
cout << "Queue 1 Overflow\n";
}
}

void Insert2(int x) {
if (rear1 < rear2 - 1) {
if (front2 == MAX) front2 = MAX - 1;
arr[--rear2] = x;
cout << x << " inserted into Queue 2\n";
} else {
cout << "Queue 2 Overflow\n";
}
}

void Delete1() {
if (front1 == -1) {
cout << "Queue 1 Underflow\n";
} else {
cout << arr[front1] << " deleted from Queue 1\n";
if (front1 == rear1) {
front1 = rear1 = -1;
} else {
front1++;
}
}
}

void Delete2() {
if (front2 == MAX) {
cout << "Queue 2 Underflow\n";
} else {
cout << arr[front2] << " deleted from Queue 2\n";
if (front2 == rear2) {
front2 = rear2 = MAX;
} else {
front2--;
}
}
}
};

int main() {
TwoQueues q;
q.Insert1(10);
q.Insert2(20);
q.Delete1();
q.Insert1(30);
q.Delete2();
return 0;
}
Output:

Q8b: WAP to implement dequeue using arrays with all the basic operations.

Code:
#include<iostream>
using namespace std;
#define MAX 5

class Deque {
int arr[MAX];
int front, rear, size;

public:
Deque() {
front = -1;
rear = 0;
size = 0;
}

bool IsFull() {
return (size == MAX);
}

bool IsEmpty() {
return (size == 0);
}

void InsertFront(int x) {
if (IsFull()) {
cout << "Deque Overflow\n";
return;
}
if (front == -1) {
front = rear = 0;
} else if (front == 0) {
front = MAX - 1;
} else {
front = front - 1;
}
arr[front] = x;
size++;
}

void InsertRear(int x) {
if (IsFull()) {
cout << "Deque Overflow\n";
return;
}
if (rear == MAX - 1) {
rear = 0;
} else {
rear = rear + 1;
}
arr[rear] = x;
size++;
}

void DeleteFront() {
if (IsEmpty()) {
cout << "Deque Underflow\n";
return;
}
if (front == rear) {
front = rear = -1;
} else if (front == MAX - 1) {
front = 0;
} else {
front++;
}
size--;
}

void DeleteRear() {
if (IsEmpty()) {
cout << "Deque Underflow\n";
return;
}
if (rear == front) {
rear = front = -1;
} else if (rear == 0) {
rear = MAX - 1;
} else {
rear--;
}
size--;
}

void Display() {
if (IsEmpty()) {
cout << "Deque is empty\n";
return;
}
int i = front;
while (i != rear) {
cout << arr[i] << " ";
i = (i + 1) % MAX;
}
cout << arr[rear] << endl;
}
};

int main() {
Deque dq;
dq.InsertRear(5);
dq.InsertRear(10);
dq.InsertFront(15);
dq.Display();
dq.DeleteRear();
dq.Display();
return 0;
}

Output:
Experiment 6
Q1:
WAP to construct simple linear linked list using dynamic memory allocation for the
given elements with the following functions, (a) Inserting a new node, (b) Accessing
a node (finding the position wrt header), (c) Removing a node with particular key
value, (d) Complete deletion of a linked list, and (e) Displaying the current list. (f)
Copy the linked list and return the pointer of the new list.

Code:
#include<iostream>
using namespace std;

class Node {
public:
int data;
Node* next;
};

class LinkedList {
Node* head;

public:
LinkedList() {
head = nullptr;
}

// (a) Insert a new node


void Insert(int newData) {
Node* newNode = new Node();
newNode->data = newData;
newNode->next = head;
head = newNode;
cout << "Inserted: " << newData << endl;
}

// (b) Access a node (finding the position wrt header)


Node* Access(int position) {
Node* temp = head;
int count = 0;
while (temp != nullptr) {
if (count == position) {
return temp;
}
count++;
temp = temp->next;
}
return nullptr; // If position is invalid
}
// (c) Remove a node with a particular key value
void Remove(int key) {
Node* temp = head;
Node* prev = nullptr;

if (temp != nullptr && temp->data == key) {


head = temp->next;
delete temp;
cout << "Removed: " << key << endl;
return;
}

while (temp != nullptr && temp->data != key) {


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

if (temp == nullptr) return; // Key not found

prev->next = temp->next;
delete temp;
cout << "Removed: " << key << endl;
}

// (d) Complete deletion of the linked list


void DeleteList() {
Node* current = head;
Node* next;

while (current != nullptr) {


next = current->next;
delete current;
current = next;
}
head = nullptr;
cout << "List deleted." << endl;
}

// (e) Display the current list


void Display() {
Node* temp = head;
while (temp != nullptr) {
cout << temp->data << " -> ";
temp = temp->next;
}
cout << "NULL" << endl;
}

// (f) Copy the linked list and return the pointer of the new list
LinkedList* Copy() {
LinkedList* newList = new LinkedList();
Node* current = head;
Node** lastPtrRef = &(newList->head);

while (current != nullptr) {


Node* newNode = new Node();
newNode->data = current->data;
newNode->next = nullptr;
*lastPtrRef = newNode;
lastPtrRef = &(newNode->next);
current = current->next;
}
return newList;
}
};

int main() {
LinkedList list;
list.Insert(10);
list.Insert(20);
list.Insert(30);

list.Display();
Node* node = list.Access(1);
if (node) cout << "Node at position 1: " << node->data << endl;

list.Remove(20);
list.Display();

LinkedList* copiedList = list.Copy();


cout << "Copied list: ";
copiedList->Display();

list.DeleteList();
list.Display();

return 0;
}

Output:
Q2: (a) WAP to reverse a singly linked list using one auxillary pointer. And try without
using any auxillary pointer. (b) WAP to implement Stack ADT using Linked list with
the basic operations as Create(), IsEmpty(), Push(), Pop(), IsFull() with appropriate
prototype to a functions.

Code a:
#include<iostream>
using namespace std;

class Node {
public:
int data;
Node* next;
};

class LinkedList {
Node* head;

public:
LinkedList() {
head = nullptr;
}

void Insert(int newData) {


Node* newNode = new Node();
newNode->data = newData;
newNode->next = head;
head = newNode;
}

void Display() {
Node* temp = head;
while (temp != nullptr) {
cout << temp->data << " -> ";
temp = temp->next;
}
cout << "NULL" << endl;
}

// (ii)(a) Reverse using one auxiliary pointer


void Reverse() {
Node* prev = nullptr;
Node* current = head;
Node* next = nullptr;

while (current != nullptr) {


next = current->next;
current->next = prev;
prev = current;
current = next;
}
head = prev;
}
};

int main() {
LinkedList list;
list.Insert(10);
list.Insert(20);
list.Insert(30);

cout << "Original list: ";


list.Display();

list.Reverse();

cout << "Reversed list: ";


list.Display();

return 0;
}

Output A:

Code b:
#include<iostream>
using namespace std;

class Node {
public:
int data;
Node* next;
};

class Stack {
Node* top;

public:
Stack() {
top = nullptr;
}

bool IsEmpty() {
return top == nullptr;
}

void Push(int newData) {


Node* newNode = new Node();
newNode->data = newData;
newNode->next = top;
top = newNode;
cout << "Pushed: " << newData << endl;
}

void Pop() {
if (IsEmpty()) {
cout << "Stack is Empty" << endl;
return;
}
Node* temp = top;
cout << "Popped: " << top->data << endl;
top = top->next;
delete temp;
}

void Display() {
Node* temp = top;
while (temp != nullptr) {
cout << temp->data << " -> ";
temp = temp->next;
}
cout << "NULL" << endl;
}
};

int main() {
Stack stack;
stack.Push(10);
stack.Push(20);
stack.Push(30);

stack.Display();
stack.Pop();
stack.Display();

return 0;
}
Output B;

Q3: WAP to implement Queue ADT using Linked list with the basic functions of
Create(), IsEmpty(), Insert(), Delete() and IsFull() with suitable prototype to a
functions.

Code:
#include<iostream>
using namespace std;

class Node {
public:
int data;
Node* next;
};

class Queue {
Node *front, *rear;

public:
Queue() {
front = rear = nullptr;
}

bool IsEmpty() {
return front == nullptr;
}

void Insert(int newData) {


Node* newNode = new Node();
newNode->data = newData;
newNode->next = nullptr;
if (rear == nullptr) {
front = rear = newNode;
cout << "Inserted: " << newData << endl;
return;
}

rear->next = newNode;
rear = newNode;
cout << "Inserted: " << newData << endl;
}

void Delete() {
if (IsEmpty()) {
cout << "Queue is Empty" << endl;
return;
}

Node* temp = front;


front = front->next;

if (front == nullptr) {
rear = nullptr;
}

cout << "Deleted: " << temp->data << endl;


delete temp;
}

void Display() {
Node* temp = front;
while (temp != nullptr) {
cout << temp->data << " -> ";
temp = temp->next;
}
cout << "NULL" << endl;
}
};

int main() {
Queue q;
q.Insert(10);
q.Insert(20);
q.Insert(30);

q.Display();
q.Delete();
q.Display();

return 0;
}
Output:

Q4: WAP for polynomial addition. Represent polynomial in linked list form with
suitable data structure.

Code:
#include<iostream>
using namespace std;

class Node {
public:
int coeff;
int power;
Node* next;
};

class Polynomial {
Node* head;

public:
Polynomial() {
head = nullptr;
}

// Add term to the polynomial


void AddTerm(int coeff, int power) {
Node* newNode = new Node();
newNode->coeff = coeff;
newNode->power = power;
newNode->next = nullptr;

if (!head || head->power < power) {


newNode->next = head;
head = newNode;
} else {
Node* temp = head;
while (temp->next && temp->next->power >= power) {
temp = temp->next;
}
newNode->next = temp->next;
temp->next = newNode;
}
}

// Display the polynomial


void Display() {
if (!head) {
cout << "0" << endl;
return;
}

Node* temp = head;


while (temp != nullptr) {
cout << temp->coeff << "x^" << temp->power;
if (temp->next != nullptr && temp->next->coeff > 0)
cout << " + ";
temp = temp->next;
}
cout << endl;
}

// Polynomial addition
Polynomial* Add(Polynomial* poly2) {
Polynomial* result = new Polynomial();
Node* p1 = head;
Node* p2 = poly2->head;

while (p1 != nullptr && p2 != nullptr) {


if (p1->power == p2->power) {
result->AddTerm(p1->coeff + p2->coeff, p1->power);
p1 = p1->next;
p2 = p2->next;
} else if (p1->power > p2->power) {
result->AddTerm(p1->coeff, p1->power);
p1 = p1->next;
} else {
result->AddTerm(p2->coeff, p2->power);
p2 = p2->next;
}
}

while (p1 != nullptr) {


result->AddTerm(p1->coeff, p1->power);
p1 = p1->next;
}

while (p2 != nullptr) {


result->AddTerm(p2->coeff, p2->power);
p2 = p2->next;
}

return result;
}
};

int main() {
Polynomial poly1, poly2;

poly1.AddTerm(3, 2);
poly1.AddTerm(5, 1);
poly1.AddTerm(6, 0);

poly2.AddTerm(2, 2);
poly2.AddTerm(3, 1);
poly2.AddTerm(4, 0);

cout << "Polynomial 1: ";


poly1.Display();
cout << "Polynomial 2: ";
poly2.Display();

Polynomial* result = poly1.Add(&poly2);


cout << "Result of addition: ";
result->Display();

delete result;
return 0;
}

Output:
Q5: WAP to swap elements in pairs in the given linked list. (e.g.: 1->2->3->4->5-
>null, then result should be 2->1->4->3->5->null.

Code:
#include<iostream>
using namespace std;

class Node {
public:
int data;
Node* next;
};

class LinkedList {
Node* head;

public:
LinkedList() {
head = nullptr;
}

void Insert(int newData) {


Node* newNode = new Node();
newNode->data = newData;
newNode->next = head;
head = newNode;
}

// Swap elements in pairs


void SwapInPairs() {
Node* temp = head;
while (temp != nullptr && temp->next != nullptr) {
// Swap the data of the two nodes
int swap = temp->data;
temp->data = temp->next->data;
temp->next->data = swap;
// Move to the next pair
temp = temp->next->next;
}
}

void Display() {
Node* temp = head;
while (temp != nullptr) {
cout << temp->data << " -> ";
temp = temp->next;
}
cout << "NULL" << endl;
}
};
int main() {
LinkedList list;
list.Insert(5);
list.Insert(4);
list.Insert(3);
list.Insert(2);
list.Insert(1);

cout << "Original list: ";


list.Display();

list.SwapInPairs();

cout << "List after swapping in pairs: ";


list.Display();

return 0;
}

Output:

Q6: (a) WAP to find second last node of the given linked list. (b) WAP to
concatenate two singly linked list in sorted order either ascending or descending.

Code A:
#include<iostream>
using namespace std;

class Node {
public:
int data;
Node* next;
};

class LinkedList {
Node* head;

public:
LinkedList() {
head = nullptr;
}

void Insert(int newData) {


Node* newNode = new Node();
newNode->data = newData;
newNode->next = head;
head = newNode;
}

// Find the second last node


Node* FindSecondLast() {
if (head == nullptr || head->next == nullptr) {
return nullptr; // No second last node exists
}

Node* temp = head;


while (temp->next->next != nullptr) {
temp = temp->next;
}
return temp;
}

void Display() {
Node* temp = head;
while (temp != nullptr) {
cout << temp->data << " -> ";
temp = temp->next;
}
cout << "NULL" << endl;
}
};

int main() {
LinkedList list;
list.Insert(10);
list.Insert(20);
list.Insert(30);

list.Display();

Node* secondLast = list.FindSecondLast();


if (secondLast) {
cout << "Second last node: " << secondLast->data << endl;
} else {
cout << "Second last node doesn't exist." << endl;
}

return 0;
}
Output A:

Code B:
#include<iostream>
using namespace std;

class Node {
public:
int data;
Node* next;
};

class LinkedList {
Node* head;

public:
LinkedList() {
head = nullptr;
}

void Insert(int newData) {


Node* newNode = new Node();
newNode->data = newData;
newNode->next = nullptr;

if (!head || head->data >= newData) {


newNode->next = head;
head = newNode;
} else {
Node* temp = head;
while (temp->next != nullptr && temp->next->data < newData) {
temp = temp->next;
}
newNode->next = temp->next;
temp->next = newNode;
}
}

void Display() {
Node* temp = head;
while (temp != nullptr) {
cout << temp->data << " -> ";
temp = temp->next;
}
cout << "NULL" << endl;
}

// Concatenate two sorted lists in sorted order


LinkedList* Concatenate(LinkedList* list2) {
Node* head1 = head;
Node* head2 = list2->head;

LinkedList* resultList = new LinkedList();

while (head1 != nullptr && head2 != nullptr) {


if (head1->data <= head2->data) {
resultList->Insert(head1->data);
head1 = head1->next;
} else {
resultList->Insert(head2->data);
head2 = head2->next;
}
}

while (head1 != nullptr) {


resultList->Insert(head1->data);
head1 = head1->next;
}

while (head2 != nullptr) {


resultList->Insert(head2->data);
head2 = head2->next;
}

return resultList;
}
};

int main() {
LinkedList list1, list2;

list1.Insert(10);
list1.Insert(20);
list1.Insert(30);

list2.Insert(15);
list2.Insert(25);
list2.Insert(35);

cout << "List 1: ";


list1.Display();

cout << "List 2: ";


list2.Display();
LinkedList* resultList = list1.Concatenate(&list2);
cout << "Concatenated sorted list: ";
resultList->Display();

return 0;
}
Output B
Experiment 7

Q1: WAP to create a Circular Singly Linked List for the given elements with the
following functions:
(a) Inserting a node, before the node with key givenkey,
(b) Inserting a node, after the node with key givenkey,
(c) Accessing a node (finding the position wrt header),
(d) Removing a node with particular key value,
(e) Complete deletion of a list,
(f) Displaying the current list, and
(g) Sorting the list.

Code:

#include <iostream>

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

class CircularSinglyLinkedList {
private:
Node* head;

public:
CircularSinglyLinkedList() : head(nullptr) {}

// Function to insert a node before the given key


void insertBefore(int key, int data) {
Node* newNode = new Node{data, nullptr};
if (!head) { // If the list is empty
head = newNode;
head->next = head; // Point to itself
return;
}

Node* current = head;


Node* prev = nullptr;

// Search for the key in the list


do {
prev = current;
current = current->next;
if (current->data == key) { // Key found
newNode->next = current;
prev->next = newNode;
return;
}
} while (current != head);

std::cout << "Key not found!" << std::endl;


delete newNode; // Clean up if key is not found
}

// Function to insert a node after the given key


void insertAfter(int key, int data) {
Node* newNode = new Node{data, nullptr};
if (!head) { // If the list is empty
head = newNode;
head->next = head; // Point to itself
return;
}

Node* current = head;

// Search for the key in the list


do {
if (current->data == key) { // Key found
newNode->next = current->next;
current->next = newNode;
return;
}
current = current->next;
} while (current != head);

std::cout << "Key not found!" << std::endl;


delete newNode; // Clean up if key is not found
}

// Function to display the current list


void display() {
if (!head) {
std::cout << "List is empty!" << std::endl;
return;
}

Node* current = head;


do {
std::cout << current->data << " ";
current = current->next;
} while (current != head);
std::cout << std::endl;
}

// Function to remove a node with the given key


void removeNode(int key) {
if (!head) { // If the list is empty
std::cout << "List is empty!" << std::endl;
return;
}

Node* current = head;


Node* prev = nullptr;

// Search for the key in the list


do {
if (current->data == key) { // Key found
if (current == head && current->next == head) { // Only one node
delete head;
head = nullptr;
} else {
if (current == head) { // Update head if necessary
prev = head;
while (prev->next != head) { // Find the last node
prev = prev->next;
}
prev->next = current->next; // Remove head
head = current->next; // Update head
} else {
prev->next = current->next; // Bypass the current node
}
delete current;
}
return;
}
prev = current;
current = current->next;
} while (current != head);

std::cout << "Key not found!" << std::endl;


}

// Function to sort the list


void sortList() {
if (!head || head->next == head) return; // List is empty or has one element

Node* current = head;


Node* index = nullptr;
int temp;

do {
index = current->next;
while (index != head) {
if (current->data > index->data) {
temp = current->data;
current->data = index->data;
index->data = temp;
}
index = index->next;
}
current = current->next;
} while (current != head);
}

// Function to completely delete the list


void deleteList() {
if (!head) return;

Node* current = head;


Node* nextNode;

do {
nextNode = current->next;
delete current;
current = nextNode;
} while (current != head);

head = nullptr;
}

~CircularSinglyLinkedList() {
deleteList(); // Clean up on destruction
}
};

int main() {
CircularSinglyLinkedList list;

// Inserting nodes into the list


list.insertAfter(10, 20); // Should indicate "Key not found!"
list.insertBefore(10, 30); // Should indicate "Key not found!"

// Adding nodes to ensure we have a base for future inserts


list.insertAfter(20, 10); // Now we can insert after (will still indicate not found)
list.insertBefore(10, 20); // Should work now

// Add some initial nodes


list.insertAfter(10, 30); // Insert 30 after 10
list.insertAfter(30, 40); // Insert 40 after 30
list.display(); // Expected: 20 10 30 40

list.sortList(); // Sort the list


list.display(); // Should be sorted

list.removeNode(30); // Remove the node with value 30


list.display(); // Expected: 20 10 40

list.deleteList(); // Delete entire list


list.display(); // Expected: "List is empty!"

return 0;
}

Output:
Q2: WAP to implement doubly linked list with the following operations.

(a) Inserting a node, before the node with key givenkey.


(b) Inserting a node, after the node with key givenkey.
(c) Inserting a node at iith location wrt header.(assuming header at 1st location).
(d) Accessing a node (finding the position wrt header).
(e) Removing a node with particular key value.
(f) Complete deletion of a list.
(g) Displaying the current list in clockwise fashion.
(h) Displaying the current list in anti-clockwise fashion.
(i) Sorting the list.

Code:

#include <iostream>
#include <string>

struct Student {
std::string student_name;
int student_roll_no;
float total_marks;
};

struct DNode {
Student data;
DNode* next;
DNode* prev;
};

class DoublyLinkedList {
private:
DNode* head;

public:
DoublyLinkedList() : head(nullptr) {}

// Function to insert a node before the given key


void insertBefore(int key, const Student& student) {
DNode* newNode = new DNode{student, nullptr, nullptr};
if (!head) { // If list is empty
head = newNode;
newNode->next = newNode->prev = newNode; // Point to itself
return;
}

DNode* current = head;


do {
if (current->data.student_roll_no == key) {
newNode->next = current;
newNode->prev = current->prev;
current->prev->next = newNode;
current->prev = newNode;
if (current == head) head = newNode; // Update head if necessary
return;
}
current = current->next;
} while (current != head);

std::cout << "Key " << key << " not found!" << std::endl;
delete newNode; // Clean up
}

// Function to insert a node after the given key


void insertAfter(int key, const Student& student) {
DNode* newNode = new DNode{student, nullptr, nullptr};
if (!head) { // If list is empty
head = newNode;
newNode->next = newNode->prev = newNode; // Point to itself
return;
}

DNode* current = head;


do {
if (current->data.student_roll_no == key) {
newNode->next = current->next;
newNode->prev = current;
current->next->prev = newNode;
current->next = newNode;
return;
}
current = current->next;
} while (current != head);

std::cout << "Key " << key << " not found!" << std::endl;
delete newNode; // Clean up
}

// Function to insert a node at the ith location


void insertAt(int index, const Student& student) {
DNode* newNode = new DNode{student, nullptr, nullptr};
if (!head) { // If list is empty
head = newNode;
newNode->next = newNode->prev = newNode; // Point to itself
return;
}

if (index == 0) { // Insert at the beginning


newNode->next = head;
newNode->prev = head->prev;
head->prev->next = newNode;
head->prev = newNode;
head = newNode;
return;
}

DNode* current = head;


int pos = 0;

do {
if (pos == index - 1) {
newNode->next = current->next;
newNode->prev = current;
current->next->prev = newNode;
current->next = newNode;
return;
}
current = current->next;
pos++;
} while (current != head);

std::cout << "Index " << index << " out of bounds!" << std::endl;
delete newNode; // Clean up
}

// Function to access a node (finding position with respect to the header)


int accessNode(int key) {
DNode* current = head;
int position = 0;

if (!head) return -1; // List is empty

do {
if (current->data.student_roll_no == key) return position;
current = current->next;
position++;
} while (current != head);

return -1; // Key not found


}

// Function to remove a node with a particular key value


void removeNode(int key) {
if (!head) return;

DNode* current = head;

do {
if (current->data.student_roll_no == key) {
if (current == head && current->next == head) { // Only one node
delete head;
head = nullptr;
} else {
current->prev->next = current->next;
current->next->prev = current->prev;
if (current == head) head = current->next; // Update head if necessary
delete current;
}
return;
}
current = current->next;
} while (current != head);

std::cout << "Key " << key << " not found!" << std::endl;
}

// Function to completely delete the list


void deleteList() {
if (!head) return;

DNode* current = head;


DNode* nextNode;

do {
nextNode = current->next;
delete current;
current = nextNode;
} while (current != head);

head = nullptr;
}

// Function to display the current list clockwise


void displayClockwise() {
if (!head) {
std::cout << "List is empty!" << std::endl;
return;
}

DNode* current = head;


do {
std::cout << "Roll No: " << current->data.student_roll_no
<< ", Name: " << current->data.student_name
<< ", Marks: " << current->data.total_marks << std::endl;
current = current->next;
} while (current != head);
}

// Function to display the current list anti-clockwise


void displayAntiClockwise() {
if (!head) {
std::cout << "List is empty!" << std::endl;
return;
}

DNode* current = head->prev;


do {
std::cout << "Roll No: " << current->data.student_roll_no
<< ", Name: " << current->data.student_name
<< ", Marks: " << current->data.total_marks << std::endl;
current = current->prev;
} while (current->next != head);
}

// Function to sort the list based on student roll number


void sortList() {
if (!head || head->next == head) return; // List is empty or has one element

DNode* current = head;


DNode* index = nullptr;
Student temp;

do {
index = current->next;
while (index != head) {
if (current->data.student_roll_no > index->data.student_roll_no) {
temp = current->data;
current->data = index->data;
index->data = temp;
}
index = index->next;
}
current = current->next;
} while (current != head);
}

~DoublyLinkedList() {
deleteList(); // Clean up on destruction
}
};

int main() {
DoublyLinkedList list;

// Create students
Student s1 = {"Alice", 1, 85.0};
Student s2 = {"Bob", 2, 90.0};
Student s3 = {"Charlie", 3, 95.0};
Student s4 = {"David", 4, 88.0};
Student s5 = {"Eve", 5, 92.0};
// Insert students directly into the list
list.insertAt(0, s1); // Insert Alice at index 0
list.insertAt(1, s2); // Insert Bob at index 1
list.insertAt(2, s3); // Insert Charlie at index 2
list.insertAt(3, s4); // Insert David at index 3
list.insertAt(4, s5); // Insert Eve at index 4

std::cout << "List after initial insertions:" << std::endl;


list.displayClockwise(); // Display the current list

// Testing the key-based insertions


list.insertBefore(3, {"Frank", 6, 87.0}); // Insert Frank before Charlie
list.insertAfter(1, {"Grace", 7, 89.0}); // Insert Grace after Bob
std::cout << "\nList after more insertions:" << std::endl;
list.displayClockwise(); // Display the current list

// Accessing a node
int position = list.accessNode(4); // Access position of David
std::cout << "\nPosition of roll number 4 (David): " << position << std::endl;

// Sort the list


list.sortList();
std::cout << "\nSorted list by roll number:" << std::endl;
list.displayClockwise(); // Should be sorted by roll_no

// Removing a node
list.removeNode(2); // Remove Bob
std::cout << "\nList after removing roll number 2 (Bob):" << std::endl;
list.displayClockwise(); // Display the current list

// Complete deletion of the list


list.deleteList();
std::cout << "\nList after complete deletion:" << std::endl;
list.displayClockwise(); // Should indicate list is empty

return 0;
}

Output:

You might also like