0% found this document useful (0 votes)
2 views68 pages

DS File 2

The document contains multiple experiments demonstrating various data structure operations in C++. It includes implementations for linear arrays, strings, stacks, queues, and linked lists, covering operations such as insertion, deletion, traversal, and searching. Each experiment is accompanied by code snippets and aims to provide practical understanding of data structures.

Uploaded by

Vipin chopra
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)
2 views68 pages

DS File 2

The document contains multiple experiments demonstrating various data structure operations in C++. It includes implementations for linear arrays, strings, stacks, queues, and linked lists, covering operations such as insertion, deletion, traversal, and searching. Each experiment is accompanied by code snippets and aims to provide practical understanding of data structures.

Uploaded by

Vipin chopra
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/ 68

EXPERIMENT-1

AIM :-
Write a program to implement traversal, insertion and deletion of elements in a linear array.

CODE :-
#include<iostream> using
namespace std;

void printArray(int* arr, int n) {cout << "Array: ";


for (int i = 0; i < n; i++) {cout << arr[i] <<
" ";
}
cout << endl;
}
int insertSorted(int arr[], int n, int key, int capacity){if (n >= capacity){
cout << "Cannot insert more elements. Array is full." << endl;return n;
}
arr[n] = key; return (n
+ 1);
}
void insertElement(int arr[], int& n, int x, int pos){int capacity;
if (n >= capacity) {
cout << "Cannot insert more elements. Array is full." << endl;return;
}

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


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

int deleteElement(int arr[], int& n, int key){int pos = -1;

for (int i = 0; i < n; i++) {if (arr[i] == key)


{
pos = i; break;
}
}
if (pos == -1) {
cout << "Element not found." << endl;
}
else { for (int i = pos; i < n - 1;i++) {arr[i] = arr[i + 1];
}
return n;
}
}

int main() {
const int capacity = 100;
// Maximum capacity of the arrayint
arr[capacity] ;
int n;
cout<<"Enter size of array: ";cin>>n;
cout<<"Enter elements of array: ";for(int
i=0;i<n;i++)
{
cin>>arr[i];
}
int choice;
int key, pos, x;

while (true) {
cout << "\nChoose an option:" << endl;cout << "1.
Traversal" << endl;
cout << "2. Insert at the end" << endl;
cout << "3. Insert at any position" << endl;cout << "4. Delete an
element" << endl;
cout << "5. Exit" << endl;cin >>
choice;

switch (choice) {case 1:


printArray(arr, n);break;
case 2: cout << "Enter the element to insert at the end: ";cin >> key;
n = insertSorted(arr, n, key, capacity);break;
case 3: cout << "Enter the element to insert: ";cin >> x;
cout << "Enter the position to insert at:";cin >> pos;
insertElement(arr, n, x, pos); break;
case 4:
cout << "Enter the element to delete: "; cin >> key; n =
deleteElement(arr, n,key);break;

case 5: cout << "Exiting the program." << endl;return 0;

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

return 0;
}

OUTPUT:-
EXPERIMENT-2(A)

AIM :-
Program to fetch a substring from a string, find its position and length of substring.

CODE :-
#include <iostream> #include
<string> using namespace
std;

int main() {
string inputString;
cout << "Enter the input string:";getline(cin,
inputString);

string substring;
cout << "Enter the substring to search:";cin >> substring;
size_t position = inputString.find(substring);

if (position != string::npos) {
// Calculate the length of the substringsize_t length =
substring.length();
cout << "Input String: " << inputString << endl;cout << "Substring: "
<< substring << endl;
cout << "Position of Substring: " << position << endl;cout << "Length of
Substring: " << length << endl;
}
else {
cout << "Substring not found in the input string." << endl;
}

return 0;
}
OUTPUT:-
EXPERIMENT-2(B)

AIM :-
Program to replace one string from another.

CODE :-
#include <iostream> #include
<string> using namespace
std;

int main(){
string inputString; string
oldSubstring;string
newSubstring;

cout << "Enter the input string:";getline(cin,


inputString);

cout << "Enter the substring to be replaced: ";getline(cin,


oldSubstring);

cout << "Enter the replacement substring:";getline(cin,


newSubstring);
size_t position = inputString.find(oldSubstring);if (position !=
string::npos){
// Replace the oldSubstring with the newSubstring inputString.replace(position,
oldSubstring.length(), newSubstring);cout << "Updated String: " << inputString << endl;
}
else{
cout << "Substring not found in the input string." << endl;
}

return 0;
}
OUTPUT:-
EXPERIMENT-2(C)

AIM :-
Program for concatenation of two string.

CODE :-
#include <iostream> #include
<string> using namespace
std;

int main() {
string firstString; string secondString;

cout << "Enter the first string: ";getline(cin,


firstString);

cout << "Enter the second string:";getline(cin,


secondString);

string concatenatedString = firstString + secondString;


cout << "Concatenated String: " << concatenatedString << endl;return 0;
}

OUTPUT:-
EXPERIMENT-3(A)

AIM :-
Create a Stack and perform Pop, Push and Traverse operations on the stack using Arrays.

CODE :-
#include<bits/stdc++.h>using
namespace std;

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


*top = NULL;
void push (int x){ Node *t =
new Node;if(t==NULL)
cout<<"Stack overflow!";else {
t->data = x;
t->next = top;top = t;
}
return;
}
int pop(){
struct Node *p;int x =
-1; if(top==NULL){
cout<<"Stack is empty!";
}
else{
p = top;
top=top->next; x = p->data; delete p;
}
return x;
}
void display(){ struct
Node *p;p = top;
while(p!= NULL){
cout<<p-
>data<<" "
;p=p->next;
}
cout<<endl;
}
int main(){

cout<<"MENU - "<<endl;
fn1: cout<<"1. push"<<endl;cout<<"2.
pop"<<endl; cout<<"3. display"<<endl;
cout<<"4. exit"<<endl;

int choice ;
cout<<"Enter your choice - ";cin>>choice;
switch(choice){case
1:{
int x;
cout<<"Enter the number to be pushed to the stack - ";cin>>x;
push( x);
display();
cout<<endl;goto
fn1;
}
case 2:{
cout<<"The number popped out is - "<<pop()<<endl;display();
cout<<endl;goto
fn1;
}
case 3:{
cout<<"The elements of the stack are - "<<endl;display();
cout<<endl;goto
fn1;
}
case 4:{
return 0;
}
}
}

OUTPUT:-
EXPERIMENT-3(B)

AIM :-
Write a program to convert an infix expression to postfix conversion.

CODE :-
#include <iostream> #include
<stack> #include <string>
using namespace std;

int precedence(char op) {


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

string infixToPostfix(const string& infix) {stack<char>


operatorStack;
string postfix;

for (char ch : infix) {if


(isalnum(ch)) {
postfix += ch;
}
else if (ch == '(')
{ operatorStack.push(ch);
}
else if (ch == ')') {
while (!operatorStack.empty() && operatorStack.top() != '(') {postfix +=
operatorStack.top();
operatorStack.pop();
}
if (!operatorStack.empty() && operatorStack.top() == '(')operatorStack.pop();
}
else {
while (!operatorStack.empty() && precedence(ch) <=
precedence(operatorStack.top())) {
postfix += operatorStack.top();
operatorStack.pop();
}
operatorStack.push(ch);
}

while (!operatorStack.empty()) { postfix +=


operatorStack.top();operatorStack.pop();
}
return postfix;
}

int main() {
string infixExpression;
cout << "Enter an infix expression: ";getline(cin,
infixExpression);

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


" << postfixExpression << endl;

return 0;
}

OUTPUT:-
EXPERIMENT-3(C)

AIM :-
To implement balanced parentheses using stacks.

CODE :-
#include <iostream>
#include <stack> #include
<string>

using namespace std;

bool areParenthesesBalanced(const string &expression) {stack<char> stack;

for (char c : expression) {


if (c == '(' || c == '{' || c == '[') {stack.push(c);
}
else if (c == ')' || c == '}' || c == ']') {if (stack.empty()) {
return false; // Unmatched closing parenthesis
}

char top = stack.top(); stack.pop();


if ((c == ')' && top != '(') ||(c == '}' && top != '{') ||(c == ']'&& top != '[')) {
return false; // Mismatched opening and closing parenthesis
}
}
}
return stack.empty(); // If the stack is empty at the end, allparentheses are balanced.
}

int main() { string


expression;
cout << "Enter an expression: ";cin >>
expression;

if (areParenthesesBalanced(expression)) { cout << "Balanced


parentheses!" << endl;
}
else {
cout << "Unbalanced parentheses!" << endl;
}

return 0;
}

OUTPUT:-
EXPERIMENT-4(A)

AIM :-
To implement insertion, deletion,traversing and display using circular queue.

CODE :-
#include <iostream> using
namespace std;

const int MAX_SIZE = 5;

class CircularQueue
{
private:
int front, rear;
int queue[MAX_SIZE];

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

bool isFull()
{
return (front == 0 && rear == MAX_SIZE - 1) || (front == rear + 1);
}
bool isEmpty()
{
return front == -1;
}

void enqueue(int item)


{
if (isFull())
{
cout << "Queue is full. Cannot insert." << endl;
}
else
{
if (front == -1)
{
front = rear = 0;
}
else if (rear == MAX_SIZE - 1)
{
rear = 0;
}
else
{
rear++;
}
queue[rear] = item;
cout << "Inserted " << item << " into the queue." << endl;
}
}

int dequeue()
{
int item;
if (isEmpty())
{
cout << "Queue is empty. Cannot delete." << endl;return -1;
}
else
{
item = queue[front];if (front
== rear)
{
front = rear = -1;
}
else if (front == MAX_SIZE - 1)
{
front = 0;
}
else
{
front++;
}
return item;
}
}

void display()
{
if (isEmpty())
{
cout << "Queue is empty." << endl;
}
else
{
cout << "Queue elements: ";if (front <=
rear)
{
for (int i = front; i <= rear; i++)
{
cout << queue[i] << " ";
}
}
else
{
for (int i = front; i < MAX_SIZE; i++)
{
cout << queue[i] << " ";
}
for (int i = 0; i <= rear; i++)
{
cout << queue[i] << " ";
}
}
cout << endl;
}
}
};

int main()
{
CircularQueue queue;int
choice, item;

while (true)
{

cout << "Circular Queue Menu:" << endl; cout << "1.
Enqueue" << endl;
cout << "2. Dequeue" << endl; cout << "3.
Display" << endl; cout << "4. Exit" <<
endl;
cout << "Enter your choice:";cin >> choice;

switch (choice)
{
case 1:
cout << "Enter an element to enqueue: ";cin >> item;
queue.enqueue(item);break;
case 2:
item = queue.dequeue();if (item !=
-1)
{
cout << "Deleted element: " << item << endl;
}
break;
case 3:
queue.display();break;
case 4:
cout << "Exiting the program." << endl;return 0;
default:
cout << "Invalid choice. Please try again." << endl;
}
}
return 0;
}
OUTPUT:-
EXPERIMENT-4(B)

AIM :-
To implement insertion, deletion ,traversing and display using priority queue.

CODE :-
#include <iostream> #include
<queue> using namespace
std;

int main()
{
priority_queue<int> pq;

while (true)
{

cout << "Priority Queue Menu:" << endl;cout << "1.


Insert an element" << endl;
cout << "2. Delete the top element" << endl; cout << "3. Display the
priority queue" << endl;cout << "4. Exit" << endl;
cout << "Enter your choice:";int choice,
item;
cin >>choice; switch
(choice)
{
case 1:
cout << "Enter an element to insert: ";cin >> item;
pq.push(item);
cout<< item << " has been inserted into the priority queue." <<break;

case 2:
if (pq.empty())
{
endl;

cout << "Priority queue is empty. Cannot delete." << endl;


}
else
{
item = pq.top();
pq.pop();
cout << "Deleted element: " << item << endl;
}
break;

case 3:
cout << "Priority Queue elements: ";while (!
pq.empty())
{
cout << pq.top() << " ";pq.pop();
}
cout << endl;break;

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

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

return 0;
}
OUTPUT:-
EXPERIMENT-5(A)

AIM :-
Write a program to implement insertion, searching and deletion of elements in a singly LL.

CODE :-
#include <iostream> using
namespace std;struct Node
{
int data;
Node *next;
};

class LinkedList
{
private:
Node *head;

public:
LinkedList()
{
head = nullptr;
}

void insertNode(int value)


{
Node *newNode = new Node;
newNode->data = value; newNode-
>next = head; head = newNode;
}

void deleteNode(int value)


{
if (head == nullptr)
{
cout << "List is empty. Deletion not possible." << endl;return;
}

if (head->data == value)
{
Node *temp = head; head
= head->next;delete temp;
cout << "Node with value " << value << " deleted." << endl;return;
}

Node *current = head;


while (current->next != nullptr && current->next->data != value)
{
current = current->next;
}
if (current->next != nullptr)
{

Node *temp = current->next;


current->next = current->next->next;delete temp;
cout << "Node with value " << value << " deleted." << endl;
}
else
{
cout << "Node with value " << value << " not found." << endl;
}
}

void searchNode(int value)


{
Node *current = head; while (current !
= nullptr)
{
if (current->data == value)
{
cout << "Node with value " << value << " found." << endl;return;
}
current = current->next;
}
cout << "Node with value " << value << " not found." << endl;
}

void displayList()
{
Node *current = head; if (current
== nullptr)
{
cout << "List is empty." << endl;return;
}

cout << "Linked List: "; while (current


!= nullptr)
{
cout << current->data << " -> ";current =
current->next;
}
cout << "NULL" << endl;
}

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

int main()
{
LinkedList list;
int choice, value;

do
{
cout << "Menu:\n";
cout << "1. Insert Node\n";

cout << "2. Delete Node\n"; cout << "3.


Search Node\n"; cout << "4. Display
List\n";cout << "5. Exit\n";
cout << "Enter your choice: ";cin >> choice;

switch (choice)
{
case 1:
cout << "Enter value to insert: ";cin >> value;
list.insertNode(value);
break;
case 2:
cout << "Enter value to delete: ";cin >> value;
list.deleteNode(value);
break;
case 3:
cout << "Enter value to search: ";cin >> value;
list.searchNode(value);
break;
case 4:
list.displayList();break;
case 5:
cout << "Exiting the program." << endl;break;
default:
cout << "Invalid choice. Please try again." << endl;
}
} while (choice != 5);

return 0;
}

OUTPUT:-
EXPERIMENT-5(B)

AIM :-
Write a program to implement insertion, searching and deletion of elements in a doubly LL.

CODE :-
#include <iostream> using
namespace std;struct Node
{
int data;
Node *prev;
Node *next;
};

class DoublyLinkedList
{
private:
Node *head;
Node *tail;

public:
DoublyLinkedList()
{
head = nullptr;tail =
nullptr;
}

void insertNode(int value)


{
Node *newNode = new Node;
newNode->data = value; newNode-
>prev = nullptr; newNode->next =
nullptr;

if (head == nullptr)
{
head = newNode;tail
= newNode;
}
else
{
newNode->next = head; head-
>prev = newNode; head =
newNode;
}
}
void deleteNode(int value)
{
Node *current = head;
while (current != nullptr){
if (current->data == value)
{

if (current == head)
{
head = current->next;if (head !
= nullptr)
{
head->prev = nullptr;
}
}
else if (current == tail)
{
tail = current->prev;if (tail !=
nullptr)
{
tail->next = nullptr;
}
}
else
{
current->prev->next = current->next;current->next-
>prev = current->prev;
}
delete current;
cout << "Node with value " << value << " deleted." << endl;
return;
}
current = current->next;
}
cout << "Node with value " << value << " not found." << endl;
}

void searchNode(int value)


{
Node *current = head; while (current !
= nullptr)
{
if (current->data == value)
{
cout << "Node with value " << value << " found." << endl;return;
}
current = current->next;
}
cout << "Node with value " << value << " not found." << endl;
}

void displayList()
{
Node *current = head; if (current
== nullptr)
{
cout << "List is empty." << endl;return;
}

cout << "Doubly Linked List (from head to tail): ";while (current != nullptr)
{
cout << current->data << " -> ";current =
current->next;
}
cout << "NULL" << endl;
}
}
;

int main()
{
DoublyLinkedList list;int
choice, value;

do
{
cout << "Menu:\n";
cout << "1. Insert Node\n"; cout << "2.
Delete Node\n"; cout << "3. Search
Node\n"; cout << "4. Display List\n";cout
<< "5. Exit\n";
cout << "Enter your choice: ";cin >> choice;

switch (choice)
{
case 1:
cout << "Enter value to insert: ";cin >> value;
list.insertNode(value);
break;
case 2:
cout << "Enter value to delete: ";cin >> value;
list.deleteNode(value);
break;
case 3:
cout << "Enter value to search: ";cin >> value;
list.searchNode(value);
break;
case 4:
list.displayList();break;
case 5:
cout << "Exiting the program." << endl;
break;
default:
cout << "Invalid choice. Please try again." << endl;
}
} while (choice != 5);

return 0;
}

OUTPUT:-
EXPERIMENT-5(C)

AIM :-
Write a program to implement insertion, searching and deletion of elements in a circular LL.

CODE :-
#include <iostream> using
namespace std;struct Node
{
int data;
Node *next;
};

class CircularLinkedList
{
private:
Node *head;

public:
CircularLinkedList()
{
head = nullptr;
}

void insertNode(int value)


{
Node *newNode = new Node;
newNode->data = value;
if (head == nullptr)
{
head = newNode; newNode-
>next = head;
}
else
{
Node *current = head;
while (current->next != head)
{
current = current->next;
}
current->next = newNode;
newNode->next = head;
}
}

void deleteNode(int value)


{
if (head == nullptr)
{
cout << "List is empty. Deletion not possible." << endl;return;
}

if (head->data == value)
{
Node *current = head;
while (current->next != head)
{
current = current->next;
}
current->next = head->next;if (head ==
head->next)
{
head = nullptr;
}
else
{
head = head->next;
}
delete current;
cout << "Node with value " << value << " deleted." << endl;return;
}

Node *current = head;Node


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

if (current != head)
{
prev->next = current->next;delete
current;
cout << "Node with value " << value << " deleted." << endl;
}
else
{
cout << "Node with value " << value << " not found." << endl;
}
}

void searchNode(int value)


{
if (head == nullptr)
{
cout << "List is empty. Searching not possible." << endl;return;
}

Node *current = head;do


{
if (current->data == value)
{
cout << "Node with value " << value << " found." << endl;return;
}
current = current->next;
} while (current != head);

cout << "Node with value " << value << " not found." << endl;
}
void displayList()
{
if (head == nullptr)
{
cout << "List is empty." << endl;return;
}

Node *current = head;


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

int main()
{
CircularLinkedList list;int choice,
value;

do
{
cout << "Menu:\n";
cout << "1. Insert Node\n"; cout << "2.
Delete Node\n"; cout << "3. Search
Node\n"; cout << "4. Display List\n";cout
<< "5. Exit\n";
cout << "Enter your choice: ";cin >> choice;

switch (choice)
{
case 1:
cout << "Enter value to insert: ";cin >> value;
list.insertNode(value);break;
case 2:
cout << "Enter value to delete: ";cin >> value;
list.deleteNode(value);
break;
case 3:
cout << "Enter value to search: ";cin >> value;
list.searchNode(value);
break;
case 4:
list.displayList();break;
case 5:
cout << "Exiting the program." << endl;break;
default:
cout << "Invalid choice. Please try again." << endl;
}
} while (choice != 5);

return 0;
}
OUTPUT:-
EXPERIMENT-6

AIM :-
Program to implement Stack using Linked List

CODE :-
#include <iostream> using
namespace std;struct Node
{
int data;
Node *next;
};

class Stack
{
private:
Node *top;int
size;
int capacity;

public:
Stack(int maxCapacity)
{
top = nullptr;size =
0;
capacity = maxCapacity;
}

bool isFull()
{
return size >= capacity;
}

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

void push(int value)


{
if (isFull())
{
cout << "Stack overflow. Cannot push " << value << "." << endl;return;
}

Node *newNode = new Node;


newNode->data = value; newNode-
>next = top;
top = newNode;
size++;
cout << "Pushed: " << value << endl;
}

void pop()
{

if (isEmpty())
{
cout << "Stack is empty. Pop operation not possible." << endl;return;
}

Node *temp = top;top =


top->next;
int poppedValue = temp->data;delete temp;
size--;
cout << "Popped: " << poppedValue << endl;
}

bool getTop(int &topValue)


{
if (isEmpty())
{
cout << "Stack is empty. No top element." << endl;
return false;
}
topValue = top->data;return
true;
}
};

int main()
{
int capacity, choice, value, topValue;

cout << "Enter the maximum capacity of the stack: ";cin >> capacity;
Stack stack(capacity);do
{
cout << "Menu:\n"; cout <<
"1. Push\n";cout << "2.
Pop\n";
cout << "3. Get Top\n";cout <<
"4. Exit\n";
cout << "Enter your choice: ";cin >> choice;

switch (choice)
{
case 1:
if (!stack.isFull())
{
cout << "Enter value to push: ";cin >> value;
stack.push(value);
}
else
{

cout << "Stack is full. Cannot push more elements." <<

endl;
}

break;
case 2:
stack.pop();break;
case 3:
if (stack.getTop(topValue))
{
cout << "Top element: " << topValue << endl;
}
break;
case 4:
cout << "Exiting the program." << endl;break;
default:
cout << "Invalid choice. Please try again." << endl;
}
} while (choice != 4);return 0;
}

OUTPUT:-
EXPERIMENT-7

AIM :-
Program to implement Queue using Linked List

CODE :-

#include <iostream> using


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

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

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

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

void enqueue(int value)


{
Node *newNode = new Node;
newNode->data = value;
newNode->next = nullptr;

if (isEmpty())
{
front = newNode;rear =
newNode;
}
else
{
rear->next = newNode;rear =
newNode;
}
cout << "Enqueued: " << value << endl;
}

void dequeue()
{
if (isEmpty())
{

cout << "Queue is empty. Dequeue operation not possible." <<return;

endl;

Node *temp = front;


int dequeuedValue = front->data;front = front-
>next;
delete temp;
cout << "Dequeued: " << dequeuedValue << endl;
}

int getFront()
{
if (isEmpty())
{
cout << "Queue is empty. No front element." << endl;return -1; // Return -1 to
indicate an empty queue.
}
return front->data;
}
};

int main()
{
Queue queue;
int choice, value, frontValue;

do
{
cout << "Menu:\n";
cout << "1. Enqueue\n"; cout << "2.
Dequeue\n"; cout << "3. Get
Front\n";cout << "4. Exit\n";
cout << "Enter your choice: ";cin >> choice;

switch (choice)
{
case 1:
cout << "Enter value to enqueue: ";cin >> value;
queue.enqueue(value);break;
case 2:
queue.dequeue();break;
case 3:
frontValue = queue.getFront();if
(frontValue != -1)
{
cout << "Front element: " << frontValue << endl;
}
break;

case 4:
cout << "Exiting the program." << endl;break;
default:
cout << "Invalid choice. Please try again." << endl;
}
} while (choice != 4);

return 0;
}

OUTPUT:-
EXPERIMENT-8(A)

AIM :-
Insertion, Deletion and Traversal in Binary Search Tree

CODE :-
#include <iostream> using
namespace std;

struct Node
{
int data;
Node *left;
Node *right;
Node(int val) : data(val), left(NULL), right(NULL) {}
};

Node *recursiveInsert(Node *root, int val)


{
if (root == NULL)
{
return new Node(val);
}

if (val < root->data)


{
root->left = recursiveInsert(root->left, val);
}
else
{
root->right = recursiveInsert(root->right, val);
}

return root;
}

Node *nonRecursiveInsert(Node *root, int val)


{
Node *newNode = new Node(val);if (root
== NULL)
{
return newNode;
}

Node *current = root;while


(true)
{
if (val < current->data)
{
if (current->left == NULL)
{
current->left = newNode;break;
}
current = current->left;
}
else
{
if (current->right == NULL)
{
current->right = newNode;break;
}
current = current->right;
}
}

return root;
}

void inOrderTraversal(Node *root)


{
if (root == NULL)return;
inOrderTraversal(root->left); cout << root-
>data << " "; inOrderTraversal(root->right);
}

Node *findMin(Node *node)


{
while (node->left != NULL)
{
node = node->left;
}
return node;
}

Node *deleteNode(Node *root, int val)


{
if (root == NULL)return
root;

if (val < root->data)


{
root->left = deleteNode(root->left, val);
}
else if (val > root->data)
{
root->right = deleteNode(root->right, val);
}
else
{
if (root->left == NULL)
{
Node *temp = root->right;delete
root;
return temp;
}
else if (root->right == NULL)
{
Node *temp = root->left;delete
root;
return temp;
}

Node *temp = findMin(root->right);


root->data = temp->data;
root->right = deleteNode(root->right, temp->data);
}

return root;
}

int main()
{
Node *root = NULL;
root = recursiveInsert(root, 50); root =
recursiveInsert(root, 30); root =
recursiveInsert(root, 70); root =
recursiveInsert(root, 20); root =
recursiveInsert(root, 40); root =
recursiveInsert(root, 60); root =
recursiveInsert(root, 80);

cout << "In-order Traversal: ";


inOrderTraversal(root);
cout << endl;

root = deleteNode(root, 30);


cout << "In-order Traversal after deletion of 30: ";inOrderTraversal(root);
cout << endl;

return 0;
}

OUTPUT:-
EXPERIMENT-8(B)

AIM :-
Insertion, Deletion and Traversal in Threaded Binary Tree

CODE :-
#include <iostream> using
namespace std;
class ThreadedBinarySearchTree {private:
struct Node {
int data;
Node* left;
Node* right;
bool isThreaded;
};

Node* root;

Node* createNode(int data) { Node*


newNode = new Node; newNode->data
= data; newNode->left = nullptr;
newNode->right = nullptr; newNode-
>isThreaded = true;return newNode;
}

Node* findInOrderSuccessor(Node* node) {if (node ==


nullptr) return nullptr;
if (node->isThreaded) return node->right;node = node-
>right;
while (node != nullptr && !node->isThreaded) {node = node->left;
}
return node;
}
Node* findInOrderPredecessor(Node* node) {if (node ==
nullptr) return nullptr;
if (node->isThreaded) return node->left;node = node->left;
while (node != nullptr && !node->isThreaded) {node = node->right;
}
return node;
}

public:
ThreadedBinarySearchTree() {root =
nullptr;
}

void insert(int data) {


Node* newNode = createNode(data);

if (root == nullptr) {root =


newNode;
} else {
Node* current = root; Node*
parent = nullptr;

while (current != nullptr) {parent =


current;
if (data < current->data) {
if (!current->isThreaded) { current =
current->left;
} else {
break;
}
} else {
if (current->isThreaded) {current =
nullptr;
} else {
current = current->right;
}
}
}

if (data < parent->data) { newNode->left =


parent->left;newNode->right = parent;
parent->left = newNode; parent-
>isThreaded = true;
} else {
newNode->left = parent;
newNode->right = parent->right;parent->right
= newNode;
parent->isThreaded = true;
}
}
}

void deleteNode(int data) {


root = deleteNodeRecursive(root, data);
}

Node* deleteNodeRecursive(Node* root, int data) {if (root == nullptr) {


return root;
}

if (data < root->data) {


root->left = deleteNodeRecursive(root->left, data);
} else if (data > root->data) {
root->right = deleteNodeRecursive(root->right, data);
} else {
if (root->left == nullptr) { Node* temp =
root->right;if (!root->isThreaded) {
temp = findInOrderSuccessor(root);
}
delete root;return
temp;
} else if (root->right == nullptr) {Node* temp = root-
>left;
if (!root->isThreaded) {
temp = findInOrderPredecessor(root);
}
delete root;return
temp;
} else {
Node* temp = findInOrderSuccessor(root);root->data =
temp->data;
root->right = deleteNodeRecursive(root->right, temp->data);
}
}

return root;
}

void inOrderTraversal() {
Node* current = findLeftMostNode(root);while (current !
= nullptr) {
std::cout << current->data << " "; current =
findInOrderSuccessor(current);
}
std::cout << std::endl;
}

Node* findLeftMostNode(Node* node) {


if (node == nullptr) return nullptr;
while (node->left != nullptr && !node->isThreaded) {node = node->left;
}
return node;
}
};

int main() { ThreadedBinarySearchTree tbst;


tbst.insert(5); tbst.insert(3); tbst.insert(7);
tbst.insert(2); tbst.insert(4); tbst.insert(6);
tbst.insert(8);

cout << "In-order traversal: ";


tbst.inOrderTraversal();

tbst.deleteNode(3);
cout << "In-order traversal after deleting 3: ";tbst.inOrderTraversal();

tbst.deleteNode(7);
cout << "In-order traversal after deleting 7: ";tbst.inOrderTraversal();

return 0;
}

OUTPUT:-
EXPERIMENT-9(A)

AIM :-
Sorting - Insertion sort.

CODE :-
#include <iostream> using
namespace std;

void insertionSort(int *array, int size) {for (int i = 1; i < size;


i++) {
int currentElement = array[i];int j = i - 1;
while (j >= 0 && array[j] > currentElement) {array[j + 1] =
array[j];
j--;
}
array[j + 1] = currentElement;
}
}
int main() {
int array[] = {5, 3, 2, 1, 4};
int size = sizeof(array) / sizeof(array[0]);insertionSort(array,

size);

for (int i = 0; i < size; i++) {cout << array[i] <<


" ";
}
cout << endl;

return 0;
}
OUTPUT:-
EXPERIMENT-9(B)

AIM :-
Sorting - Quick sort.

CODE :-
#include <iostream> using

namespace std;

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

for (int j = low; j < high; j++) {if (array[j] <=


pivot) {
i++;
int temp = array[i]; array[i] =
array[j];array[j] = temp;
}
}

int temp = array[i + 1]; array[i + 1] =


array[high];array[high] = temp;

return i + 1;
}

void quickSort(int *array, int low, int high) {if (low < high) {
int pivotIndex = partition(array, low, high);

quickSort(array, low, pivotIndex - 1); quickSort(array, pivotIndex + 1, high);


}
}

int main() {
int array[] = {5, 3, 2, 1, 4};
int size = sizeof(array) / sizeof(array[0]);quickSort(array, 0, size -

1);

for (int i = 0; i < size; i++) {cout << array[i] <<


" ";
}
cout << endl;

return 0;
}

OUTPUT:-
EXPERIMENT-9(C)

AIM :-
Sorting - Merge sort.

CODE :-
#include <iostream> using

namespace std;

void merge(int *array, int low, int mid, int high) {int leftArraySize = mid -
low + 1;
int rightArraySize = high - mid;

int *leftArray = new int[leftArraySize]; int *rightArray = new


int[rightArraySize];

for (int i = 0; i < leftArraySize; i++) {leftArray[i] =


array[low + i];
}
for (int i = 0; i < rightArraySize; i++) {rightArray[i] =
array[mid + 1 + i];
}

int i = 0; int j = 0;
int k = low;

while (i < leftArraySize && j < rightArraySize) {if (leftArray[i] <=


rightArray[j]) {
array[k] = leftArray[i];i++;
} else {
array[k] = rightArray[j];j++;
} k+
+;
}

while (i < leftArraySize) {array[k] =


leftArray[i]; i++;
k++;
}

while (j < rightArraySize) {array[k] =


rightArray[j]; j++;
k++;
}

delete[] leftArray; delete[]


rightArray;
}

void mergeSort(int *array, int low, int high) {if (low < high) {
int mid = (low + high) / 2;

mergeSort(array, low, mid); mergeSort(array,


mid + 1, high);

merge(array, low, mid, high);


}
}

int main() {
int array[] = {5, 3, 2, 1, 4};
int size = sizeof(array) / sizeof(array[0]);mergeSort(array, 0, size -

1);

for (int i = 0; i < size; i++) {cout << array[i] <<


" ";
}
cout << endl;
return 0;
}

OUTPUT:-
EXPERIMENT-10(A)

Aim: Depth first traversal in a graph


CODE :-
#include <bits/stdc++.h>
using namespace std;

class Graph {
private:
void dfs(int node, vector<int> adj[], int vis[], vector<int> &ls) {
vis[node] = 1;
ls.push_back(node);
// traverse all its neighbours
for(auto it : adj[node]) {
// if the neighbour is not visited
if(!vis[it]) {
dfs(it, adj, vis, ls);
}
}
}
public:
// Function to return a list containing the DFS traversal of the graph.
vector<int> dfsOfGraph(int V, vector<int> adj[]) {
int vis[V] = {0};
int start = 0;

vector<int> ls;
// call dfs for starting node
dfs(start, adj, vis, ls);
return ls;
}
};

void addEdge(vector <int> adj[], int u, int v) {


adj[u].push_back(v);
adj[v].push_back(u);
}

void printAns(vector <int> &ans) {


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

int main()
{
vector <int> adj[5];
addEdge(adj, 0, 2);
addEdge(adj, 2, 4);
addEdge(adj, 0, 1);
addEdge(adj, 0, 3);

Graph g;
vector <int> ans = g.dfsOfGraph(5, adj);
printAns(ans);

return 0;
}

OUTPUT:-
EXPERIMENT-10(B)

AIM: Breadth first traversal in a graph


CODE:-
#include <bits/stdc++.h>
using namespace std;

class Graph
{
public:
// Function to return Breadth First Traversal of given graph.
vector<int> bfsOfGraph(int V, vector<int> adj[])
{
int vis[V] = {0};
vis[0] = 1;
queue<int> q;

q.push(0);
vector<int> bfs;

while (!q.empty())
{

int node = q.front();


q.pop();
bfs.push_back(node);

for (auto it : adj[node])


{

if (!vis[it])
{
vis[it] = 1;
q.push(it);
}
}
}
return bfs;
}
};

void addEdge(vector<int> adj[], int u, int v)


{
adj[u].push_back(v);
adj[v].push_back(u);
}
void printAns(vector<int> &ans)
{
for (int i = 0; i < ans.size(); i++)
{
cout << ans[i] << " ";
}
}

int main()
{
vector<int> adj[6];

addEdge(adj, 0, 1);
addEdge(adj, 1, 2);
addEdge(adj, 1, 3);
addEdge(adj, 0, 4);

Graph g;
vector<int> ans = g.bfsOfGraph(5, adj);
printAns(ans);

return 0;
}

OUTPUT:

You might also like