0% found this document useful (0 votes)
9 views89 pages

data structures - lab file (Extra Experiments)

Lab

Uploaded by

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

data structures - lab file (Extra Experiments)

Lab

Uploaded by

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

Data Structures Lab

CIC-255
Faculty name: Student name

Roll No.:
Semester:

Maharaja Agrasen Institute of Technology,


PSP area,
Sector – 22, Rohini, New Delhi – 110085

(Affiliated to Guru Gobind Singh Indraprastha University, New Delhi)


MAHARAJAAGRASENINSTITUTEOF
TECHNOLOGYVISION
To nurture young minds in a learning environment of high academic value
and imbibe spiritual and ethical values with technological and management
competence.

MISSION
The Institute shall endeavor to incorporate the following basic missions in
the teaching methodology:
Engineering Hardware – Software Symbiosis
Practical exercises in all Engineering and Management disciplines shall be
carried out by Hardware equipment as well as the related software enabling deeper
understanding of basic concepts and encouraging inquisitive nature.
Life – Long Learning
The Institute strives to match technological advancements and encourage
students to keep updating their knowledge for enhancing their skills and inculcating
their habit of continuous learning.
Liberalization and Globalization
The Institute endeavors to enhance technical and management skills of
students so that they are intellectually capable and competent professionals with
Industrial Aptitude to face the challenges of globalization.
Diversification
The Engineering, Technology and Management disciplines have diverse
fields of studies with different attributes. The aim is to create a synergy of the above
attributes by encouraging analytical thinking.
Digitization of Learning Processes
The Institute provides seamless opportunities for innovative learning in all
Engineering and Management disciplines through digitization
of learning processes using analysis, synthesis, simulation, graphics, tutorials
and related tools to create a platform for multi- disciplinary approach.
Entrepreneurship
The Institute strives to develop potential Engineers and Managers by
enhancing their skills and research capabilities so that they become successful
entrepreneurs and responsible citizens.

MAHARAJAAGRASENINSTITUTEOF
TECHNOLOGY

COMPUTERSCIENCE&ENGINEERING DEPARTMENT

VISION
“To be centre of excellence in education, research and technology transfer in the field of
computer engineering and promote entrepreneurship and ethical values.”

MISSION
“To foster an open, multidisciplinary and highly collaborative research environment
to produce world-class engineers capable of providing innovative solutions to real
life problems and fulfil societal needs.
LIST OF EXPERIMENTS (As prescribed by G.G.S.I.P.U)

1. Implement sparse matrix using array. Description of program:


a. Read a 2D array from the user.
b. Store it in the sparse matrix form, use array of structures.
c. Print the final array.
2. Create a linked list with nodes having information about a student and perform
a. Insert a new node at specified position.
b. Delete of a node with the roll number of student specified.
c. Reversal of that linked list.
3. Create doubly linked list with nodes having information about an employee and perform
Insertion at front of doubly linked list and perform deletion at end of that doubly linked list.
4. Create circular linked list having information about a college and perform Insertion at front
perform
Deletion at end.
5. Implement two stacks in a using single array.
6. Create a stack and perform Push, Pop, Peek and Traverse operations on the stack using Linked
list.
7. Create a Linear Queue using Linked List and implement different operations such as Insert,
Delete, and
Display the queue elements.
8. Implement Experiment-2 using liked list.
9. Create a Binary Tree and perform Tree traversals (Preorder, Postorder, Inorder) using the
concept of recursion.
10. Implement insertion, deletion and traversals (inorder, preorder and postorder) on binary search
tree with the information in the tree about the details of an automobile (type, company, year of
make).
11. Implement Selection Sort, Bubble Sort, Insertion sort, Merge sort, Quick sort, and Heap Sort
using array as a data structure.
12. Perform Linear Search and Binary Search on an array. Description of programs:
a. Read an array of type integer.
b. Input element from user for searching.
c. Search the element by passing the array to a function and then returning the position of the
element from the function else return -1 if the element is not found. d. Display the position
where the element has been found.
13. Implement the searching using hashing method.
14. Create a graph and perform DFS and BFS traversals.
INDEX
S.No Experiment Marks Date of Date of Signature
Performance Checking

10

11

12

13

14

15

16

17

18
19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38
Practical-

Aim: Write a program to merge two arrays(sorted in ascending order) and create a ghird

array sorted in ascending order.

Software Used: Visual Studio Code

Algorithm:

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

// Function to merge two sorted arrays into a third sorted array


void mergeArrays(int arr1[], int arr2[], int n1, int n2, int arr3[]) {
int i = 0, j = 0, k = 0;

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


if (arr1[i] <= arr2[j]) {
arr3[k++] = arr1[i++];
} else { arr3[k++] =
arr2[j++];
}
}
while (i < n1) {
arr3[k++] = arr1[i++];
}

while (j < n2) {


arr3[k++] = arr2[j++];
}
}

int main() {
int n1, n2;

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

cout << "Enter the number of elements in the second sorted array: ";
cin >> n2;
int arr2[n2]; cout << "Enter elements of the second sorted array in
ascending order:\n"; for (int i = 0; i < n2; i++) {
cin >> arr2[i];
} int arr3[n1 + n2];

mergeArrays(arr1, arr2, n1, n2, arr3);

cout << "Merged array: "; for


(int i = 0; i < n1 + n2; i++) {
cout << arr3[i] << " ";
} cout <<
endl; return
0;
}

Output:
Practical-

Aim: In a sales company, there are 5 salesman and each salesman is supposed to sell 3
product. WAP using 2D array to print the total sales by each salesman and the total
sales of each item.

Software Used: Visual Studio Code

Algorithm:

Source Code:

#include <iostream>
using namespace std;
int main() {
const int salesmen = 5;
const int products = 3; int
sales[salesmen][products];

cout << "Enter the sales data for 5 salesmen and 3 products:\n";
for (int i = 0; i < salesmen; i++) { cout << "Salesman " << i + 1
<< ":\n"; for (int j = 0; j < products; j++) {
cout << "Product " << j + 1 << ": ";
cin >> sales[i][j];
}
}

cout << "\nTotal sales by each salesman:\n";


for (int i = 0; i < salesmen; i++) { int
totalSalesman = 0; for (int j = 0; j <
products; j++) {
totalSalesman += sales[i][j];
} cout << "Salesman " << i + 1 << ": " << totalSalesman <<
endl;
}

cout << "\nTotal sales of each product:\n";


for (int j = 0; j < products; j++) {
int totalProduct = 0; for (int i =
0; i < salesmen; i++) {
totalProduct += sales[i][j];
} cout << "Product " << j + 1 << ": " << totalProduct <<
endl;
}

return 0;
}
Output:
Practical-

Aim: Write a program to perform addition, subtraction and multiplication of 2D array

Software Used: Visual Studio Code

Algorithm:
Source Code:

#include <iostream>
using namespace std;

int rows = 3;
int cols = 3;

void addMatrices(int A[rows][cols], int B[rows][cols], int result[rows][cols]) {


for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
result[i][j] = A[i][j] + B[i][j];
}
}
}

void subtractMatrices(int A[rows][cols], int B[rows][cols], int result[rows][cols]) {


for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
result[i][j] = A[i][j] - B[i][j];
}
}
}

void multiplyMatrices(int A[rows][cols], int B[rows][cols], int result[rows][cols]) {


for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
result[i][j] = 0;
for (int k = 0; k < cols; k++) {
result[i][j] += A[i][k] * B[k][j];
}
}
}
}
void printMatrix(int matrix[rows][cols]) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
cout << matrix[i][j] << "\t";
} cout <<
endl;
}
}

int main() {
int A[rows][cols], B[rows][cols], result[rows][cols];

cout << "Enter elements of the first 3x3 matrix (A):\n";


for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
cin >> A[i][j];
}
}

cout << "Enter elements of the second 3x3 matrix (B):\n";


for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
cin >> B[i][j];
}
}

addMatrices(A, B, result); cout <<


"\nMatrix after addition:\n";
printMatrix(result);

subtractMatrices(A, B, result); cout <<


"\nMatrix after subtraction:\n";
printMatrix(result);
multiplyMatrices(A, B, result); cout <<
"\nMatrix after multiplication:\n";
printMatrix(result);

return 0;
}
Output:
Practical-

Aim: Write a program to fill a square matrix with '0' in diagonal, '1' in upper triangle and
'-1' in lower triangle

Software Used: Visual Studio Code

Algorithm:

Source Code:

#include <iostream>
using namespace std;

int main() {
int n;

cout << "Enter the size of the square matrix: ";


cin >> n;
int matrix[n][n]; for (int i
= 0; i < n; i++) { for (int j
= 0; j < n; j++) { if (i ==
j) { matrix[i][j] = 0;
} else if (i < j) {
matrix[i][j] = 1;
} else {
matrix[i][j] = -
1;
}
}
}

cout << "\nThe matrix is:\n";


for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cout << matrix[i][j] << "\t";
} cout <<
endl; }

return 0;
}

Output:
Practical-

Aim: Write a program to perform binary search in an array.

Software Used: Visual Studio Code

Algorithm:

Source Code:

#include <iostream>
using namespace std;

int binarySearch(int arr[], int size, int key) {


int low = 0, high = size - 1;

while (low <= high) { int mid =


low + (high - low) / 2; if
(arr[mid] == key) return mid;
else if (arr[mid] < key)
low = mid + 1;
else
high = mid - 1;
} return -
1; }

int main() {
int size, key;

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


cin >> size;

int arr[size];

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


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

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


cin >> key; int result =
binarySearch(arr, size, key);

if (result != -1)
cout << "Element found at index " << result << endl;
else
cout << "Element not found" << endl;

return 0;
}
Output:
Practical-

Aim: Create two arrays and merge them into third one in sorted manner

Software Used: Visual Studio Code

Algorithm:

Source Code:

#include <iostream>
using namespace std;

void mergeArrays(int arr1[], int n1, int arr2[], int n2, int arr3[]) {
for (int i = 0; i < n1; i++) arr3[i] = arr1[i]; for
(int i = 0; i < n2; i++) arr3[n1 + i] = arr2[i];

// Sorting the merged array for (int


i = 0; i < n1 + n2 - 1; i++) {
for (int j = i + 1; j < n1 + n2; j++)
{ if (arr3[i] > arr3[j]) { int temp
= arr3[i]; arr3[i] = arr3[j]; arr3[j]
= temp;
}
}
}
}

int main() {
int n1, n2; cout << "Enter size of
first array: "; cin >> n1;
int arr1[n1]; cout << "Enter elements of
first array:\n"; for (int i = 0; i < n1; i++)
cin >> arr1[i];

cout << "Enter size of second array: ";


cin >> n2;
int arr2[n2]; cout << "Enter elements of
second array:\n"; for (int i = 0; i < n2; i++)
cin >> arr2[i];

int arr3[n1 + n2]; mergeArrays(arr1,


n1, arr2, n2, arr3);

cout << "Merged and sorted array:\n"; for (int i = 0; i


< n1 + n2; i++) cout << arr3[i] << " "; cout << endl;
return 0;
}
Output:
Practical-

Aim: Write a program to find all the subarrays having sum zero

Software Used: Visual Studio Code

Algorithm:

Source Code:

#include <iostream>
using namespace std;

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


for (int i = 0; i < n; i++) {
int sum = 0; for (int j = i;
j < n; j++) {
sum += arr[j];
if (sum == 0) {
cout << "Subarray with sum zero found from index " << i << " to " << j <<
endl;
}
}
}
}
int main() {
int n; cout << "Enter size of
array: "; cin >> n; int arr[n];

cout << "Enter array elements: "; for


(int i = 0; i < n; i++) cin >> arr[i];
findSubarrays(arr, n);

return 0;
}

Output:
Practical-

Aim: Write a program to implement stack using arrays

Software Used: Visual Studio Code

Algorithm:

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

class Stack {
int top;
public:
int arr[MAX]; Stack() { top = -
1; } void push(int x) { if (top <
MAX - 1) arr[++top] = x; else
cout << "Stack Overflow\n";
} int pop()
{
return (top >= 0) ? arr[top--] : -1;

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

}
};

int main() { Stack s; int n, val; cout << "Enter


number of elements to push: "; cin >> n; for
(int i = 0; i < n; i++) {
cout << "Enter value: ";
cin >> val;
s.push(val); } cout << "Popped element: " <<
s.pop() << endl; return 0;
}

Output:
Practical-

Aim: Write a program to implement queue using arrays

Software Used: Visual Studio Code

Algorithm:

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

class Queue {
int front, rear;
int arr[MAX];
public:
Queue() { front = -1;
rear = -1;

} void enqueue(int x)
{ if (rear < MAX - 1)
arr[++rear] = x; else
cout << "Queue Overflow\n";

} int dequeue()
{
return (front < rear) ? arr[++front] : -1;

} bool isEmpty()
{
return front == rear;

}
};

int main() { Queue q; int n, val; cout << "Enter


number of elements to enqueue: "; cin >> n; for
(int i = 0; i < n; i++) {
cout << "Enter value: ";
cin >> val;
q.enqueue(val); } cout << "Dequeued element: " <<
q.dequeue() << endl; return 0;
}

Output:
Practical-

Aim: Write a program to create a linked list and reverse it

Software Used: Visual Studio Code

Algorithm:

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

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

// Function to insert a new node at the beginning of the list


void insertAtBeginning(Node** head_ref, int new_data) {
Node* new_node = new Node();
new_node->data = new_data; new_node-
>next = *head_ref;
*head_ref = new_node;
}

// Function to reverse the linked list


Node* reverseList(Node* head) {
Node* prev = NULL;
Node* current = head;
Node* next = NULL;

while (current != NULL) {


next = current->next; // Store next node current->next
= prev; // Reverse current node's pointer prev = current;
// Move pointers one position ahead current = next; }
return prev; // New head is the previous node
}

// Function to print the linked


list void printList(Node* node)
{ while (node != NULL) { cout
<< node->data << " "; node =
node->next;
} cout <<
endl; }

int main() {
Node* head = NULL;
int n, value;
// Creating linked list cout <<
"Enter number of nodes: "; cin >>
n; for (int i = 0; i < n; i++) {
cout << "Enter value for node " << i+1 << ": ";
cin >> value; insertAtBeginning(&head, value);
//Insert at the beginning
}

cout << "Original List: ";


printList(head);

// Reversing the linked list

head = reverseList(head);

cout <<
"Reversed
List: ";
printList(head
);

return 0;
}

Output:
Practical-

Aim: Write a program to implement two stacks using single array

Software Used: Visual Studio Code

Algorithm:

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

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;

} void push2(int x) {
if (top1 < top2 - 1)
arr[--top2] = x;

} int pop1() { return (top1 >= 0) ?


arr[top1--] : -1; }
int pop2() {
return (top2 < MAX) ? arr[top2++] : -1; }
};

int main() { TwoStacks ts; int n, val; cout <<


"Enter number of elements for stack1: "; cin >>
n; for (int i = 0; i < n; i++) {
cout << "Enter value: ";
cin >> val;
ts.push1(val); } cout << "Popped from stack1: " <<
ts.pop1() << endl;

cout << "Enter number of elements for stack2: ";


cin >> n; for (int i = 0; i < n; i++) {
cout << "Enter value: ";
cin >> val;
ts.push2(val); } cout << "Popped from stack2: " <<
ts.pop2() << endl; return 0;
}

Output:
Practical-

Aim: Write a program to create linked list and find the count of duplicate elements (if
any)

Software Used: Visual Studio Code

Algorithm:

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

struct Node {
int data;
Node* next;
};
void insertAtEnd(Node** head_ref, int new_data)
{ Node* new_node = new Node(); new_node-
>data = new_data; new_node->next = NULL;
if (*head_ref == NULL) {
*head_ref = new_node;
return;
}

Node* last = *head_ref;


while (last->next != NULL) {
last = last->next;
}

last->next = new_node;
}

int countDuplicates(Node* head)


{ Node* current = head; int
duplicates = 0;

while (current != NULL) {


Node* runner = current->next;
while (runner != NULL) {
if (current->data == runner->data) {
duplicates++;
break; } runner =
runner->next;
}
current = current->next;
}

return duplicates;
}
void printList(Node* node) {
while (node != NULL) {
cout << node->data << " ";
node = node->next;
}
cout << endl;
}

int main() {
Node* head = NULL;
int n, value;

cout << "Enter number of nodes: ";


cin >> n; for (int i = 0; i < n; i++)
{
cout << "Enter value for node " << i + 1 << ": ";
cin >> value;
insertAtEnd(&head, value);
}

cout << "Linked List: ";


printList(head);

int duplicateCount = countDuplicates(head); cout << "Number of


duplicate elements: " << duplicateCount << endl;

return 0;
}
Output:
Practical-

Aim: Write a program to create a stack and perform push, pop, peek and traverse
operations on the stack using a linked list.

Software Used: Visual Studio Code

Algorithm:

Source Code:
#include <iostream>
using namespace
std; struct Node { int
data;
Node* next;
}; class
Stack {
private:
Node* top;
public:
Stack() { top =
nullptr; }
void push(int value) {
Node* newNode = new
Node(); newNode->data =
value; newNode->next = top;
top = newNode;
cout << "Pushed: " << value << endl;
} void pop()
{
if (top == nullptr) {
cout << "Stack Underflow!" << endl;
return;
}
Node* temp = top; top = top->next; cout
<< "Popped: " << temp->data << endl; delete
temp; } void peek() {
if (top == nullptr) {
cout << "Stack is empty!" << endl;
} else { cout << "Top element is: " << top->data
<< endl;
} } void
traverse() {
if (top == nullptr) {
cout << "Stack is empty!" << endl;
return;
}
Node* temp = top; cout <<
"Stack elements: "; while
(temp != nullptr) { cout <<
temp->data << " "; temp =
temp->next;
}
cout << endl;
}
}; int main() {
Stack stack;

stack.push(10);
stack.push(20);
stack.push(30);
stack.peek();
stack.traverse();
stack.pop();
stack.peek();

stack.traverse()
; return 0; }

Output:
Practical-

Aim: Write a program to create a circular linked list having information about a college
and perform insertion at front and deletion at end.

Software Used: Visual Studio Code

Algorithm:

Source Code:
#include <iostream>
#include <string>
using namespace
std; struct Node {
string name; string
department; int year;
Node* next;
};
class CircularLinkedList {
private:
Node* last;
public:

CircularLinkedList() {
last = nullptr;
}

void insertFront(string name, string dept, int year) {


Node* newNode = new Node(); newNode-
>name = name; newNode->department = dept;
newNode->year = year;

if (last == nullptr) { newNode-


>next = newNode; last =
newNode;
} else { newNode->next = last-
>next; last->next =
newNode;
} cout << "Inserted at front: " << name << ", " << dept << ", " << year <<
endl;
}

void deleteEnd() {
if (last == nullptr) {
cout << "List is empty!" << endl;
return; } if (last-
>next == last) {
cout << "Deleted: " << last->name << ", " << last->department << ", " <<
last->year << endl;
delete last;
last = nullptr;
}
else {
Node*
temp =
last-
>next;
while
(temp-
>next !=
last) {
temp = temp->next;
}

temp->next = last->next; cout << "Deleted: " << last->name << ", " <<
last->department << ", " <<
last->year << endl;
delete last;
last = temp;
} } void display() {
if (last == nullptr) {
cout << "List is empty!" << endl;
return;
}

Node* temp = last->next; cout <<


"Circular Linked List:" << endl; do {
cout << temp->name << ", " << temp->department << ", " << temp->year <<
endl; temp = temp->next;
} while (temp != last->next);
}
};

int main() {
CircularLinkedList cll;
cll.insertFront("MAIT", "Electrical", 1999);
cll.insertFront("DTU", "Computer Science", 1941);
cll.insertFront("NSUT”, "Mechanical", 1983);
cll.display(); cll.deleteEnd(); cll.display();
cll.deleteEnd();
cll.display();

return 0;
}

Output:
Practical-

Aim: Write a program to create a doubly linked list having information about an
employee and perform insertion at front and deletion at the end

Software Used: Visual Studio Code

Algorithm:

Source Code:
#include <iostream>
#include <string>
using namespace std;
struct Node {
string name; int
id;
string department;
Node* prev;
Node* next;
}; class
DoublyLinkedList {
private:
Node* head;
Node* tail;
public:
DoublyLinkedList() {
head = nullptr; tail
= nullptr;
} void insertFront(string name, int id, string
dept) { Node* newNode = new Node();
newNode->name = name; newNode->id = id;
newNode->department = dept; newNode->prev
= nullptr; newNode->next = head; if (head !=
nullptr) {
head->prev = newNode;
} else { tail =
newNode;
} head = newNode; cout << "Inserted at front: " << name << ", " << id <<
", " << dept << endl;
} void deleteEnd()
{
if (tail == nullptr) {
cout << "List is empty!" << endl;
return;
}
Node* temp = tail;
if (head == tail) {
head = nullptr;
tail = nullptr;
} else { tail = tail-
>prev; tail->next =
nullptr;
} cout << "Deleted from end: " << temp->name << ", " << temp->id << ", "
<<
temp->department << endl;
delete temp;
} void display()
{
if (head == nullptr) {
cout << "List is empty!" << endl;
return;
}
Node* temp = head; cout << "Doubly Linked List:" << endl; while (temp !=
nullptr) { cout << temp->name << ", " << temp->id << ", " << temp->department
<< endl; temp = temp->next;
}
}
}; int
main() {
DoublyLinkedList dll;
dll.insertFront("Aman", 101, "HR");
dll.insertFront("Shankar", 102, "Finance");
dll.insertFront("Alisha", 103, "Engineering");
dll.display(); dll.deleteEnd(); dll.display();
dll.deleteEnd(); dll.display(); return 0;
}
Output:
Practical-

Aim: Write a program to create a linked list with nodes having info about a student and
perform:
(a) insertion of new node at a specified position
(b)deletion of node with specified roll number
(c) reversal of linked list Software

Used: Visual Studio Code

Algorithm:
Source Code:
#include <iostream>
#include <string>

using namespace std;

struct StudentNode
{ int rollNo;
string name;
StudentNode* next;

StudentNode(int r, string n) : rollNo(r), name(n), next(nullptr) {}


};

void insertAtPosition(StudentNode*& head, int position, int rollNo, string name)


{ StudentNode* newNode = new StudentNode(rollNo, name); if (position == 0)
{ newNode->next = head; head = newNode;
return;
}

StudentNode* temp = head; for (int i = 0; i < position -


1 && temp != nullptr; ++i) {
temp = temp->next;
} if (temp == nullptr) { cout << "Position
out of range." << endl; delete newNode;
return; } newNode->next =
temp->next; temp->next =
newNode;
}

void deleteByRollNo(StudentNode*& head, int rollNo) {


StudentNode* temp = head;
StudentNode* prev = nullptr;
while (temp != nullptr && temp->rollNo != rollNo) {
prev = temp; temp
= temp->next;
}

if (temp == nullptr) {
cout << "Roll number not found." << endl;
return; }

if (prev == nullptr) {
head = temp->next;
} else { prev->next = temp-
>next;
}

delete temp;
}

void reverse(StudentNode*& head) {


StudentNode* prev = nullptr;
StudentNode* current = head;
StudentNode* next = nullptr;

while (current != nullptr) {


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

void display(StudentNode* head) {


StudentNode* temp = head;
while (temp != nullptr) {
cout << "Roll No: " << temp->rollNo << ", Name: " << temp->name << endl;
temp = temp->next;
}
}

int main() {
StudentNode* head = nullptr;
int choice, position, rollNo;
string name;

while (true) {
cout << "\nMenu:\n"; cout << "1.
Insert at Position\n"; cout << "2.
Delete by Roll No\n"; cout <<
"3. Reverse List\n"; cout << "4.
Display List\n"; cout << "5.
Exit\n"; cout << "Enter your
choice: "; cin >> choice;

switch (choice) {
case 1:
cout << "Enter position: "; cin >> position; cout
<< "Enter roll number: "; cin >> rollNo; cout <<
"Enter name: "; cin.ignore(); // To ignore leftover
newline character getline(cin, name);
insertAtPosition(head, position, rollNo, name);
break;

case 2:
cout << "Enter roll number to delete:
"; cin >> rollNo; deleteByRollNo(head,
rollNo); break; case 3:
reverse(head); cout << "List
reversed." << endl; break;
case 4:
display(head);
break;

case 5:
while (head != nullptr) {
StudentNode* temp = head;
head = head->next; delete
temp; } return 0;

default:
cout << "Invalid choice. Try again." << endl;
}
}

return 0;
}
Output:
Practical-

Aim: Write a program to create a linear queue using linked list and implement
insertion, deletion and display.
Software Used: Visual Studio Code

Algorithm:
Source Code:

#include <iostream>
using namespace std;

// Node structure for the queue


struct Node {
int data;
Node* next;

Node(int val) : data(val), next(nullptr) {}


};

// Queue class using linked list


class Queue {
private:
Node* front; // Pointer to the front of the queue
Node* rear; // Pointer to the rear of the queue

public:
// Constructor to initialize the queue
Queue() : front(nullptr), rear(nullptr) {}

// Function to insert an element (enqueue)


void enqueue(int value) {
Node* newNode = new Node(value);

if (rear == nullptr) { // If the queue is empty


front = rear = newNode;
cout << value << " enqueued into the queue." << endl;
return;
}

// Add the new node at the end and update the rear
rear->next = newNode;
rear = newNode;
cout << value << " enqueued into the queue." << endl;
}

// Function to delete an element (dequeue)


void dequeue() {
if (front == nullptr) { // If the queue is empty
cout << "Queue is empty, nothing to dequeue." << endl;
return;
}

// Remove the front node and update the front pointer


Node* temp = front;
front = front->next;

// If the queue becomes empty after the operation


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

cout << "Dequeued " << temp->data << " from the queue." << endl;
delete temp; // Free the memory of the dequeued node
}

// Function to display the queue


void display() const {
if (front == nullptr) { // If the queue is empty
cout << "Queue is empty." << endl;
return;
}

Node* temp = front;


cout << "Queue elements: ";
while (temp != nullptr) {
cout << temp->data << " ";
temp = temp->next;
}
cout << endl;
}

// Destructor to clean up the allocated memory


~Queue() {
while (front != nullptr) {
Node* temp = front;
front = front->next;
delete temp;
}
}
};

// Main function to demonstrate queue operations


int main() {
Queue q;
int choice, value;

while (true) {
cout << "\nMenu:\n";
cout << "1. Enqueue\n";
cout << "2. Dequeue\n";
cout << "3. Display Queue\n";
cout << "4. Exit\n";
cout << "Enter your choice: ";
cin >> choice;

switch (choice) {
case 1:
cout << "Enter value to enqueue: ";
cin >> value;
q.enqueue(value);
break;

case 2:
q.dequeue();
break;

case 3:
q.display();
break;

case 4:
cout << "Exiting..." << endl;
return 0;

default:
cout << "Invalid choice. Please try again." << endl;
}
}

return 0;
}
Output:
Practical-

Aim: Write a program to implement Sparse Matrix using linked list.


Software Used: Visual Studio Code

Algorithm:

Source Code:

#include <iostream>
using namespace std;
// Node structure for the sparse matrix
struct Node {
int row; // Row index
int col; // Column index
int value; // Non-zero value
Node* next; // Pointer to the next node

// Constructor to initialize node


Node(int r, int c, int val) : row(r), col(c), value(val), next(nullptr) {}
};

// SparseMatrix class using linked list


class SparseMatrix {
private:
Node* head; // Pointer to the head of the linked list

public:
// Constructor to initialize an empty sparse matrix
SparseMatrix() : head(nullptr) {}

// Function to insert a new non-zero element into the sparse matrix


void insert(int r, int c, int val) {
if (val == 0) return; // Only store non-zero elements

Node* newNode = new Node(r, c, val);

if (head == nullptr) { // If the list is empty


head = newNode;
} else {
// Insert at the end of the linked list
Node* temp = head;
while (temp->next != nullptr) {
temp = temp->next;
}
temp->next = newNode;
}
}
// Function to display the sparse matrix in row-column-value format
void display() const {
if (head == nullptr) {
cout << "The sparse matrix is empty." << endl;
return;
}

Node* temp = head;


cout << "Row\tCol\tValue\n";
while (temp != nullptr) {
cout << temp->row << "\t" << temp->col << "\t" << temp->value << endl;
temp = temp->next;
}
}

// Function to print the full matrix representation (with zeroes)


void displayFullMatrix(int totalRows, int totalCols) const {
Node* temp = head;
for (int i = 0; i < totalRows; ++i) {
for (int j = 0; j < totalCols; ++j) {
if (temp != nullptr && temp->row == i && temp->col == j) {
cout << temp->value << " "; // Print non-zero value
temp = temp->next; // Move to the next node
} else {
cout << "0 "; // Print zero
}
}
cout << endl;
}
}

// Destructor to free up memory


~SparseMatrix() {
Node* temp;
while (head != nullptr) {
temp = head;
head = head->next;
delete temp;
}
}
};

// Main function to demonstrate the sparse matrix operations


int main() {
SparseMatrix sm;
int rows, cols, nonZeroElements;

// Get matrix dimensions and non-zero elements


cout << "Enter number of rows: ";
cin >> rows;
cout << "Enter number of columns: ";
cin >> cols;
cout << "Enter number of non-zero elements: ";
cin >> nonZeroElements;

// Input non-zero elements


for (int i = 0; i < nonZeroElements; ++i) {
int r, c, val;
cout << "Enter row index, column index, and value of non-zero element " << i + 1 << ": ";
cin >> r >> c >> val;
sm.insert(r, c, val);
}

// Display sparse matrix in row-column-value format


cout << "\nSparse Matrix (Row-Column-Value format):" << endl;
sm.display();

// Display full matrix (including zeroes)


cout << "\nFull Matrix Representation:" << endl;
sm.displayFullMatrix(rows, cols);

return 0;
}
Output:
Practical-

Aim: Write a program to binary tree and Traverse (pre-order, in-order, post-order)
using recursion.
Software Used: Visual Studio Code

Algorithm:

Source Code:

#include <iostream>
using namespace std;
// Node structure for the binary tree
struct Node {
int data;
Node* left;
Node* right;

// Constructor to initialize node


Node(int value) : data(value), left(nullptr), right(nullptr) {}
};

// Binary Tree class


class BinaryTree {
public:
Node* root; // Pointer to the root of the tree

// Constructor to initialize the binary tree


BinaryTree() : root(nullptr) {}

// Function to insert nodes in the binary tree


Node* insert(Node* node, int value) {
if (node == nullptr) {
// If the node is null, create a new node
return new Node(value);
}
if (value < node->data) {
node->left = insert(node->left, value); // Insert in the left subtree
} else if (value > node->data) {
node->right = insert(node->right, value); // Insert in the right subtree
}
return node;
}

// Pre-order Traversal (Root -> Left -> Right)


void preOrder(Node* node) {
if (node == nullptr) {
return;
}
cout << node->data << " "; // Visit the root
preOrder(node->left); // Traverse the left subtree
preOrder(node->right); // Traverse the right subtree
}

// In-order Traversal (Left -> Root -> Right)


void inOrder(Node* node) {
if (node == nullptr) {
return;
}
inOrder(node->left); // Traverse the left subtree
cout << node->data << " "; // Visit the root
inOrder(node->right); // Traverse the right subtree
}

// Post-order Traversal (Left -> Right -> Root)


void postOrder(Node* node) {
if (node == nullptr) {
return;
}
postOrder(node->left); // Traverse the left subtree
postOrder(node->right); // Traverse the right subtree
cout << node->data << " "; // Visit the root
}
};

// Main function
int main() {
BinaryTree tree;

// Insert nodes into the binary tree


tree.root = tree.insert(tree.root, 50);
tree.insert(tree.root, 30);
tree.insert(tree.root, 70);
tree.insert(tree.root, 20);
tree.insert(tree.root, 40);
tree.insert(tree.root, 60);
tree.insert(tree.root, 80);
cout << "Pre-order traversal: ";
tree.preOrder(tree.root); // Pre-order traversal
cout << endl;

cout << "In-order traversal: ";


tree.inOrder(tree.root); // In-order traversal
cout << endl;

cout << "Post-order traversal: ";


tree.postOrder(tree.root); // Post-order traversal
cout << endl;

return 0;
}

Output:
Practical-

Aim: Write a program to binary search tree with information about automobile and
perform insertion, deletion and traversal.
Software Used: Visual Studio Code

Algorithm:

Source Code:

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

// Structure for automobile information


struct Automobile {
string modelName;
int yearOfManufacture;
double price;

Automobile() : modelName(""), yearOfManufacture(0), price(0.0) {} // Default constructor


Automobile(string name, int year, double cost) : modelName(name), yearOfManufacture(year),
price(cost) {}
};

// Structure for Binary Search Tree Node


struct TreeNode {
Automobile autoInfo;
TreeNode* left;
TreeNode* right;

// Constructor to initialize node with automobile information


TreeNode(Automobile info) : autoInfo(info), left(nullptr), right(nullptr) {}
};

// Binary Search Tree Class


class BST {
public:
TreeNode* root;

// Constructor to initialize the tree


BST() : root(nullptr) {}

// Insert automobile information into the BST


TreeNode* insert(TreeNode* node, Automobile autoInfo) {
if (node == nullptr) {
// If the node is null, create a new node with the automobile info
return new TreeNode(autoInfo);
}
// Insert based on year of manufacture
if (autoInfo.yearOfManufacture < node->autoInfo.yearOfManufacture) {
node->left = insert(node->left, autoInfo); // Insert in the left subtree
} else if (autoInfo.yearOfManufacture > node->autoInfo.yearOfManufacture) {
node->right = insert(node->right, autoInfo); // Insert in the right subtree
} else {
cout << "Duplicate entry for year " << autoInfo.yearOfManufacture << endl;
}
return node;
}

// Find the minimum node in the right subtree (used for deletion)
TreeNode* findMin(TreeNode* node) {
while (node->left != nullptr) {
node = node->left;
}
return node;
}

// Delete a node by year of manufacture


TreeNode* deleteNode(TreeNode* node, int year) {
if (node == nullptr) {
return node;
}
// Traverse the tree to find the node to delete
if (year < node->autoInfo.yearOfManufacture) {
node->left = deleteNode(node->left, year);
} else if (year > node->autoInfo.yearOfManufacture) {
node->right = deleteNode(node->right, year);
} else {
// Node found
if (node->left == nullptr && node->right == nullptr) {
delete node;
return nullptr;
} else if (node->left == nullptr) {
TreeNode* temp = node->right;
delete node;
return temp;
} else if (node->right == nullptr) {
TreeNode* temp = node->left;
delete node;
return temp;
} else {
TreeNode* temp = findMin(node->right); // Find the smallest node in the right subtree
node->autoInfo = temp->autoInfo; // Replace node's data with that of the smallest node
node->right = deleteNode(node->right, temp->autoInfo.yearOfManufacture); // Delete
the duplicate node
}
}
return node;
}

// In-order Traversal (Left -> Root -> Right)


void inOrder(TreeNode* node) {
if (node == nullptr) {
return;
}
inOrder(node->left);
displayNode(node);
inOrder(node->right);
}

// Pre-order Traversal (Root -> Left -> Right)


void preOrder(TreeNode* node) {
if (node == nullptr) {
return;
}
displayNode(node);
preOrder(node->left);
preOrder(node->right);
}

// Post-order Traversal (Left -> Right -> Root)


void postOrder(TreeNode* node) {
if (node == nullptr) {
return;
}
postOrder(node->left);
postOrder(node->right);
displayNode(node);
}

// Display a single node's automobile information


void displayNode(TreeNode* node) {
cout << "Model: " << node->autoInfo.modelName
<< ", Year: " << node->autoInfo.yearOfManufacture
<< ", Price: " << node->autoInfo.price << endl;
}
};

// Main function
int main() {
BST tree; // Create a Binary Search Tree
int choice, year;
string modelName;
double price;

while (true) {
cout << "\nMenu:\n";
cout << "1. Insert Automobile\n";
cout << "2. Delete Automobile by Year of Manufacture\n";
cout << "3. In-order Traversal\n";
cout << "4. Pre-order Traversal\n";
cout << "5. Post-order Traversal\n";
cout << "6. Exit\n";
cout << "Enter your choice: ";
cin >> choice;

switch (choice) {
case 1:
cout << "Enter Model Name: ";
cin.ignore();
getline(cin, modelName);
cout << "Enter Year of Manufacture: ";
cin >> year;
cout << "Enter Price: ";
cin >> price;
tree.root = tree.insert(tree.root, Automobile(modelName, year, price));
break;

case 2:
cout << "Enter Year of Manufacture to delete: ";
cin >> year;
tree.root = tree.deleteNode(tree.root, year);
break;

case 3:
cout << "In-order Traversal:\n";
tree.inOrder(tree.root);
break;

case 4:
cout << "Pre-order Traversal:\n";
tree.preOrder(tree.root);
break;

case 5:
cout << "Post-order Traversal:\n";
tree.postOrder(tree.root);
break;

case 6:
exit(0);

default:
cout << "Invalid choice. Please try again.\n";
}
}

return 0;
}
Output:
Practical-

Aim: Write a program to remove a loop from linked list.


Software Used: Visual Studio Code

Algorithm:

Source Code:

#include <iostream>
using namespace std;
// Node structure for linked list
struct Node {
int data;
Node* next;
Node(int value) : data(value), next(nullptr) {}
};

// Function to detect and remove loop in the linked list


void removeLoop(Node* head) {
if (head == nullptr || head->next == nullptr)
return;

Node* slow = head;


Node* fast = head;

// Detect loop using Floyd’s Cycle-Finding Algorithm


while (fast != nullptr && fast->next != nullptr) {
slow = slow->next; // Move slow pointer by 1
fast = fast->next->next; // Move fast pointer by 2

if (slow == fast) { // If slow and fast meet, loop is detected


break;
}
}

// If loop exists
if (slow == fast) {
// Move one pointer to head and keep the other at the meeting point
slow = head;

// Special case when the loop is at the start


if (slow == fast) {
while (fast->next != slow) {
fast = fast->next;
}
} else {
// Move both pointers one step at a time until they meet at the loop start
while (slow->next != fast->next) {
slow = slow->next;
fast = fast->next;
}
}

// Break the loop by setting the next of the loop-end node to nullptr
fast->next = nullptr;
}
}

// Function to insert a node at the end of the linked list


void insert(Node*& head, int value) {
Node* newNode = new Node(value);
if (head == nullptr) {
head = newNode;
return;
}

Node* temp = head;


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

// Function to create a loop in the linked list (for testing purposes)


void createLoop(Node* head, int k) {
if (head == nullptr) return;

Node* temp = head;


Node* loopNode = nullptr;
int count = 1;

// Traverse to the kth node


while (temp->next != nullptr) {
if (count == k) {
loopNode = temp; // Store the kth node to create a loop later
}
temp = temp->next;
count++;
}

// Link the last node to the kth node to create a loop


temp->next = loopNode;
}

// Function to display the linked list


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

// Main function
int main() {
Node* head = nullptr;

// Creating a linked list: 10 -> 20 -> 30 -> 40 -> 50 -> 60 -> NULL
insert(head, 10);
insert(head, 20);
insert(head, 30);
insert(head, 40);
insert(head, 50);
insert(head, 60);

// Display the original list


cout << "Original list: ";
display(head);

// Create a loop for testing: 60 -> 30


createLoop(head, 3);

// Detect and remove the loop


removeLoop(head);

// Display the list after removing the loop


cout << "List after removing loop: ";
display(head);

return 0;
}

Output:
Practical-

Aim: Write a program to segregate even and odd node in linked list.
Software Used: Visual Studio Code

Algorithm:

Source Code:

#include <iostream>
using namespace std;
// Node structure for linked list
struct Node {
int data;
Node* next;
Node(int value) : data(value), next(nullptr) {}
};

// Function to append a node to the end of the linked list


void append(Node*& head, int value) {
Node* newNode = new Node(value);
if (head == nullptr) {
head = newNode;
return;
}
Node* temp = head;
while (temp->next != nullptr) {
temp = temp->next;
}
temp->next = newNode;
}

// Function to segregate even and odd nodes in the linked list


void segregateEvenOdd(Node*& head) {
if (head == nullptr) return;

Node* evenHead = nullptr;


Node* oddHead = nullptr;
Node* evenTail = nullptr;
Node* oddTail = nullptr;

Node* current = head;


while (current != nullptr) {
if (current->data % 2 == 0) {
if (evenHead == nullptr) {
evenHead = evenTail = current;
} else {
evenTail->next = current;
evenTail = evenTail->next;
}
} else {
if (oddHead == nullptr) {
oddHead = oddTail = current;
} else {
oddTail->next = current;
oddTail = oddTail->next;
}
}
current = current->next;
}

// Terminate the end of the last lists


if (evenTail != nullptr) {
evenTail->next = oddHead;
}
if (oddTail != nullptr) {
oddTail->next = nullptr;
}

// Set the new head of the list


head = evenHead;
}

// Function to display the linked list


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

// Main function
int main() {
Node* head = nullptr;
// Creating a linked list: 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> NULL
append(head, 1);
append(head, 2);
append(head, 3);
append(head, 4);
append(head, 5);
append(head, 6);
append(head, 7);

// Display the original list


cout << "Original list: ";
display(head);

// Segregate even and odd nodes


segregateEvenOdd(head);

// Display the segregated list


cout << "List after segregating even and odd nodes: ";
display(head);

return 0;
}

Output:

You might also like