0% found this document useful (0 votes)
3 views27 pages

Lab Manual - 5th Sem - DS C++

Uploaded by

adnagaprasad
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)
3 views27 pages

Lab Manual - 5th Sem - DS C++

Uploaded by

adnagaprasad
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/ 27

Visvesvaraya Technological University

Belagavi, Karnataka-590 018

Data Structures Using C++ Laboratory Manual


(21EC584)
for
Vth Semester
Bachelor of Engineering

Department of Electronics and Communication Engineering


SDM Institute of Technology, Ujire-574240
Course Data Structures using C++
Course Code 21EC584
Semester 5th CIE marks 50
Teaching Hours/Week (L: T:P: S) 0:0:2:0 SEE 50
Marks
Experiments
Course objectives:
 Understand object-oriented programming concepts, and apply them in solving
problems.
 To create, debug and run simple C++ programs.
 Introduce the concepts of functions, friend functions, inheritance, polymorphism
and function overloading.
 Introduce the concepts of exception handling and multithreading
Experiments
1 Write a C++ program that uses functions to perform the following:
a) Create a singly linked list of integers.
b) Delete a given integer from the above linked list.
c) Display the contents of the above list after deletion.
2 Write a template-based C++ program that uses functions to perform the
following:
a) Create a doubly linked list of elements.
b) Delete a given element from the above doubly linked list.
c) Display the contents of the above list after deletion.
3 Write a C++ program that uses stack operations to convert a given infix
expression into its postfix equivalent, Implement the stack using an array.
4 Write a C++ program to implement a double ended queue ADT using an array,
using a doubly linked list.
5 Write a C++ program that uses function templates to perform the following:
a) Search for a key element in a list of elements using linear search.
b) Search for a key element in a list of sorted elements using binary search.
6 Write a C++ program that implements Insertion sort algorithm to arrange a list of
integers in ascending order.
7 Write a template-based C++ program that implements selection sort algorithm to
arrange a list of elements in descending order.
8 Write a template-based C++ program that implements Quick sort algorithm to
arrange a list of elements in ascending order.
9 Write a C++ program that implements Heap sort algorithm for sorting a list of
integers in ascending order.
10 Write a C++ program that implements Radix sort algorithm for sorting a list of
integers in ascending order.
11 Write a C++ program that uses functions to perform the following:
a) Create a binary search tree of integers.
b) Traverse the above Binary search tree non recursively in Inorder.
12 Write a C++ program that uses functions to perform the following:
a) Create a binary search tree of integers.
b) Search for an integer key in the above binary search tree non recursively.
c) Search for an integer key in the above binary search tree recursively.
Course Outcomes: At the end of the course the students will be able to:
• Identify the appropriate data structures and algorithms for solving real world problems.
• Implement various kinds of searching and sorting techniques.
• Implement data structures such as stacks, queues and Search trees to solve various
computing problems.

1 Write a C++ program that uses functions to perform the following:


a) Create a singly linked list of integers.
b) Delete a given integer from the above linked list.
c) Display the contents of the above list after deletion.
#include <iostream>

// Define a Node structure for the singly linked list


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

// Function to create a new Node with the given data


Node* createNode(int data) {
Node* newNode = new Node;
newNode->data = data;
newNode->next = nullptr;
return newNode;
}

// Function to insert a new Node at the end of the linked list


void insertNode(Node*& head, int data) {
Node* newNode = createNode(data);
if (head == nullptr) {
head = newNode;
} else {
Node* temp = head;
while (temp->next != nullptr) {
temp = temp->next;
}
temp->next = newNode;
}
}

// Function to delete a given integer from the linked list


void deleteNode(Node*& head, int key) {
Node* current = head;
Node* prev = nullptr;

// Search for the node with the given key


while (current != nullptr && current->data != key) {
prev = current;
current = current->next;
}

// If the key is not found


if (current == nullptr) {
std::cout << "Element not found in the list." << std::endl;
return;
}

// Update the pointers to remove the node


if (prev == nullptr) {
// If the key is in the first node
head = current->next;
} else {
prev->next = current->next;
}

// Free the memory of the deleted node


delete current;
}

// Function to display the contents of the linked list


void displayList(const Node* head) {
const Node* current = head;
while (current != nullptr) {
std::cout << current->data << " ";
current = current->next;
}
std::cout << std::endl;
}

// Function to free the memory allocated for the linked list


void deleteList(Node*& head) {
Node* current = head;
Node* next = nullptr;
while (current != nullptr) {
next = current->next;
delete current;
current = next;
}
head = nullptr;
}

int main() {
Node* head = nullptr;

// Creating a singly linked list of integers


insertNode(head, 1);
insertNode(head, 2);
insertNode(head, 3);
insertNode(head, 4);

std::cout << "Original list: ";


displayList(head);

// Deleting a given integer from the list


int keyToDelete;
std::cout << "Enter the integer to delete: ";
std::cin >> keyToDelete;
deleteNode(head, keyToDelete);

// Displaying the contents of the list after deletion


std::cout << "List after deletion: ";
displayList(head);

// Freeing the memory allocated for the linked list


deleteList(head);

return 0;
}
Output
Original list: 1 2 3 4
Enter the integer to delete: 4
List after deletion: 1 2 3

2 Write a template-based C++ program that uses functions to perform the


following:
a) Create a doubly linked list of elements.
b) Delete a given element from the above doubly linked list.
c) Display the contents of the above list after deletion.
#include <iostream>

// Node structure for doubly linked list


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

Node(int value) : data(value), prev(nullptr), next(nullptr) {}


};

// Doubly Linked List class


class DoublyLinkedList {
private:
Node* head;

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

// Function to insert a new element at the end of the list


void insert(int value) {
Node* newNode = new Node(value);
if (!head) {
head = newNode;
} else {
Node* current = head;
while (current->next) {
current = current->next;
}
current->next = newNode;
newNode->prev = current;
}
}

// Function to delete a given element from the list


void deleteElement(int value) {
Node* current = head;
while (current && current->data != value) {
current = current->next;
}

if (!current) {
std::cout << "Element not found in the list.\n";
return;
}

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

if (current->next) {
current->next->prev = current->prev;
}

delete current;
std::cout << "Element " << value << " deleted from the list.\n";
}
// Function to display the contents of the list
void display() {
Node* current = head;
while (current) {
std::cout << current->data << " ";
current = current->next;
}
std::cout << "\n";
}
};

int main() {
DoublyLinkedList myList;

// Insert elements into the list


myList.insert(1);
myList.insert(2);
myList.insert(3);
myList.insert(4);

std::cout << "Original List: ";


myList.display();

// Delete an element from the list


int elementToDelete;
std::cout << "Enter the element to delete: ";
std::cin >> elementToDelete;
myList.deleteElement(elementToDelete);

// Display the contents after deletion


std::cout << "List after deletion: ";
myList.display();

return 0;
}
Output
Original List: 1 2 3 4
Enter the element to delete: 2
Element 2 deleted from the list.
List after deletion: 1 3 4

3 Write a C++ program that uses stack operations to convert a given infix
expression into its postfix equivalent, Implement the stack using an array.
#include <iostream>
#include <stack>

using namespace std;

// Function to check if a character is an operator


bool isOperator(char c) {
return (c == '+' || c == '-' || c == '*' || c == '/');
}

// Function to get the precedence of an operator


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

// Function to convert infix expression to postfix


string infixToPostfix(string infix) {
stack<char> s;
string postfix = "";

for (char c : infix) {


if (isalnum(c)) {
// If operand, append to postfix
postfix += c;
} else if (c == '(') {
// If '(', push onto the stack
s.push(c);
} else if (c == ')') {
// Pop and append operators from stack until '(' is encountered
while (!s.empty() && s.top() != '(') {
postfix += s.top();
s.pop();
}
// Pop the '(' from the stack
s.pop();
} else if (isOperator(c)) {
// Pop and append operators from stack with higher or equal precedence
while (!s.empty() && getPrecedence(s.top()) >= getPrecedence(c)) {
postfix += s.top();
s.pop();
}
// Push the current operator onto the stack
s.push(c);
}
}

// Pop and append remaining operators from stack


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

return postfix;
}

int main() {
string infixExpression;

// Input infix expression


cout << "Enter infix expression: ";
getline(cin, infixExpression);

// Convert to postfix and display the result


string postfixExpression = infixToPostfix(infixExpression);
cout << "Postfix expression: " << postfixExpression << endl;

return 0;
}
Out put
Enter infix expression: a*b+c-d+c
Postfix expression: ab*c+d-c+
4 Write a C++ program to implement a double ended queue ADT using an array,
using a doubly linked list.
#include <iostream>

// Node structure for a doubly linked list


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

class Deque {
private:
Node* front;
Node* rear;

public:
Deque() : front(nullptr), rear(nullptr) {}

// Function to check if the deque is empty


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

// Function to insert an element at the front of the deque


void insertFront(int value) {
Node* newNode = new Node;
newNode->data = value;
newNode->next = nullptr;
newNode->prev = nullptr;

if (isEmpty()) {
front = rear = newNode;
} else {
newNode->next = front;
front->prev = newNode;
front = newNode;
}

std::cout << "Inserted " << value << " at the front.\n";
}

// Function to insert an element at the rear of the deque


void insertRear(int value) {
Node* newNode = new Node;
newNode->data = value;
newNode->next = nullptr;
newNode->prev = nullptr;

if (isEmpty()) {
front = rear = newNode;
} else {
newNode->prev = rear;
rear->next = newNode;
rear = newNode;
}

std::cout << "Inserted " << value << " at the rear.\n";
}

// Function to delete an element from the front of the deque


void deleteFront() {
if (isEmpty()) {
std::cout << "Deque is empty. Cannot delete from the front.\n";
return;
}

Node* temp = front;


front = front->next;

if (front != nullptr) {
front->prev = nullptr;
} else {
rear = nullptr;
}

std::cout << "Deleted element from the front: " << temp->data << "\n";
delete temp;
}

// Function to delete an element from the rear of the deque


void deleteRear() {
if (isEmpty()) {
std::cout << "Deque is empty. Cannot delete from the rear.\n";
return;
}

Node* temp = rear;


rear = rear->prev;

if (rear != nullptr) {
rear->next = nullptr;
} else {
front = nullptr;
}

std::cout << "Deleted element from the rear: " << temp->data << "\n";
delete temp;
}

// Function to display the elements of the deque


void display() {
if (isEmpty()) {
std::cout << "Deque is empty.\n";
return;
}

Node* current = front;


while (current != nullptr) {
std::cout << current->data << " ";
current = current->next;
}
std::cout << "\n";
}

// Destructor to free memory


~Deque() {
while (!isEmpty()) {
deleteFront();
}
}
};

int main() {
Deque deque;

deque.insertFront(1);
deque.insertFront(2);
deque.insertRear(3);
deque.display();

deque.deleteFront();
deque.deleteRear();
deque.display();

return 0;
}
OUT PUT
Output:

Inserted 1 at the front.


Inserted 2 at the front.
Inserted 3 at the rear.
213
Deleted element from the front: 2
Deleted element from the rear: 3
1
Deleted element from the front: 1

5 Write a C++ program that uses function templates to perform the following:
a) Search for a key element in a list of elements using linear search.
b) Search for a key element in a list of sorted elements using binary search.
#include <iostream>
#include <vector>

// Function template for linear search


template <typename T>
int linearSearch(const std::vector<T>& arr, const T& key) {
for (size_t i = 0; i < arr.size(); ++i) {
if (arr[i] == key) {
return i; // Element found, return its index
}
}
return -1; // Element not found
}

// Function template for binary search


template <typename T>
int binarySearch(const std::vector<T>& arr, const T& key) {
int low = 0;
int high = arr.size() - 1;

while (low <= high) {


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

if (arr[mid] == key) {
return mid; // Element found, return its index
} else if (arr[mid] < key) {
low = mid + 1;
} else {
high = mid - 1;
}
}

return -1; // Element not found


}

int main() {
std::vector<int> unsortedList = {4, 2, 7, 1, 9, 5, 3, 8, 6};
std::vector<int> sortedList = {1, 2, 3, 4, 5, 6, 7, 8, 9};
int key;

// Linear search on unsorted list


std::cout << "Enter key for linear search: ";
std::cin >> key;
int linearResult = linearSearch(unsortedList, key);
if (linearResult != -1) {
std::cout << "Linear search: Element found at index " << linearResult << std::endl;
} else {
std::cout << "Linear search: Element not found" << std::endl;
}

// Binary search on sorted list


std::cout << "Enter key for binary search: ";
std::cin >> key;
int binaryResult = binarySearch(sortedList, key);
if (binaryResult != -1) {
std::cout << "Binary search: Element found at index " << binaryResult << std::endl;
} else {
std::cout << "Binary search: Element not found" << std::endl;
}

return 0;
}
Out Put
Enter key for linear search: 7
Linear search: Element found at index 2
Enter key for binary search: 5
Binary search: Element found at index 4
6 Write a C++ program that implements Insertion sort algorithm to arrange a
list of integers in ascending order.
#include <iostream>
#include <vector>

void insertionSort(std::vector<int>& arr) {


int n = arr.size();

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


int key = arr[i];
int j = i - 1;

// Move elements of arr[0..i-1] that are greater than key to one position ahead of their
current position
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
--j;
}

arr[j + 1] = key;
}
}

int main() {
std::cout << "Insertion Sort Algorithm Implementation\n\n";

// Input: a list of integers


std::vector<int> arr = {12, 11, 13, 5, 6};

std::cout << "Original array: ";


for (int num : arr) {
std::cout << num << " ";
}
std::cout << "\n";

// Sort the array using Insertion Sort


insertionSort(arr);

// Output: Sorted array


std::cout << "Sorted array: ";
for (int num : arr) {
std::cout << num << " ";
}
std::cout << "\n";

return 0;
}
Out Put
Insertion Sort Algorithm Implementation

Original array: 12 11 13 5 6
Sorted array: 5 6 11 12 13

7 Write a template-based C++ program that implements selection sort algorithm


to arrange a list of elements in descending order.
#include <iostream>
#include <vector>

template <typename T>


void selectionSort(std::vector<T>& arr) {
int n = arr.size();

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


// Find the maximum element in the unsorted part of the array
int maxIndex = i;
for (int j = i + 1; j < n; ++j) {
if (arr[j] > arr[maxIndex]) {
maxIndex = j;
}
}

// Swap the found maximum element with the first element


std::swap(arr[i], arr[maxIndex]);
}
}

int main() {
// Example usage
std::vector<int> numbers = {64, 25, 12, 22, 11};

std::cout << "Original array: ";


for (const auto& num : numbers) {
std::cout << num << " ";
}
// Perform selection sort in descending order
selectionSort(numbers);

std::cout << "\nArray after selection sort in descending order: ";


for (const auto& num : numbers) {
std::cout << num << " ";
}

return 0;
}
Out put
Original array: 64 25 12 22 11
Array after selection sort in descending order: 64 25 22 12 11

8 Write a template-based C++ program that implements Quick sort algorithm to


arrange a list of elements in ascending order.
#include <iostream>
#include <vector>
// Function to partition the array into two halves
template <typename T>
int partition(std::vector<T>& arr, int low, int high) {
T pivot = arr[high]; // Choose the last element as the pivot
int i = low - 1; // Index of the smaller element
for (int j = low; j < high; ++j) {
// If the current element is smaller than or equal to the pivot
if (arr [j] <= pivot) {
// Swap arr[i] and arr[j]
std::swap(arr[++i], arr[j]);
}
}
// Swap arr[i+1] and arr[high] (put the pivot in its correct place)
std::swap(arr[i + 1], arr[high]);
return i + 1; // Return the index of the pivot element
}
// Function to perform quick sort on the array
template <typename T>
void quickSort(std::vector<T>& arr, int low, int high) {
if (low < high) {
// Partition the array into two halves and get the pivot index
int pivotIndex = partition(arr, low, high);
// Recursively sort the subarrays
quickSort(arr, low, pivotIndex - 1);
quickSort(arr, pivotIndex + 1, high);
}
}
// Function to print the elements of the array
template <typename T>
void printArray(const std::vector<T>& arr) {
for (const auto& element : arr) {
std::cout << element << " ";
}
std::cout << std::endl;
}
int main() {
// Example usage
std::vector<int> arr = {12, 7, 11, 5, 6, 1, 2};
std::cout << "Original array: ";
printArray(arr);
int size = arr.size();
quickSort(arr, 0, size - 1);
std::cout << "Sorted array: ";
printArray(arr);
return 0;
}

9 Write a C++ program that implements Heap sort algorithm for sorting a list of
integers in ascending order.
#include <iostream>
#include <vector>
using namespace std;

void heapify(vector<int>& arr, int n, int i) {


int largest = i; // Initialize largest as root
int left = 2 * i + 1; // Left child
int right = 2 * i + 2; // Right child

// If left child is larger than root


if (left < n && arr[left] > arr[largest])
largest = left;
// If right child is larger than largest so far
if (right < n && arr[right] > arr[largest])
largest = right;

// If largest is not root


if (largest != i) {
swap(arr[i], arr[largest]);
// Recursively heapify the affected sub-tree
heapify(arr, n, largest);
}
}
void heapSort(vector<int>& arr) {
int n = arr.size();
// Build heap (rearrange array)
for (int i = n / 2 - 1; i >= 0; i--)
heapify(arr, n, i);
// One by one extract an element from heap
for (int i = n - 1; i >= 0; i--) {
// Move current root to end
swap(arr[0], arr[i]);

// Call max heapify on the reduced heap


heapify(arr, i, 0);
}
}
int main() {
vector<int> arr = {12, 11, 13, 5, 6, 7};

cout << "Original array: ";


for (int num : arr) {
cout << num << " ";
}
cout << endl;

heapSort(arr);

cout << "Sorted array: ";


for (int num : arr) {
cout << num << " ";
}
cout << endl;

return 0;
}
OUT PUT
Original array: 12 11 13 5 6 7
Sorted array: 5 6 7 11 12 13

10 Write a C++ program that implements Radix sort algorithm for sorting a list of
integers in ascending order.
#include <iostream>
#include <vector>
#include <algorithm>

// Function to find the maximum number in the array


int findMax(std::vector<int>& arr) {
int max = arr[0];
for (int i = 1; i < arr.size(); i++) {
if (arr[i] > max) {
max = arr[i];
}
}
return max;
}

// Using counting sort to sort the elements based on significant places


void countingSort(std::vector<int>& arr, int exp) {
const int n = arr.size();
const int radix = 10; // The base of the number system

std::vector<int> output(n);
std::vector<int> count(radix, 0);

// Count the number of occurrences at each digit place


for (int i = 0; i < n; i++) {
count[(arr[i] / exp) % radix]++;
}

// Update count[i] to store the position of the next occurrence of that digit
for (int i = 1; i < radix; i++) {
count[i] += count[i - 1];
}

// Build the output array by placing elements in their sorted order


for (int i = n - 1; i >= 0; i--) {
output[count[(arr[i] / exp) % radix] - 1] = arr[i];
count[(arr[i] / exp) % radix]--;
}

// Copy the output array to the original array


std::copy(output.begin(), output.end(), arr.begin());
}

// Radix sort function


void radixSort(std::vector<int>& arr) {
int max = findMax(arr);

// Perform counting sort for every digit place


for (int exp = 1; max / exp > 0; exp *= 10) {
countingSort(arr, exp);
}
}

int main() {
std::vector<int> arr = {170, 45, 75, 90, 802, 24, 2, 66};

std::cout << "Original array: ";


for (int num : arr) {
std::cout << num << " ";
}

radixSort(arr);

std::cout << "\nSorted array: ";


for (int num : arr) {
std::cout << num << " ";
}

return 0;
}
Out put
Original array: 170 45 75 90 802 24 2 66
Sorted array: 2 24 45 66 75 90 170 802

11 Write a C++ program that uses functions to perform the following:


a) Create a binary search tree of integers.
b) Traverse the above Binary search tree non recursively in Inorder.
#include <iostream>
#include <stack>

// Node structure for the Binary Search Tree


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

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


};

// Function to insert a new node into the Binary Search Tree


Node* insert(Node* root, int value) {
if (root == nullptr) {
return new Node(value);
}

if (value < root->data) {


root->left = insert(root->left, value);
} else if (value > root->data) {
root->right = insert(root->right, value);
}

return root;
}

// Function to traverse the Binary Search Tree non-recursively in Inorder


void inorderTraversal(Node* root) {
std::stack<Node*> s;
Node* current = root;

while (current != nullptr || !s.empty()) {


while (current != nullptr) {
s.push(current);
current = current->left;
}

current = s.top();
s.pop();

std::cout << current->data << " ";

current = current->right;
}
}

// Driver program
int main() {
Node* root = nullptr;

// Insert elements into the Binary Search Tree


root = insert(root, 50);
insert(root, 30);
insert(root, 20);
insert(root, 40);
insert(root, 70);
insert(root, 60);
insert(root, 80);

// Perform Inorder traversal non-recursively


std::cout << "Inorder Traversal: ";
inorderTraversal(root);
std::cout << std::endl;

return 0;
}
Out put
Inorder Traversal: 20 30 40 50 60 70 80

12 Write a C++ program that uses functions to perform the following:


a) Create a binary search tree of integers.
b) Search for an integer key in the above binary search tree non recursively.
c) Search for an integer key in the above binary search tree recursively.
#include <iostream>

// Define a structure for a node in the binary search tree


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

// Function to insert a new node into the binary search tree


Node* insert(Node* root, int key) {
if (root == nullptr) {
return new Node(key);
}

if (key < root->data) {


root->left = insert(root->left, key);
} else if (key > root->data) {
root->right = insert(root->right, key);
}

return root;
}
// Function to perform non-recursive search in the binary search tree
bool searchNonRecursive(Node* root, int key) {
while (root != nullptr) {
if (key == root->data) {
return true; // Key found
} else if (key < root->data) {
root = root->left;
} else {
root = root->right;
}
}
return false; // Key not found
}

// Function to perform recursive search in the binary search tree


bool searchRecursive(Node* root, int key) {
if (root == nullptr) {
return false; // Key not found
}

if (key == root->data) {
return true; // Key found
} else if (key < root->data) {
return searchRecursive(root->left, key);
} else {
return searchRecursive(root->right, key);
}
}

// Function to delete all nodes in the binary search tree


void deleteTree(Node* root) {
if (root != nullptr) {
deleteTree(root->left);
deleteTree(root->right);
delete root;
}
}

int main() {
// Create an empty binary search tree
Node* root = nullptr;
// Insert elements into the binary search tree
root = insert(root, 50);
insert(root, 30);
insert(root, 20);
insert(root, 40);
insert(root, 70);
insert(root, 60);
insert(root, 80);

// Search for a key non-recursively


int keyToSearch = 40;
if (searchNonRecursive(root, keyToSearch)) {
std::cout << "Key " << keyToSearch << " found (non-recursive).\n";
} else {
std::cout << "Key " << keyToSearch << " not found (non-recursive).\n";
}

// Search for a key recursively


keyToSearch = 60;
if (searchRecursive(root, keyToSearch)) {
std::cout << "Key " << keyToSearch << " found (recursive).\n";
} else {
std::cout << "Key " << keyToSearch << " not found (recursive).\n";
}

// Delete the binary search tree to free memory


deleteTree(root);

return 0;
}
Output :
Key 40 found (non-recursive).
Key 60 found (recursive).

You might also like