Thanks to visit codestin.com
Credit goes to www.scribd.com

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

Data Structure

The document contains six programs demonstrating various data structures and algorithms in C++. Programs include creating and manipulating square matrices, linked lists (singly and circular doubly), and stack operations using arrays. Each program includes source code, user input prompts, and output examples.

Uploaded by

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

Data Structure

The document contains six programs demonstrating various data structures and algorithms in C++. Programs include creating and manipulating square matrices, linked lists (singly and circular doubly), and stack operations using arrays. Each program includes source code, user input prompts, and output examples.

Uploaded by

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

Program – 1

Source Code:
/*Write a program to create a square matrix, fill the data inside and print the diagonal
elements.*/

#include <iostream>
using namespace std;
int main() {
int n;
cout << "Enter the size of the square matrix (n x n): ";
cin >> n;
int matrix[100][100]; // assuming maximum size is 100x100
// Input elements of the matrix
cout << "Enter the elements of the matrix:" << endl;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cout << "Element [" << i << "][" << j << "]: ";
cin >> matrix[i][j];
}
}
// Display the matrix
cout << "\nMatrix is:\n";
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cout << matrix[i][j] << "\t";
}
cout << endl;
}
// Print main diagonal elements
cout << "\nMain Diagonal Elements: ";
for (int i = 0; i < n; i++) {
1
cout << matrix[i][i] << " ";
}
// Print secondary diagonal elements
cout << "\nSecondary Diagonal Elements: ";
for (int i = 0; i < n; i++) {
cout << matrix[i][n - 1 - i] << " ";
}
cout << endl;
return 0;
}

Output:

2
Program – 2
Source Code:
/*Write a program to perform addition and subtraction on two matrices.*/
#include <iostream>
using namespace std;
int main() {
int rows, cols;
// Input number of rows and columns
cout << "Enter number of rows and columns of the matrices: ";
cin >> rows >> cols;
int matrix1[100][100], matrix2[100][100], sum[100][100], diff[100][100];
// Input first matrix
cout << "\nEnter elements of Matrix 1:\n";
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
cout << "Element [" << i << "][" << j << "]: ";
cin >> matrix1[i][j];
}
}
// Input second matrix
cout << "\nEnter elements of Matrix 2:\n";
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
cout << "Element [" << i << "][" << j << "]: ";
cin >> matrix2[i][j];
}
}
// Matrix Addition and Subtraction
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {

3
sum[i][j] = matrix1[i][j] + matrix2[i][j];
diff[i][j] = matrix1[i][j] - matrix2[i][j];
}
}
// Display Sum Matrix
cout << "\nMatrix Addition Result (Matrix1 + Matrix2):\n";
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
cout << sum[i][j] << "\t";
}
cout << endl;
}
// Display Difference Matrix
cout << "\nMatrix Subtraction Result (Matrix1 - Matrix2):\n";
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
cout << diff[i][j] << "\t";
}
cout << endl;
}
return 0;
}
Source Code:

4
5
Program – 3
Source Code:

/*Write a program to perform multiplication on two matrices.*/


#include <iostream>
using namespace std;
int main() {
int row1, col1, row2, col2;
// Input dimensions of Matrix A
cout << "Enter rows and columns of first matrix: ";
cin >> row1 >> col1;
// Input dimensions of Matrix B
cout << "Enter rows and columns of second matrix: ";
cin >> row2 >> col2;
// Check if multiplication is possible
if (col1 != row2) {
cout << "Matrix multiplication not possible! (col1 must be equal to row2)" << endl;
return 0;
}
// Declare matrices
int A[100][100], B[100][100], result[100][100];
// Input Matrix A
cout << "Enter elements of first matrix:\n";
for (int i = 0; i < row1; i++)
for (int j = 0; j < col1; j++)
cin >> A[i][j];

// Input Matrix B
cout << "Enter elements of second matrix:\n";
for (int i = 0; i < row2; i++)

6
for (int j = 0; j < col2; j++)
cin >> B[i][j];
// Initialize result matrix with 0
for (int i = 0; i < row1; i++)
for (int j = 0; j < col2; j++)
result[i][j] = 0;
// Matrix multiplication logic
for (int i = 0; i < row1; i++) {
for (int j = 0; j < col2; j++) {
for (int k = 0; k < col1; k++) {
result[i][j] += A[i][k] * B[k][j];
}
}
}
// Output result matrix
cout << "Resultant Matrix:\n";
for (int i = 0; i < row1; i++) {
for (int j = 0; j < col2; j++) {
cout << result[i][j] << " ";
}
cout << endl;
}
return 0;
}

Output:

Enter rows and columns of first matrix: 3 *3


Enter rows and columns of second matrix: 3 * 3

7
Enter elements of first matrix:
2 5 9
3 6 8
4 5 6
Enter elements of second matrix:
8 4 5
5 9 3
6 23 2
Resultant Matrix:
40 117 47
79 170 94
122 223 138

8
Program – 4
Source Code:
/*Write a program to perform insertion, deletion of nodes from the end in singly linked
list.*/
#include <iostream>
using namespace std;
// Define the Node structure
struct Node {
int data;
Node* next;
};
// Function to insert node at the end
void insertAtEnd(Node*& head, int value) {
Node* newNode = new Node();
newNode->data = value;
newNode->next = nullptr;
if (head == nullptr) {
head = newNode;
} else {
Node* temp = head;
while (temp->next != nullptr)
temp = temp->next;
temp->next = newNode;
}
cout << value << " inserted at end.\n";
}
// Function to delete node from the end
void deleteFromEnd(Node*& head) {
if (head == nullptr) {
cout << "List is empty. Nothing to delete.\n";
return;
9
}
if (head->next == nullptr) {
cout << head->data << " deleted from end.\n";
delete head;
head = nullptr;
return;
}
Node* temp = head;
while (temp->next->next != nullptr)
temp = temp->next;
cout << temp->next->data << " deleted from end.\n";
delete temp->next;
temp->next = nullptr;
}
// Function to display the list
void displayList(Node* head) {
if (head == nullptr) {
cout << "List is empty.\n";
return;
}
cout << "Linked List: ";
while (head != nullptr) {
cout << head->data << " -> ";
head = head->next;
}
cout << "NULL\n";
}
// Main function
int main() {
Node* head = nullptr;

10
int choice, value;
while (true) {
cout << "\n--- MENU ---\n";
cout << "1. Insert at End\n";
cout << "2. Delete from End\n";
cout << "3. Display List\n";
cout << "4. Exit\n";
cout << "Enter your choice: ";
cin >> choice;
switch (choice) {
case 1:
cout << "Enter value to insert: ";
cin >> value;
insertAtEnd(head, value);
break;
case 2:
deleteFromEnd(head);
break;
case 3:
displayList(head);
break;
case 4:
cout << "Exiting...\n";
return 0;
default:
cout << "Invalid choice. Try again.\n";
}
}

11
Output:
--- MENU ---
1. Insert at End
2. Delete from End
3. Display List
4. Exit
Enter your choice: 1
Enter value to insert: 30
30 inserted at end.

--- MENU ---


1. Insert at End
2. Delete from End
3. Display List
4. Exit
Enter your choice: 1
Enter value to insert:
40
40 inserted at end.

--- MENU ---


1. Insert at End
2. Delete from End
3. Display List
4. Exit
Enter your choice: 1
Enter value to insert: 50
50 inserted at end.

--- MENU ---

12
1. Insert at End
2. Delete from End
3. Display List
4. Exit
Enter your choice: 3
Linked List: 30 -> 40 -> 50 -> NULL

--- MENU ---


1. Insert at End
2. Delete from End
3. Display List
4. Exit
Enter your choice: 2
50 deleted from end.

--- MENU ---


1. Insert at End
2. Delete from End
3. Display List
4. Exit
Enter your choice: 3
Linked List: 30 -> 40 -> NULL

13
Program – 5
Source Code:
/*Write a program to perform insertion and deletion of nodes from the end in circular doubly
linked list.*/
#include <iostream>
using namespace std;

// Node structure
struct Node {
int data;
Node* next;
Node* prev;
};
// Function to insert node at end
void insertAtEnd(Node*& head, int value) {
Node* newNode = new Node();
newNode->data = value;
if (head == nullptr) {
newNode->next = newNode->prev = newNode;
head = newNode;
} else {
Node* last = head->prev;
newNode->next = head;
newNode->prev = last;
last->next = newNode;
head->prev = newNode;
}
cout << value << " inserted at end.\n";
}
// Function to delete node from end
void deleteFromEnd(Node*& head) {
14
if (head == nullptr) {
cout << "List is empty. Nothing to delete.\n";
return;
}
// Only one node
if (head->next == head) {
cout << head->data << " deleted from end.\n";
delete head;
head = nullptr;
return;
}
Node* last = head->prev;
Node* secondLast = last->prev;
secondLast->next = head;
head->prev = secondLast;
cout << last->data << " deleted from end.\n";
delete last;
}
// Function to display list
void displayList(Node* head) {
if (head == nullptr) {
cout << "List is empty.\n";
return;
}
Node* temp = head;
cout << "Circular Doubly Linked List: ";
do {
cout << temp->data << " <-> ";
temp = temp->next;
} while (temp != head);

15
cout << "(back to head)\n";
}
// Main function
int main() {
Node* head = nullptr;
int choice, value;
while (true) {
cout << "\n--- MENU ---\n";
cout << "1. Insert at End\n";
cout << "2. Delete from End\n";
cout << "3. Display List\n";
cout << "4. Exit\n";
cout << "Enter your choice: ";
cin >> choice;
switch (choice) {
case 1:
cout << "Enter value to insert: ";
cin >> value;
insertAtEnd(head, value);
break;
case 2:
deleteFromEnd(head);
break;
case 3:
displayList(head);
break;
case 4:
cout << "Exiting...\n";
return 0;
default:

16
cout << "Invalid choice. Try again.\n";
}
}
}
Output:
--- MENU ---
1. Insert at End
2. Delete from End
3. Display List
4. Exit
Enter your choice: 1
Enter value to insert: 50
50 inserted at end.

--- MENU ---


1. Insert at End
2. Delete from End
3. Display List
4. Exit
Enter your choice: 1
Enter value to insert: 0
0 inserted at end.

--- MENU ---


1. Insert at End
2. Delete from End
3. Display List
4. Exit
Enter your choice: 1
Enter value to insert: 85

17
85 inserted at end.

--- MENU ---


1. Insert at End
2. Delete from End
3. Display List
4. Exit
Enter your choice: 3
Circular Doubly Linked List: 50 <-> 0 <-> 85 <-> (back to head)

--- MENU ---


1. Insert at End
2. Delete from End
3. Display List
4. Exit
Enter your choice: 2
85 deleted from end.

--- MENU ---


1. Insert at End
2. Delete from End
3. Display List
4. Exit
Enter your choice: 3
Circular Doubly Linked List: 50 <-> 0 <-> (back to head)

18
Program – 6
Source Code:
/*Write a program to perform push and pop operations in stack, where stack should be
created using array.*/
#include <iostream>
using namespace std;
#define SIZE 100 // Define maximum size of the stack
class Stack {
private:
int arr[SIZE];
int top;
public:
Stack() {
top = -1; // Initialize top to -1 indicating empty stack
}
// Push operation
void push(int value) {
if (top == SIZE - 1) {
cout << "Stack Overflow! Cannot push " << value << endl;
return;
}
arr[++top] = value;
cout << value << " pushed to stack.\n";
}
// Pop operation
void pop() {
if (top == -1) {
cout << "Stack Underflow! Nothing to pop.\n";
return;
}
cout << arr[top--] << " popped from stack.\n";
19
}
// Display stack contents
void display() {
if (top == -1) {
cout << "Stack is empty.\n";
return;
}
cout << "Stack elements: ";
for (int i = top; i >= 0; i--)
cout << arr[i] << " ";
cout << endl;
}
};
// Main function
int main() {
Stack s;
int choice, value;
while (true) {
cout << "\n--- MENU ---\n";
cout << "1. Push\n";
cout << "2. Pop\n";
cout << "3. Display\n";
cout << "4. Exit\n";
cout << "Enter your choice: ";
cin >> choice;
switch (choice) {
case 1:
cout << "Enter value to push: ";
cin >> value;
s.push(value);

20
break;
case 2:
s.pop();
break;
case 3:
s.display();
break;
case 4:
cout << "Exiting...\n";
return 0;
default:
cout << "Invalid choice! Try again.\n";
}
}
}

Output:
--- MENU ---
1. Push
2. Pop
3. Display
4. Exit
Enter your choice: 1
Enter value to push: 50
50 pushed to stack.
--- MENU ---
1. Push
2. Pop
3. Display
4. Exit

21
Enter your choice: 1
Enter value to push: 60
60 pushed to stack.
--- MENU ---
1. Push
2. Pop
3. Display
4. Exit
Enter your choice: 1
Enter value to push: 80
80 pushed to stack.
--- MENU ---
1. Push
2. Pop
3. Display
4. Exit
Enter your choice: 3
Stack elements: 80 60 50

--- MENU ---


1. Push
2. Pop
3. Display
4. Exit
Enter your choice: 2
80 popped from stack.

--- MENU ---


1. Push
2. Pop

22
3. Display
4. Exit
Enter your choice: 3
Stack elements: 60 50

23
Program – 7
Source Code:
/*Write a program to perform push and pop operation in stack, where stack should be
created linked list.*/
#include <iostream>
using namespace std;
// Node structure for linked list
struct Node {
int data;
Node* next;
};
// Stack class using linked list
class Stack {
private:
Node* top;
public:
Stack() {
top = nullptr; // Initialize top as NULL
}
// Push operation
void push(int value) {
Node* newNode = new Node();
newNode->data = value;
newNode->next = top;
top = newNode;
cout << value << " pushed to stack.\n";
}
// Pop operation
void pop() {
if (top == nullptr) {
cout << "Stack Underflow! Nothing to pop.\n";
24
return;
}
Node* temp = top;
cout << top->data << " popped from stack.\n";
top = top->next;
delete temp;
}
// Display stack contents
void display() {
if (top == nullptr) {
cout << "Stack is empty.\n";
return;
}
cout << "Stack elements: ";
Node* temp = top;
while (temp != nullptr) {
cout << temp->data << " ";
temp = temp->next;
}
cout << endl;
}
};
// Main function
int main() {
Stack s;
int choice, value;
while (true) {
cout << "\n--- MENU ---\n";
cout << "1. Push\n";
cout << "2. Pop\n";

25
cout << "3. Display\n";
cout << "4. Exit\n";
cout << "Enter your choice: ";
cin >> choice;
switch (choice) {
case 1:
cout << "Enter value to push: ";
cin >> value;
s.push(value);
break;
case 2:
s.pop();
break;
case 3:
s.display();
break;
case 4:
cout << "Exiting...\n";
return 0;
default:
cout << "Invalid choice! Try again.\n";
}
}
}

Output:
--- MENU ---
1. Push
2. Pop
3. Display

26
4. Exit
Enter your choice: 1
Enter value to push: 90
90 pushed to stack.

--- MENU ---


1. Push
2. Pop
3. Display
4. Exit
Enter your choice: 2
90 popped from stack.

--- MENU ---


1. Push
2. Pop
3. Display
4. Exit
Enter your choice: 3
Stack is empty.

27
Program – 8
Source Code:
/*Write a program to calculate factorial of given number using stack.*/
#include <iostream>
using namespace std;
#define SIZE 100
class Stack {
private:
int arr[SIZE];
int top;
public:
Stack() {
top = -1;
}
void push(int value) {
if (top == SIZE - 1) {
cout << "Stack Overflow!\n";
return;
}
arr[++top] = value;
}
int pop() {
if (top == -1) {
cout << "Stack Underflow!\n";
return -1;
}
return arr[top--];
}
bool isEmpty() {
return top == -1;

28
}
};
// Function to calculate factorial using stack
int factorial(int n) {
Stack s;
int result = 1;
// Push numbers from n down to 1 onto the stack
for (int i = n; i >= 1; i--) {
s.push(i);
}
while (!s.isEmpty()) { // Pop and multiply
result *= s.pop();
}
return result;
}
int main() { // Main function
int number;
cout << "Enter a number to find factorial: ";
cin >> number;
if (number < 0) {
cout << "Factorial is not defined for negative numbers.\n";
} else {
int fact = factorial(number);
cout << "Factorial of " << number << " is: " << fact << endl;
}
return 0;
}
Output:
Enter a number to find factorial: 5
Factorial of 5 is: 120

29
Program – 9
Source Code:
/*Write a program to perform insertion and deletion of data items in queue. queue should be
implemented by using a linked list.*/

#include <iostream>
using namespace std;
// Node structure
struct Node {
int data;
Node* next;
};
// Queue class using linked list
class Queue {
private:
Node* front;
Node* rear;
public:
Queue() {
front = rear = nullptr;
}
// Enqueue (Insertion)
void enqueue(int value) {
Node* newNode = new Node();
newNode->data = value;
newNode->next = nullptr;
if (rear == nullptr) {
front = rear = newNode;
} else {
rear->next = newNode;
rear = newNode;
30
}
cout << value << " inserted into queue.\n";
}
// Dequeue (Deletion)
void dequeue() {
if (front == nullptr) {
cout << "Queue Underflow! Nothing to delete.\n";
return;
}
Node* temp = front;
cout << front->data << " deleted from queue.\n";
front = front->next;
if (front == nullptr) // If queue becomes empty
rear = nullptr;
delete temp;
}
// Display queue
void display() {
if (front == nullptr) {
cout << "Queue is empty.\n";
return;
}
Node* temp = front;
cout << "Queue elements: ";
while (temp != nullptr) {
cout << temp->data << " ";
temp = temp->next;
}
cout << endl;
}

31
};
// Main function
int main() {
Queue q;
int choice, value;

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

switch (choice) {
case 1:
cout << "Enter value to insert: ";
cin >> value;
q.enqueue(value);
break;
case 2:
q.dequeue();
break;
case 3:
q.display();
break;
case 4:
cout << "Exiting...\n";
return 0;

32
default:
cout << "Invalid choice! Try again.\n";
}
}
}
Output:
--- MENU ---
1. Enqueue (Insert)
2. Dequeue (Delete)
3. Display Queue
4. Exit
Enter your choice: 1
Enter value to insert: 45
45 inserted into queue.

--- MENU ---


1. Enqueue (Insert)
2. Dequeue (Delete)
3. Display Queue
4. Exit
Enter your choice: 1
Enter value to insert: 55
55 inserted into queue.

--- MENU ---


1. Enqueue (Insert)
2. Dequeue (Delete)
3. Display Queue
4. Exit
Enter your choice: 1

33
Enter value to insert: 66
66 inserted into queue.

--- MENU ---


1. Enqueue (Insert)
2. Dequeue (Delete)
3. Display Queue
4. Exit
Enter your choice: 3
Queue elements: 45 55 66

--- MENU ---


1. Enqueue (Insert)
2. Dequeue (Delete)
3. Display Queue
4. Exit
Enter your choice: 2
45 deleted from queue.

34
Program – 10
Source Code:
/*Write a program to perform insertion and deletion of data items in queue, queue should be
implemented by using arrays.*/
#include <iostream>
using namespace std;
#define SIZE 100
class Queue {
private:
int arr[SIZE];
int front, rear;
public:
Queue() {
front = -1;
rear = -1;
}
// Insertion (Enqueue)
void enqueue(int value) {
if (rear == SIZE - 1) {
cout << "Queue Overflow! Cannot insert " << value << endl;
return;
}
if (front == -1) front = 0; // First insertion
arr[++rear] = value;
cout << value << " inserted into queue.\n";
}
// Deletion (Dequeue)
void dequeue() {
if (front == -1 || front > rear) {
cout << "Queue Underflow! Nothing to delete.\n";
return;
35
}
cout << arr[front++] << " deleted from queue.\n";
// Reset when queue becomes empty
if (front > rear) {
front = rear = -1;
}
}
// Display Queue
void display() {
if (front == -1 || front > rear) {
cout << "Queue is empty.\n";
return;
}
cout << "Queue elements: ";
for (int i = front; i <= rear; i++) {
cout << arr[i] << " ";
}
cout << endl;
}
};
// Main function
int main() {
Queue q;
int choice, value;
while (true) {
cout << "\n--- MENU ---\n";
cout << "1. Enqueue (Insert)\n";
cout << "2. Dequeue (Delete)\n";
cout << "3. Display Queue\n";
cout << "4. Exit\n";

36
cout << "Enter your choice: ";
cin >> choice;
switch (choice) {
case 1:
cout << "Enter value to insert: ";
cin >> value;
q.enqueue(value);
break;
case 2:
q.dequeue();
break;
case 3:
q.display();
break;
case 4:
cout << "Exiting...\n";
return 0;
default:
cout << "Invalid choice! Try again.\n";
}
}
}
Output:
--- MENU ---
1. Enqueue (Insert)
2. Dequeue (Delete)
3. Display Queue
4. Exit
Enter your choice: 1
Enter value to insert: 50

37
50 inserted into queue.

--- MENU ---


1. Enqueue (Insert)
2. Dequeue (Delete)
3. Display Queue
4. Exit
Enter your choice: 1
Enter value to insert: 90
90 inserted into queue.

--- MENU ---


1. Enqueue (Insert)
2. Dequeue (Delete)
3. Display Queue
4. Exit
Enter your choice: 1
Enter value to insert: 80
80 inserted into queue.

--- MENU ---


1. Enqueue (Insert)
2. Dequeue (Delete)
3. Display Queue
4. Exit
Enter your choice: 3
Queue elements: 50 90 80

--- MENU ---


1. Enqueue (Insert)

38
2. Dequeue (Delete)
3. Display Queue
4. Exit
Enter your choice: 2
50 deleted from queue.

39
Program – 11
Source Code:
/*Write a program to demonstrate functioning of a double ended queue.*/
#include <iostream>
using namespace std;
#define SIZE 10
class Deque {
private:
int arr[SIZE];
int front, rear;
public:
Deque() {
front = -1;
rear = -1;
}
// Check if deque is full
bool isFull() {
return ((front == 0 && rear == SIZE - 1) || (front == rear + 1));
}
// Check if deque is empty
bool isEmpty() {
return (front == -1);
}
// Insert at front
void insertFront(int value) {
if (isFull()) {
cout << "Deque Overflow! Cannot insert at front.\n";
return;
}
if (isEmpty()) {

40
front = rear = 0;
} else if (front == 0) {
front = SIZE - 1;
} else {
front--;
}

arr[front] = value;
cout << value << " inserted at front.\n";
}
// Insert at rear
void insertRear(int value) {
if (isFull()) {
cout << "Deque Overflow! Cannot insert at rear.\n";
return;
}
if (isEmpty()) {
front = rear = 0;
} else if (rear == SIZE - 1) {
rear = 0;
} else {
rear++;
}
arr[rear] = value;
cout << value << " inserted at rear.\n";
}
// Delete from front
void deleteFront() {
if (isEmpty()) {
cout << "Deque Underflow! Cannot delete from front.\n";

41
return;
}
cout << arr[front] << " deleted from front.\n";
if (front == rear) {
front = rear = -1;
} else if (front == SIZE - 1) {
front = 0;
} else {
front++;
}
}
// Delete from rear
void deleteRear() {
if (isEmpty()) {
cout << "Deque Underflow! Cannot delete from rear.\n";
return;
}
cout << arr[rear] << " deleted from rear.\n";
if (front == rear) {
front = rear = -1;
} else if (rear == 0) {
rear = SIZE - 1;
} else {
rear--;
}
}
// Display deque
void display() {
if (isEmpty()) {
cout << "Deque is empty.\n";

42
return;
}
cout << "Deque elements: ";
int i = front;
while (true) {
cout << arr[i] << " ";
if (i == rear)
break;
i = (i + 1) % SIZE;
}
cout << endl;
}
};
// Main function
int main() {
Deque dq;
int choice, value;
while (true) {
cout << "\n--- DEQUE MENU ---\n";
cout << "1. Insert Front\n";
cout << "2. Insert Rear\n";
cout << "3. Delete Front\n";
cout << "4. Delete Rear\n";
cout << "5. Display\n";
cout << "6. Exit\n";
cout << "Enter your choice: ";
cin >> choice;
switch (choice) {
case 1:
cout << "Enter value to insert at front: ";

43
cin >> value;
dq.insertFront(value);
break;
case 2:
cout << "Enter value to insert at rear: ";
cin >> value;
dq.insertRear(value);
break;
case 3:
dq.deleteFront();
break;
case 4:
dq.deleteRear();
break;
case 5:
dq.display();
break;
case 6:
cout << "Exiting...\n";
return 0;
default:
cout << "Invalid choice! Try again.\n";
}
}
}
Output:
--- DEQUE MENU ---
1. Insert Front
2. Insert Rear
3. Delete Front

44
4. Delete Rear
5. Display
6. Exit
Enter your choice: 1
Enter value to insert at front: 50
50 inserted at front.

--- DEQUE MENU ---


1. Insert Front
2. Insert Rear
3. Delete Front
4. Delete Rear
5. Display
6. Exit
Enter your choice: 2
Enter value to insert at rear:
65
65 inserted at rear.

--- DEQUE MENU ---


1. Insert Front
2. Insert Rear
3. Delete Front
4. Delete Rear
5. Display
6. Exit
Enter your choice: 3
50 deleted from front.

45
Program – 12
Source Code:
/*Write a program to read the postfix arithmetic expression and evaluate its value using the
stack.*/
#include <iostream>
#include <stack>
#include <cctype> // for isdigit
#include <string>
using namespace std;
// Function to evaluate postfix expression
int evaluatePostfix(const string& expression) {
stack<int> stk;
for (char ch : expression) {
if (ch == ' ') {
continue; // Skip spaces
}
if (isdigit(ch)) {
// Convert char to int and push
stk.push(ch - '0');
} else {
// Operator encountered: pop two operands
if (stk.size() < 2) {
cout << "Invalid Expression!" << endl;
return -1;
}
int operand2 = stk.top(); stk.pop();
int operand1 = stk.top(); stk.pop();
int result;
switch (ch) {
case '+': result = operand1 + operand2; break;
case '-': result = operand1 - operand2; break;
46
case '*': result = operand1 * operand2; break;
case '/':
if (operand2 == 0) {
cout << "Division by zero error!\n";
return -1;
}
result = operand1 / operand2; break;
default:
cout << "Invalid operator: " << ch << endl;
return -1;
}
stk.push(result);
}
}
if (stk.size() != 1) {
cout << "Invalid postfix expression!\n";
return -1;
}
return stk.top();
}
// Main function
int main() {
string expression;
cout << "Enter postfix expression (single-digit operands and space-separated): ";
getline(cin, expression);
int result = evaluatePostfix(expression);
if (result != -1)
cout << "Result of postfix expression: " << result << endl;
return 0;
}

47
Output:

Enter postfix expression: 5 6 2 + * 12 4 / -


5 * (6 + 2) - (12 / 4)
Result of postfix expression: 36

48
Program – 13
Source Code
/*Write a program to show how to handle the overflow and underflow situation in stack.*/
#include <iostream>
using namespace std;
#define SIZE 5 // Stack size
class Stack {
private:
int arr[SIZE];
int top;
public:
Stack() {
top = -1; // Initialize top to -1 (stack is empty)
}
// Push operation (handles overflow)
void push(int value) {
if (top == SIZE - 1) {
cout << "Stack Overflow! Cannot push " << value << endl;
} else {
arr[++top] = value;
cout << value << " pushed onto the stack.\n";
}
}
// Pop operation (handles underflow)
void pop() {
if (top == -1) {
cout << "Stack Underflow! Cannot pop from an empty stack.\n";
} else {
cout << arr[top--] << " popped from the stack.\n";
}

49
}
// Display stack contents
void display() {
if (top == -1) {
cout << "Stack is empty.\n";
} else {
cout << "Stack elements: ";
for (int i = top; i >= 0; i--) {
cout << arr[i] << " ";
}
cout << endl;
}
}
};
// Main function
int main() {
Stack s;
int choice, value;
while (true) {
cout << "\n--- STACK MENU ---\n";
cout << "1. Push\n";
cout << "2. Pop\n";
cout << "3. Display\n";
cout << "4. Exit\n";
cout << "Enter your choice: ";
cin >> choice;
switch (choice) {
case 1:
cout << "Enter value to push: ";
cin >> value;

50
s.push(value);
break;
case 2:
s.pop();
break;
case 3:
s.display();
break;
case 4:
cout << "Exiting program...\n";
return 0;
default:
cout << "Invalid choice! Try again.\n";
}
}
}
Output:
--- STACK MENU ---
1. Push
2. Pop
3. Display
4. Exit
Enter your choice: 1
Enter value to push: 5
5 pushed onto the stack.

--- STACK MENU ---


1. Push
2. Pop
3. Display

51
4. Exit
Enter your choice: 1
Enter value to push: 6
6 pushed onto the stack.

--- STACK MENU ---


1. Push
2. Pop
3. Display
4. Exit
Enter your choice: 2
6 popped from the stack.

--- STACK MENU ---


1. Push
2. Pop
3. Display
4. Exit
Enter your choice: 2
5 popped from the stack.

--- STACK MENU ---


1. Push
2. Pop
3. Display
4. Exit
Enter your choice: 2
Stack Underflow! Cannot pop from an empty stack.

52
Program – 14
Source Code:
/*Write a program to create binary search tree using the concept of linked list and array,
suppose data set will be given at the run time.*/
#include <iostream>
using namespace std;
// Structure of a node in BST
struct Node {
int data;
Node* left;
Node* right;
// Constructor
Node(int value) {
data = value;
left = right = nullptr;
}
};
// Function to insert a node in BST
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;
}
// Inorder traversal (LNR)
void inorder(Node* root) {
if (root != nullptr) {
53
inorder(root->left);
cout << root->data << " ";
inorder(root->right);
}
}
int main() {
Node* root = nullptr;
int n, value;
cout << "Enter the number of elements to insert in BST: ";
cin >> n;
cout << "Enter " << n << " values:\n";
for (int i = 0; i < n; i++) {
cin >> value;
root = insert(root, value);
}
cout << "\nIn-order Traversal of BST: ";
inorder(root);
cout << endl;
return 0;
}
Output:
Enter the number of elements to insert in BST: 5
Enter 5 values:
50
60
10
30
40

In-order Traversal of BST: 10 30 40 50 60

54
Program – 15
Source Code:
/*Write a program to create a binary tree with any data set and traverse the data items in pre-
order, in-order and post-order manner using recursion.*/
#include <iostream>
using namespace std;
// Define a node in the binary tree
struct Node {
int data;
Node* left;
Node* right;
Node(int value) {
data = value;
left = right = nullptr;
}
};
// Function to create a binary tree recursively
Node* createTree() {
int value;
cout << "Enter data (-1 for NULL node): ";
cin >> value;
if (value == -1) {
return nullptr;
}
Node* newNode = new Node(value);
cout << "Enter left child of " << value << endl;
newNode->left = createTree();
cout << "Enter right child of " << value << endl;
newNode->right = createTree();
return newNode;
}
55
// In-order traversal (LNR)
void inorder(Node* root) {
if (root != nullptr) {
inorder(root->left);
cout << root->data << " ";
inorder(root->right);
}
}
// Pre-order traversal (NLR)
void preorder(Node* root) {
if (root != nullptr) {
cout << root->data << " ";
preorder(root->left);
preorder(root->right);
}
}
// Post-order traversal (LRN)
void postorder(Node* root) {
if (root != nullptr) {
postorder(root->left);
postorder(root->right);
cout << root->data << " ";
}
}
int main() {
cout << "Create a Binary Tree\n";
Node* root = createTree();
cout << "\nIn-order Traversal: ";
inorder(root);
cout << "\nPre-order Traversal: ";

56
preorder(root);
cout << "\nPost-order Traversal: ";
postorder(root);
cout << endl;
return 0;
}
Output:
Enter right child of 20
Enter data (-1 for NULL node): -1
Enter right child of 10
Enter data (-1 for NULL node): 30
Enter left child of 30
Enter data (-1 for NULL node): -1
Enter right child of 30
Enter data (-1 for NULL node): -1

In-order Traversal: 20 10 30
Pre-order Traversal: 10 20 30
Post-order Traversal: 20 30 10

57
Program – 16
Source Code:
/*Write a program to perform deletion of any data item from the binary search tree.*/
#include <iostream>
using namespace std;
// Define the structure of a node
struct Node {
int data;
Node* left;
Node* right;
Node(int value) {
data = value;
left = right = nullptr;
}
};
// Function to insert data into BST
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 find the node with the minimum value in a BST
Node* findMin(Node* root) {
while (root && root->left != nullptr)
root = root->left;
return root;

58
}
// Function to delete a node from the BST
Node* deleteNode(Node* root, int key) {
if (root == nullptr)
return root;
// Search for the node to delete
if (key < root->data)
root->left = deleteNode(root->left, key);
else if (key > root->data)
root->right = deleteNode(root->right, key);
else {
// Node found: three cases
// Case 1: Node with no children (leaf node)
if (root->left == nullptr && root->right == nullptr) {
delete root;
return nullptr;
}
// Case 2: Node with only one child
else if (root->left == nullptr) {
Node* temp = root->right;
delete root;
return temp;
}
else if (root->right == nullptr) {
Node* temp = root->left;
delete root;
return temp;
}
// Case 3: Node with two children
Node* temp = findMin(root->right); // Find in-order successor

59
root->data = temp->data; // Copy data
root->right = deleteNode(root->right, temp->data); // Delete successor
}
return root;
}
// In-order traversal of BST
void inorder(Node* root) {
if (root != nullptr) {
inorder(root->left);
cout << root->data << " ";
inorder(root->right);
}
}
int main() {
Node* root = nullptr;
int n, value, delValue;
cout << "Enter number of nodes to insert: ";
cin >> n;
cout << "Enter " << n << " values:\n";
for (int i = 0; i < n; i++) {
cin >> value;
root = insert(root, value);
}
cout << "\nIn-order Traversal before Deletion: ";
inorder(root);
cout << "\nEnter value to delete: ";
cin >> delValue;
root = deleteNode(root, delValue);
cout << "In-order Traversal after Deletion: ";
inorder(root);

60
cout << endl;
return 0;
}
Output:
Enter number of nodes to insert: 5
Enter 5 values:
50
40
30
20
10
In-order Traversal before Deletion: 10 20 30 40 50
Enter value to delete: 30
In-order Traversal after Deletion: 10 20 40 50
Write a program to find the height of any tree.
#include <iostream>
using namespace std;
// Define the structure of a node
struct Node {
int data;
Node* left;
Node* right;
Node(int value) {
data = value;
left = right = nullptr;
}
};
// Function to insert a node in a binary tree (you can modify for BST as needed)
Node* insert(Node* root, int value) {
if (root == nullptr) {

61
return new Node(value);
}
if (value < root->data)
root->left = insert(root->left, value);
else
root->right = insert(root->right, value);
return root;
}
// Function to calculate the height of a binary tree
int findHeight(Node* root) {
if (root == nullptr)
return 0;
int leftHeight = findHeight(root->left);
int rightHeight = findHeight(root->right);
return 1 + max(leftHeight, rightHeight);
}
// In-order traversal to display the tree
void inorder(Node* root) {
if (root != nullptr) {
inorder(root->left);
cout << root->data << " ";
inorder(root->right);
}
}
int main() {
Node* root = nullptr;
int n, value;
cout << "Enter number of nodes: ";
cin >> n;
cout << "Enter " << n << " values:\n";

62
for (int i = 0; i < n; ++i) {
cin >> value;
root = insert(root, value);
}
cout << "\nIn-order Traversal: ";
inorder(root);
int height = findHeight(root);
cout << "\nHeight of the tree: " << height << endl;
return 0;
}
Output:
Enter number of nodes: 5
Enter 5 values:
50
30
70
40
50

In-order Traversal: 30 40 50 50 70
Height of the tree: 3

63
Program – 17
Source Code:
/*Write a program to create any given undirected graph using the adjacency matrix, and
print each node/element with list of its adjacent elements.*/
#include <iostream>
using namespace std;
const int MAX = 100; // Maximum number of nodes
void createGraph(int adj[MAX][MAX], int nodes, int edges) {
int u, v;
for (int i = 0; i < edges; ++i) {
cout << "Enter edge (u v): ";
cin >> u >> v;
adj[u][v] = 1;
adj[v][u] = 1; // Because the graph is undirected
}
}
void printAdjacencyList(int adj[MAX][MAX], int nodes) {
cout << "\nAdjacency List:\n";
for (int i = 0; i < nodes; ++i) {
cout << "Node " << i << ": ";
for (int j = 0; j < nodes; ++j) {
if (adj[i][j] == 1)
cout << j << " ";
}
cout << endl;
}
}
int main() {
int nodes, edges;
int adj[MAX][MAX] = {0}; // Initialize with 0
cout << "Enter number of nodes: ";
64
cin >> nodes;
cout << "Enter number of edges: ";
cin >> edges;
createGraph(adj, nodes, edges);
printAdjacencyList(adj, nodes);
return 0;
}
Output:
Enter number of nodes: 4
Enter number of edges: 3
Enter edge (u v): 5 3
Enter edge (u v): 4 2
Enter edge (u v): 4 1

Adjacency List:
Node 0:
Node 1:
Node 2:
Node 3:

65
Program – 18
Source Code:
/*Write a program to find the minimum spanning tree of any given graph.*/
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
// Structure to represent an edge
struct Edge {
int u, v, weight;
};
// Comparator to sort edges by weight
bool compare(Edge a, Edge b) {
return a.weight < b.weight;
}
// Disjoint Set Union (Union-Find)
class DSU {
private:
vector<int> parent, rank;
public:
DSU(int n) {
parent.resize(n);
rank.resize(n, 0);
for (int i = 0; i < n; i++)
parent[i] = i;
}
int find(int x) {
if (parent[x] != x)
parent[x] = find(parent[x]); // Path compression
return parent[x];

66
}
bool unionByRank(int x, int y) {
int rootX = find(x);
int rootY = find(y);
if (rootX == rootY)
return false;
if (rank[rootX] < rank[rootY])
parent[rootX] = rootY;
else if (rank[rootX] > rank[rootY])
parent[rootY] = rootX;
else {
parent[rootY] = rootX;
rank[rootX]++;
}
return true;
}
};

int main() {
int V, E;
cout << "Enter number of vertices and edges: ";
cin >> V >> E;
vector<Edge> edges(E);
cout << "Enter edges in the format: u v weight\n";
for (int i = 0; i < E; i++) {
cin >> edges[i].u >> edges[i].v >> edges[i].weight;
}
// Sort edges by weight
sort(edges.begin(), edges.end(), compare);

67
DSU dsu(V);
vector<Edge> mst;
int totalWeight = 0;
for (Edge edge : edges) {
if (dsu.unionByRank(edge.u, edge.v)) {
mst.push_back(edge);
totalWeight += edge.weight;
}
}
cout << "\nMinimum Spanning Tree Edges:\n";
for (Edge e : mst) {
cout << e.u << " - " << e.v << " : " << e.weight << "\n";
}
cout << "Total weight of MST: " << totalWeight << endl;
return 0;
}
Output:

Enter number of vertices and edges: 4 5


Enter edges in the format: u v weight
0 1 10
026
035
1 3 15
234
Minimum Spanning Tree Edges:
2-3:4
0-3:5
0 - 1 : 10
Total weight of MST: 19

68
Program – 19
Source Code:
/*Write a program to search any run time given element from the array of 10 elements in the
array are unsorted.*/
#include <iostream>
using namespace std;
int main() {
int arr[10];
int key, found = 0;
cout << "Enter 10 unsorted elements:\n";
for (int i = 0; i < 10; i++) {
cin >> arr[i];
}
cout << "Enter element to search: ";
cin >> key;
for (int i = 0; i < 10; i++) {
if (arr[i] == key) {
cout << "Element found at index " << i << " (position " << i + 1 << ")\n";
found = 1;
break;
}
}
if (!found) {
cout << "Element not found in the array.\n";
}
return 0;
}

69
Output:

Enter 10 unsorted elements:


50
0
40
30
10
20
60
90
70
80
Enter element to search: 20
Element found at index 5 (position 6)

70
Program – 20
Source Code:
/*Write a program to demonstrate the binary search.*/
#include <iostream>
#include <vector>
#include <algorithm> // For sort function
// Function to perform binary search
int binarySearch(const std::vector<int>& arr, int target) {
int left = 0, right = arr.size() - 1;
while (left <= right) {
int mid = left + (right - left) / 2; // Prevent potential overflow
if (arr[mid] == target) {
return mid; // Target found
}
if (arr[mid] < target) {
left = mid + 1; // Focus on the right half
} else {
right = mid - 1; // Focus on the left half
}
}
return -1; // Target not found
}
int main() {
// Declare and initialize an array
std::vector<int> arr = {34, 7, 23, 32, 5, 62};
// Sort the array for binary search
std::sort(arr.begin(), arr.end());
std::cout << "Sorted array: ";
for (int num : arr) {
std::cout << num << " ";

71
}
std::cout << "\n";
int target;
std::cout << "Enter the number to search: ";
std::cin >> target;
// Perform binary search
int result = binarySearch(arr, target);
if (result != -1) {
std::cout << "Element found at index " << result << ".\n";
} else {
std::cout << "Element not found in the array.\n";
}
return 0;
}
Output
Sorted array: 5 7 23 32 34 62
Enter the number to search: 32
Element found at index 3.

72

You might also like