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

DS Lab programs

Uploaded by

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

DS Lab programs

Uploaded by

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

EX.

NO:1 ARRAY IMPLEMENTATION OF LIST ADT

Aim
To write a c++ program to implement list ADT using array

Algorithm
Step 1: start
Step 2: Initialise MAXSIZE and listsize and declare an array variable arr[MAXSIZE] to hold a list
Step 3: Create a method insert() with data and position as parameter to add an element in the array
for the given position with the respective data
Step 4: isEmpty() method is used to check whether the given list is empty or not and return true or
false based on the condition
Step 5: remove() checks if the data is present in the list ,then it removes the first occurrence of the
data from the list or else print as not found.
Step 6: search() check if the data is present in the list, then it must print ”Data found at the position”
followed by the position occurrence of the data.Else it must print “data not found”
Step 7: display() check if the list is not empty,then it prints all data in the list separated by a space
or else it must print as”List is Empty”.

Result:
Thus the C++ program for array implementation of LIST ADT is compiled and executed
successfully.
Program
#include <iostream>
#define MAXSIZE 100
using namespace std;
int arr[MAXSIZE], listSize = 0;
bool isEmpty()
{
return listSize==0;
}
void insert (int a,int b)
{
b--;
if(listSize>=MAXSIZE)
{
cout<<"List is Full"<<endl;
return;
}
if( b <0 || b+1>listSize+1)
{
cout<<"Invalid Position"<<endl;
return;
}
for(int i=listSize-1;i>=b;i--)
{
arr[i+1]=arr[i];
}
arr[b]=a;
listSize++;
}
void remove(int a)
{
int b= -1;
for(int i=0;i<listSize;i++)
{
if(arr[i]==a)
{
b=i;
break;
}
}
if (b== -1)
{
cout<<"Data not found"<<endl;
return;
}
for(int i=b;i<listSize-1;i++)
{
arr[i]=arr[i+1];
}
listSize--;
}
void search(int a)//RMGR
{
for(int i=0;i<listSize; i++)
{
if(arr[i]==a)
{
cout<<"Data found at the position "<<i+1<<endl;
return;
}
}
cout<<"Data not found"<<endl;;
}
void display()
{
if(isEmpty())
{
cout<<"List is Empty"<<endl;
return;
}
for(int i=0;i<listSize;i++)
{
cout<<arr[i] <<” ”;
}
cout<<endl;
}
void printReverse()
{
if(isEmpty())
{
for(int index = listSize-1;index >= 0; index--)
{
cout << arr[index] << “ “;
}
cout << endl;
}
else
{
cout << “List is Empty” << endl;
}
}
int main()
{
Int N, queryType, data, position;
cin >> N;
for(int query = 1; query <= N; query++)
{
cin >> queryType;
switch(queryType)
{
case 1:
cin >> data >> position;
insert(data, position);
break;
case 2:
cin >> data;
remove(data);
break;
case 3:
cin >> data;
search(data);
break;
case 4:
display();
break;
case 5:
printReverse();
break;
}
}
return 0;
}

Example Input/Output 1:
Input:
31
1 10 1
1 20 2
1 30 3
1 40 1
1 50 1
4
5
3 10
3 20
3 30
3 40
3 50
3 60
2 10
4
2 20
4
2 30
4
2 40
4
2 50
4
2 60
4
1 100 1
1 200 1
1 300 3
1 400 5
4
5
Output:
50 40 10 20 30
30 20 10 40 50
Data found at the position 3
Data found at the position 4
Data found at the position 5
Data found at the position 2
Data found at the position 1
Data not found
50 40 20 30
50 40 30
50 40
50
List is Empty
Data not found
List is Empty
Invalid Position
200 100 300
300 100 200
EX.NO:2A ARRAY IMPLEMENTATION OF STACK.
Aim :
To write a C++ program to implement stack using array.
Algorithm
Step 1: Start
Step 2: Declare Stack[MAX]; //Maximum size of Stack
Step 3: Check if the stack is full or not by comparing top with (MAX-1) If the stack is full, Then
print "Stack Overflow" i.e, stack is full and cannot be pushed with another element
Step 4: Else, the stack is not full Increment top by 1 and Set, stack[top] = x which pushes the
element x into the address pointed by top. // The element x is stored in a[top]
Step 5: Check if the stack is empty or not by comparing top with base of array i.e 0 If top is less
than 0, then stack is empty, print "Stack Underflow" Else, If top is greater than zero the stack is not
empty, then store the value pointed by top in a variable x=stack[top] and decrement top by 1. The
popped element is x.
Step 6:Peek()-Print the top most element of the stack.
Step 7:stop
Result:
Thus the C++ program for array implementation of stack is compiled and executed
successfully.
Program
#include<iostream>
#define MAXSIZE 5
using namespace std;
int arr[MAXSIZE],top=-1;
bool isEmpty()
{
return(top<0);
}
int push(int x)
{
if(top>=MAXSIZE-1){
Cout<<”Overflow”<<endl;
}
else{
top++;
arr[top]=x;
}
}
int pop()
{
if(top<0)
{
cout<<”Underflow”<<endl;
return 0;
}
else {
Int x=arr[top--];
return x;
}
}
Int peek()
{
If(top<0){
cout<<”Underflow”<<endl;
return 0; }
else{
int x=arr[top];
return x;
}
}
void display()
{
if(!isEmpty())
{
for(int index=0; index<=top; index++)
{
cout<<arr[index]<<” “;
}
else
{
cout<<”Stack is empty”;
}
cout<<endl;
}
int main()
{
int N,option,value;
cin>>N;
for(int ctr=0; ctr<N; ctr++)
{
cin>>option;
switch(option)
{
case 1:
cin>>value;
push(value);
break;
case 0:
cout<<peek()<<endl;
break;
case -1:
cout<<pop()<<endl;
break;
}
}
display();
return 0;
}
Example Input/Output 1:
19
1 10
1 20
1 30
0
1 70
1 80
1 90
0
-1
-1
-1
-1
-1
-1
0
1 50
1 60
1 70
0

Output:
30
Overflow
80
80
70
30
20
10
Underflow
0
Underflow
0
70
50 60 70
Example Input/output 2:
Input :
5
1 100
1 200
-1
-1
-1

Output:
200
100
Underflow
0
Stack is empty
EX.NO:2B LINKED LIST IMPLEMENTATION OF STACK.
Aim :
To write a C++ program to implement stack using linked List.
Algorithm
Step 1: start
Step 2: Declare the node structure of the stack with data and pointer
Step 3:Push() works as follows

• Create a newNode with the given data.


• Check whether the stack is empty (TOP == NULL).
• If it is empty, then set the pointer of the node to NULL.
• If it is not empty, then make the node point to TOP.
• Finally, make the newNode as TOP.

Step 4: Pop() works as follows

• Check whether stack is empty (top == NULL).


• If it is empty, then display "EMPTY STACK"
• If it is not empty, then create a temporary node and set it to TOP.
• Print the data of TOP.
• Make TOP to point to the next node.
• Delete the temporary node.

Step 5:Dispay() print the data of each node in the stack

Step 6:Stop

Result:
Thus the C++ program for Linked List implementation of stack is compiled and executed
successfully.
Program
#include<iostream>
using namespace std;
class Node
{
public :
int data;
Node *next;
Node(int val)
{
data=val;
next=NULL;
}
};
class Stack
{
public:
Node *head;
Stack()
{
head=NULL;
}
bool isEmpty();
void push(int);
int pop();
int peek();
};
bool Stack::isEmpty()
{
if(head==NULL)
{
return true;
}
else {
return false;
}
}
Void Stack::push(int data)
{
Node* newNode=new Node(data);
newNode->next=head;
head=newNode;
}
int Stack::pop()
{
if(isEmpty())
{
Cout<<”Stack Underflow”<<endl;
return 0;
}
else{
int removed=head->data;
Node* temp=head;
head=head->next;
delete temp;
return removed;
}
}
int Stack::peek()
{
if(isEmpty())
{
cout<<”Stack Empty”<<endl;
return 0;
}
else {
return head->data;
}
}
void display(Stack s)
{
if(s.isEmpty())
{
cout<<”Stack Empty”<<endl;
}
else{
Node *temp=s.head;
while(temp!=NULL)
{
cout<<temp->data<<” “;
temp=temp->next;
}
cout<<endl;
}
}
int main()
{
Stack s= Stack();
int N,queryType,data;
cin>>N;
for(int query=1;query<=N;query++)
{
cin>>queryType;
switch(queryTpe)
{
case 1:
cin>>data;
s.push(data);
break;
case 2:
if(!s.isEmpty())
{
cout<<”Popped Element: ”<<s.pop()<<endl;
}
case 3:
if(!s.isEmpty())
{
cout<<”Top Element: “<<s.peek()<<endl;
}
else
{
s.peek();
}
break;
case 4:
display(s);
break;
}
}
return 0;
}
Input:
17
1 11 Output:
1 22 55 44 33 22 11
1 33 Popped Element: 55 44 33 22 11
1 44 Top Element: 44
1 55 44 33 22 11
4 Popped Element: 44
2 Popped Element: 33
4 Popped Element: 22
3 Popped Element: 11
4 Stack Underflow
2 Stack Empty
2 Stack Empty
2
2
2
3
4
EX.NO:3A ARRAY IMPLEMENTATION OF QUEUE
Aim:
To write a C++ program to implement Queue using Array.
Algorithm:
1. Start by defining a maximum size for the queue and initializing an empty array of that size.
2. Initialize two variables: front and rear to keep track of the front and rear of the queue,
initially set both to -1.
3. To check if the queue is empty, check if front is equal to -1.
4. To check if the queue is full, check if rear is equal to the maximum size minus 1.
5. To enqueue an element, perform the following steps:
• Check if the queue is full. If it is, display an error message or return an appropriate
value.
• Increment rear by 1.
• Add the new element to the rear position in the array.
• If it is the first element being added, set front to 0.
6. To dequeue an element, perform the following steps:
• Check if the queue is empty. If it is, display an error message or return an appropriate
value.
• Retrieve the element at the front position from the array.
• Increment front by 1.
• If front becomes greater than rear, it means the queue is empty, so set both front and rear
to -1.
• Return the dequeued element.
7. To get the front element without dequeuing, simply return the element at the front position
in the array.
8. Stop the program.

Result:
Thus the C++ program for implementing Queue using array is compiled and executed
successfully.
Program
#include <iostream>
#define MAXSIZE 5
using namespace std;
int arr[MAXSIZE];
int front=0,qsize=0;
void add(int d){
if(qsize == MAXSIZE){
cout<<"Queue is full"<<endl;
}
else{
arr[qsize] = d;
qsize++;
}
}
int poll()
{
if(qsize == 0)
{
cout<<"Queue is empty"<<endl;
return 0;
}
else{
int data = arr[front];
for(int i = 0; i < qsize-1; i++){
arr[i] = arr[i+1];
}
qsize--;
return data;
}
}
int peek()
{
if(qsize == 0){
cout<<"Queue is empty" << endl;
return 0;
}else{
return arr[front];
}
}
bool isEmpty()
{
if(qsize == 0){
return true;
}
else{
return false;
}
}
int main(){
int N, option, value;
cin>>N;
for(int ctr= 0; ctr<N; ctr++){
cin >> option;
switch(option){
case 1:
cin>> value;
add(value);
break;
case 0:
cout<<peek() <<endl;
break;
case -1:
cout<<poll()<<endl;
break;
}
}
return 0;
}

Example Input/Output 1:
Input :
19
1 100
1 200
1 300 Output:
1 400 100
1 500 Queue is full
0 100
1 600 100
0 200
-1 300
-1 400
-1 500
-1 Queue is empty
-1 0
-1 Queue is empty
0 0
1 111 111
1 222
1 333
0
EX.NO:3B LINKED LIST IMPLEMENTATION OF QUEUE
Aim:
To write a CPP program to implement Queue using Linked List.
Algorithm:
1. Start the program.
2. Define a structure for the linked list node, which contains two fields: data (the value to be
stored in the node), and next (a pointer to the next node in the list).
3. Define a structure for the queue, which contains two fields: head (a pointer to the front of
the queue), and tail (a pointer to the back of the queue).
4. Initialize an empty queue by setting the head and tail pointers to NULL.

5. To add an item to the back of the queue (enqueue), create a new node with the given data,
and set its next pointer to NULL.
a. If the queue is empty (head and tail are both NULL), set both head and tail to point to the
new node.
b. Otherwise, set the next pointer of the current tail to point to the new node, and then
update the tail pointer to point to the new node.
6. To remove an item from the front of the queue (dequeue), check if the queue is empty by
checking if the head pointer is NULL. If the queue is empty, return an error or throw an exception.
a. Otherwise, retrieve the data from the node pointed to by the head pointer, and update the
head pointer to point to the next node in the list.
b. If the head pointer is now NULL (i.e., there were only one node in the list), also update
the tail pointer to NULL.
7. Repeat steps 4 and 5 as needed to enqueue and dequeue items from the queue.
8. When the queue is no longer needed, free the memory allocated for each node in the linked
list.
9. Stop the program

Result:
Thus the CPP program for implementing Queue using Linked List is compiled and executed
successfully.
Program
#include <iostream>
using namespace std;
class Node{
public:
int data;
Node* next;
Node(int val){
data = val;
next = NULL;
}
};
class Queue{
public:
Node *head;// head is the pointer
Node *tail;// tail is the pointer
Queue(){
head = NULL;
tail = NULL;
}
bool isEmpty();
void add(int);
int poll();
void display();
};
bool Queue::isEmpty()
{
if(head == NULL){
return true;
}
else{
return false;
}
}
void Queue::add(int data)
{
Node *new_node = new Node(data);
if(isEmpty()){
new_node->next = NULL;
head = new_node;
tail = new_node;
}
cout<<"Inserted: "<<data;
}
int Queue::poll()
{
if(isEmpty()){
cout<<"Queue is empty" << endl;
}
else
{
Node *temp = head;
int data = head -> data;
head = head -> next;
delete temp;
return data;
}
}
void Queue::display(){
if(isEmpty()){
cout<<"Queue is empty" << endl;
}
else{
Node *temp = head;
while(temp!= NULL){
cout<<temp->data <<" ";
temp = temp -> next;
}
cout<<endl;
}
}
void printQueueReverse(Node *ptr){
if(ptr != NULL){
printQueueReverse(ptr->next);
cout<<ptr->data<< " ";
}
}
void printReverse(Queue q){
if(q.isEmpty()){
cout<<"Queue is empty"<<endl;
return;
}
printQueueReverse(q.head);
cout<<endl;
}
int main(){
Queue q = Queue();
int N, queryType, data;
cin>>N;
for(int query = 1; query <= N; query++){
cin>>queryType;
switch(queryType){
case 1:
cin>>data;
q.add(data);
break;
case 2:
if(!q.isEmpty()){
cout<<"Polled: "<<q.poll()<<endl;
}
else{
q.poll();
}
break;
case 3:
q.display();
break;
}
}
return 0;
}

Example Input/Output 1:
Input:
19
1 100
1 200
1 300
1 400
1 500
0 Output
1 600 100
0 Queue is full
-1 100
-1 100
-1 200
-1 300
-1 400
-1 500
0 Queue is empty
1 111 0
1 222 Queue is empty
1 333 0
0 111
EX.NO:4A IMPLEMENTATION OF SINGLY LINKED LIST
Aim:
To write a CPP program for Singly Linked List implementation of List ADT.
Algorithm:
1. Start the program.
2. Define a structure for the linked list node. This structure should have two fields: one for the
data and one for a pointer to the next node in the list.
3. Define a head pointer to the first node in the list. Initially, this pointer will be NULL.
4. To insert a new node at the beginning of the list: a. Create a new node and set its data field
to the new value. b. Set the new node's next pointer to point to the current head node. c. Set
the head pointer to point to the new node.
5. To insert a new node at the end of the list:
a. Create a new node and set its data field to the new value.
b. Set its next pointer to NULL.
c. If the head pointer is NULL, set it to point to the new node.
d. Otherwise, traverse the list until you reach the end and set the next pointer of the
last node to the new node.
6. To traverse the list:
a. Start at the head node.
b. While the current node is not NULL, process its data and move to the next node.
7. To search for a specific value in the list:
a. Start at the head node.
b. While the current node is not NULL, check if its data matches the target value. If
so, return the node.
c. If the target value is not found, return NULL.
8. To delete a node from the list:
a. If the node to be deleted is the head node, set the head pointer to point to the next
node.
b. Otherwise, traverse the list until you reach the node before the one to be deleted.
c. Set the next pointer of the previous node to skip over the node to be deleted.
d. Free the memory allocated for the deleted node.

9. Stop the program.

Result:
Thus a CPP program for Singly Linked List implementation of List ADT is compiled and
executed successfully.
Program
#include <iostream>
using namespace std;
class Node
{
public:
int data;
Node *next;
Node(int Val)
{
data = val;
next = NULL;
}
};
class SinglyLinkedList
{
public:
Node *head, *tail;
SinglyLinkedList()
{
head = NULL;
tail = NULL;
}
bool isEmpty();
void append(int);
void insert(int, int);
void deleteNode(int);
bool search(int);
void printList();
};
bool SinglyLinkedList::isEmpty() {
return head == NULL;
}
void SinglyLinkedList::append(int data) {
Node* new_node = new Node(data);
if (isEmpty()) {
head = new_node;
tail = new_node;
return;
}
tail->next = new_node;
tail = new_node;
}
void SinglyLinkedList::insert(int prevData, int data) {
if (isEmpty()) {
cout << "list is empty\n";
return;
}
Node* current_node = head;
while (current_node != NULL) {
if (current_node->data == prevData) {
Node* new_node = new Node(data);
new_node->next = current_node->next;
current_node->next = new_node;
if (current_node == tail) {
tail = new_node;
}
return;
}
current_node = current_node->next;
}
cout << "previous val not in list\n";
}
void SinglyLinkedList::deleteNode(int data) {
if (isEmpty()) {
cout << "val not in list\n";
return;
}
Node* current_node = head;
Node* prev_node = NULL;
while (current_node != NULL) {
if (current_node->data == data) {
if (prev_node == NULL) {
head = current_node->next;
} else {
prev_node->next = current_node->next;
}
if (current_node == tail) {
tail = prev_node;
}
delete current_node;
return;
}
prev_node = current_node;
current_node = current_node->next;
}
cout << "val not in list\n";
}
bool SinglyLinkedList::search(int data) {
if (isEmpty()) {
return false;
}
Node* current_node = head;
while (current_node != NULL) {
if (current_node->data == data) {
return true;
}
current_node = current_node->next;
}
return false;
}
void SinglyLinkedList::printList()
{
if(isEmpty())
{
cout<< "list is empty"<<endl;
return;
}
Node *temp=head;
while(temp!=tail)
{
cout<<temp->data<<" ";
temp=temp->next;
}
cout<<tail->data<<endl;
}
int main()
{
SinglyLinkedList singlyLinkedList=SinglyLinkedList();
int N,queryType,preData,data;
cin>> N;
for(int query=1;query<=N;query++)
{
cin>> queryType;
switch(queryType)
{
case 1:
cin>> data;
singlyLinkedList.append(data);
break;
case 2:
cin>> prevData>> data;
singlyLinkedList.insert(preData,data);
break;
case 3:
cin>> data;
cout<< singlyLinkedList.deleteNode(data);
break;
case 4:
cin>> data;
cout<< singlyLinkedList.search(data)<<endl;
break;
case 5:
singlyLinkedList.printList();
}
}
return 0;
}
The query type can be one of the following types
1-append
2-insert
3-deleteNode
4-search
5-printList

Example Input/Output 1:
Input:
31
1 10
1 30
1 50
5
2 10 20
2 30 40
2 50 60
2 70 80
5
4 10
4 20
4 70
4 80
5
3 10
5
3 20
5
3 30
5
3 40
5
3 50
5
3 60
5
3 70
5
1 100
1 200
5
Output:
10 30 50
previous val not in list
10 20 30 40 50 60
1
1
0
0
10 20 30 40 50 60
20 30 40 50 60
30 40 50 60
40 50 60
50 60
60
list is empty
val not in list
list is empty
1000
EX.NO:4B IMPLEMENTATION OF DOUBLY LINKED LIST
Aim:
To write a CPP program for Doubly Linked List implementation of List ADT.
Algorithm:
1. Start the program.
2. Define a structure for each node of the list, containing three fields: a pointer to the previous
node, a pointer to the next node, and the data that the node holds.
3. Define a pointer to the head of the list and initialize it to NULL.
4. Define a pointer to the tail of the list and initialize it to NULL.
5. To add a node to the beginning of the list:
a. Create a new node and set its data field to the desired value.
b. Set the next field of the new node to the current head of the list, and the previous
field of the new node to NULL.
c. If the head of the list is not NULL, set the previous field of the current head node
to the new node.
d. Set the head pointer to point to the new node.
e. If the tail pointer is NULL, set it to point to the new node
6. To add a node to the end of the list:
a. Create a new node and set its data field to the desired value.
b. Set the next field of the new node to NULL, and the previous field of the new
node to the current tail of the list.
c. If the tail of the list is not NULL, set the next field of the current tail node to the
new node.
d. Set the tail pointer to point to the new node.
e. If the head pointer is NULL, set it to point to the new node.
7. To remove a node from the list:
a. Find the node to be removed.
b. If the node to be removed is the head of the list, set the head pointer to point to the
next node.
c. If the node to be removed is the tail of the list, set the tail pointer to point to the
previous node.
d. If the node to be removed is not the head or tail of the list, set the next field of the
previous node to point to the next node, and the previous field of the next node to point to
the previous node.
e. Free the memory occupied by the removed node.
8. To traverse the list:
a. Start at the head of the list.
b. For each node, process its data field.
c. Move to the next node until the end of the list is reached (i.e., the next field of the
current node is NULL).
9. Stop the program.

Result:
Thus a CPP program for Doubly Linked List implementation of List ADT is compiled and
executed successfully.
Program
#include <iostream>
using namespace std;
class Node
{
public:
int data;
Node *next,*prev;
Node(int val)
{
data=val;
next=prev=NULL;
}
};
class DoublyLinkedList
{
public:
Node *head,*tail;
DoublyLinkedList()
{
head=NULL;
tail=NULL;
}
bool isEmpty();
int getSize();
void insertAtNthposition(int, int);
void deleteNthNode(int);
bool search(int);
void display();
void printReverse();
};
bool DoublyLinkedList::isEmpty() {
return head == NULL;
}
int DoublyLinkedList::getSize() {
int count = 0;
Node* curr = head;
while (curr != NULL) {
count++;
curr = curr->next;
}
return count;
}
void DoublyLinkedList::insertAtNthPosition(int n, int val) {
int size = getSize();
if (n > size || n < 1) {
n = size + 1;
}
Node* newNode = new Node(val);
if (head == NULL) {
head = tail = newNode;
return;
}
if (n == 1) {
head->prev = newNode;
newNode->next = head;
head = newNode;
return;
}
if (n > size) {
tail->next = newNode;
newNode->prev = tail;
tail = newNode;
return;
}
Node* curr = head;
for (int i = 1; i < n - 1; i++) {
curr = curr->next;
}
newNode->prev = curr;
newNode->next = curr->next;
curr->next->prev = newNode;
curr->next = newNode;
}
void DoublyLinkedList::deleteNthNode(int n) {
if (isEmpty()) {
cout << "list is empty\n";
return;
}
int size = getSize();
if (n > size || n < 1) {
cout << "invalid position\n";
return;
}
if (n == 1) {
Node* temp = head;
head = head->next;
if (head != NULL) {
head->prev = NULL;
}
else {
tail = NULL;
}
delete temp;
return;
}
if (n == size) {
Node* temp = tail;
tail = tail->prev;
if (tail != NULL) {
tail->next = NULL;
}
else {
head = NULL;
}
delete temp;
return;
}
Node* curr = head;
for (int i = 1; i < n; i++) {
curr = curr->next;
}
curr->prev->next = curr->next;
curr->next->prev = curr->prev;
delete curr;
}
bool DoublyLinkedList::search(int val) {
Node* curr = head;
while (curr != NULL) {
if (curr->data == val) {
return true;
}
curr = curr->next;
}
return false;
}
void DoublyLinkedList::display()
{
if(isEmpty())
{
cout<<"list is empty"<<endl;
return;
}
Node *temp = head;
while(temp!=NULL)
{
cout<<temp->data<<" ";
temp = temp->next;
}
cout<<endl;
}
void DoublyLinkedList::printReverse()
{
if(isEmpty())
{
cout<<"list is empty"<<endl;
return;
}
Node *temp = tail;
while(temp!=NULL)
{
cout<<temp->data<<" ";
temp = temp->prev;
}
cout<<endl;
}
int main()
{
int N,query;
cin>>N;
DoublyLinkedList dll=DoublyLinkedList();
for(int ctr=1;ctr<=N;ctr++)
{
cin>>query;
if(query==1)
{
cout<<dll.isEmpty()<<endl;
}
else if(query==2)
{
cout<<dll.getsize()<<endl;
}
else if(query==3)
{
int pos,val;
cin>>pos>>val;
dll.insertAtNthPosition(pos, val);
}
else if(query==4)
{
int pos;
cin>>pos;
dll.deleteNthNode(pos);
}
else if(query==5)
{
int val;
cin>>val;
cout<<dll.search(val)<<endl;
}
else if(query==6)
{
dll.display();
}
else if(query==7)
{
dll.printReverse();
}
}
return 0;
}
The query type can be one of the following types
1-isEmpty
2-getSize
3-insertAtNthPosition
4-deleteNthNode
5-search
6-diplay
7-printReverse

Example Input/Output 1:
Input
50
1
2
3 1 100
1
2
3 1 200
3 1 300
6
7
3 4 400
3 5 500
3 6 600
3 3 700
6
7
1
2
5 100
5 200
5 300
5 400
5 500
5 600
5 700
5 800
5 900
6
7
41
6
7
46
6
7
43
6
7
48
6
7
41
42
43
41
41
42
6
7
1
2
Output
1
0
0
0
1
300 200 100
100 200 300
300 200 700 100 400 500 600
600 500 400 100 700 200 300
0
7
1
1
1
1
1
1
0
0
300 200 700 100 400 500 600
600 500 400 100 700 200 300
200 700 100 400 500 600
600 500 400 100 700 200
200 700 100 400 500
500 400 100 700 200
200 700 400 500
500 400 700 200
invalid position
200 700 400 500
500 400 700 200
invalid position
list is empty
list is empty
list is empty
1
0
EX.NO:5A IMPLEMENTATION OF BUBBLE SORT

AIM:
To write a C++ program to implement bubble sort
ALGORITHM
1. Start with an unsorted array of elements.
2. Repeat steps 3-6 until the array is sorted.
3. Compare each pair of adjacent elements in the array.
4. If the elements are in the wrong order, swap them.
5. Move to the next pair of adjacent elements and repeat steps 3-4.
6. If no swaps were made in the previous pass, the array is already sorted, and the
algorithm can terminate.

RESULT
Thus the C++ Program for bubble sort is compiled and verified successfully.
Program
#include <iostream>
using namespace std;
void BubbleSort(int arr[], int n)
{
for (int i = 0; i < n - 1; i++)
{
bool swapped = false;
for (int j = 0; j < n - i - 1; j++)
{
if (arr[j] > arr[j + 1])
{
swap(arr[j], arr[j + 1]);
swapped = true;
}
for (int k = 0; k < n; k++)
{
cout << arr[k] << " ";
}
cout<<endl;
}
if (!swapped)
{
break;
}
}
}
int main() Example Input/Output:
{ Input:
int n; 5
cin >> n; 50 20 10 30 40
int arr[n]; Output:
for (int i = 0; i < n; i++) 20 50 10 30 40
{ 20 10 50 30 40
cin >> arr[i]; 20 10 30 50 40
} 20 10 30 40 50
BubbleSort(arr, n); 10 20 30 40 50
return 0; 10 20 30 40 50
} 10 20 30 40 50
10 20 30 40 50
10 20 30 40 50
EX.NO:5B IMPLEMENTATION OF INSERTION SORT
AIM:
To write a C++ program to implement insertion sort
ALGORITHM
Step 1 − If the element is the first one, it is already sorted.

Step 2 – Move to next element

Step 3 − Compare the current element with all elements in the sorted array

Step 4 – If the element in the sorted array is smaller than the current element, iterate to the
next element. Otherwise, shift all the greater element in the array by one position towards the
right

Step 5 − Insert the value at the correct position

Step 6 − Repeat until the complete list is sorted

RESULT
Thus the C++ Program for insertion sort is compiled and verified successfully.
Program
#include <iostream>
using namespace std;
void InsertionSort(int arr[], int n)
{
int i, j, key;
for(i = 0; i < n; i++)
{
key = arr[i];
j = i - 1;
while(j >= 0 && arr[j] > key)
{
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = key;
for(int k = 0; k < n; k++)
{
cout << arr[k] << " ";
}
cout << endl;
}
}
int main()
{
int n;
cin >> n;
int arr[n];
for(int i = 0; i < n; i++)
{
cin >> arr[i];
}
InsertionSort(arr, n);
return 0;
}

Example Input/Output:
Input:
5
50 20 10 30 40
Output:
50 20 10 30 40
20 50 10 30 40
10 20 50 30 40
10 20 30 50 40
10 20 30 40 50
EX.NO:5C IMPLEMENTATION OF SELECTION SORT
AIM:
To write a C++ program to implement selection sort.
Algorithm :
1. Start with an unsorted array of elements.
2. Set the first element as the minimum value.
3. Traverse the array starting from the second element:
a. Compare the current element with the minimum value.
b. If the current element is smaller than the minimum value, update the minimum value.
4. Swap the minimum value with the first element of the unsorted portion.
5. Move the boundary of the sorted portion by incrementing it by 1.
6. Repeat steps 2 to 5 until the entire array is sorted.

RESULT
Thus the C++ Program for selection sort is compiled and verified successfully.
Program
#include <iostream>
using namespace std;
void SelectionSort(int arr[], int n)
{
for (int i = 0; i < n - 1; i++)
{
int min = i;
for (int j = i + 1; j < n; j++)
{
if (arr[j] < arr[min])
{
min = j;
}
}
swap(arr[i], arr[min]);
for (int k = 0; k < n; k++)
{
cout << arr[k] << " ";
}
cout << endl;
}
}
int main()
{
int n;
cin >> n;
int arr[n];
for (int i = 0; i < n; i++)
{
cin >> arr[i];
}
SelectionSort(arr, n);
return 0;
}

Example Input/Output:
Input:
5
50 20 10 30 40
Output:
10 20 50 30 40
10 20 50 30 40
10 20 30 50 40
10 20 30 40 50
EX.NO:6 IMPLEMENTATION OF BINARY SEARCH TREE
AIM:
To write a C++ program to implement binary search tree.

1. Start the program.


2. Create a structure for a node in the BST. Each node should have a value, a left child pointer, and a
right child pointer.
3. Initialize an empty root node as null.
4. To insert a value into the BST:
5. If the root is null, create a new node with the given value and make it the root.
6. If the value is less than the current node's value, go to the left subtree recursively.
7. If the value is greater than the current node's value, go to the right subtree recursively.
8. Repeat the above steps until you reach an empty space in the tree, then insert the new node there.
9. To search for a value in the BST:
10. Start at the root node.
11. If the value is equal to the current node's value, return the node.
12. If the value is less than the current node's value, go to the left subtree recursively.
13. If the value is greater than the current node's value, go to the right subtree recursively.
14. If you reach a null node, the value is not present in the BST.
15. To delete a node from the BST:
a. Find the node to be deleted.
b. If the node has no children, simply remove it from the tree.
c. If the node has one child, replace the node with its child.
d. If the node has two children, find the node's in-order successor (the smallest value in the
right subtree) and replace the node's value with the successor's value. Then, recursively
delete the successor node.
16. To traverse the BST:
a. In-order traversal: Traverse the left subtree, visit the current node, then traverse the right
subtree.
b. Pre-order traversal: Visit the current node, traverse the left subtree, then traverse the right
subtree.
c. Post-order traversal: Traverse the left subtree, traverse the right subtree, then visit the
current node.
17. Stop the program.

Result:
Thus the C++ program to implement binary search tree was executed and verified
successfully.
Program
#include <iostream>
struct Node
{
int data;
Node* left;
Node* right;
};
Node* root;
Node* createNode(int data)
{
Node* newNode = new Node();
newNode->data = data;
newNode->left = nullptr;
newNode->right = nullptr;
return newNode;
}
void insertNode(Node* node, int rootData, int data, char pos)
{
if (node != nullptr)
{
if (node->data == rootData)
{
if (pos == 'L' && node->left == nullptr)
{
node->left = createNode(data);
}
else if (pos == 'R' && node->right == nullptr)
{
node->right = createNode(data);
}
else
{
std::cout << "Left & Right Nodes are already present" << std::endl;
}
return;
}
insertNode(node->left, rootData, data, pos);
insertNode(node->right, rootData, data, pos);
}
}
Node* search(Node* parent, Node* node, int nodeToSearch, char childPos)
{
if (node != nullptr)
{
if (node->data == nodeToSearch)
{
Node* temp = node;
if (node == root && childPos == 'P')
{
if (node->left != nullptr && node->right != nullptr)
{
std::cout << "Cannot merge two nodes" << std::endl;
}
else if (node->left == nullptr && node->right == nullptr)
{
root = nullptr;
}
else if (node->left != nullptr)
{
root = node->left;
}
else
{
root = node->right;
}
return node;
}
if (node->left == nullptr && node->right == nullptr)
{
if (childPos == 'L')
{
parent->left = nullptr;
}
else if (childPos == 'R')
{
parent->right = nullptr;
}
}
else if (node->left != nullptr && node->right != nullptr)
{
std::cout << "Cannot merge two nodes" << std::endl;
}
else if (node->left != nullptr && node->right == nullptr)
{
if (childPos == 'L')
{
parent->left = node->left;
}
else if (childPos == 'R')
{
parent->right = node->left;
}
}
else if (node->left == nullptr && node->right != nullptr)
{
if (childPos == 'L')
{
parent->left = node->right;
}
else if (childPos == 'R')
{
parent->right = node->right;
}
}
return node;
}
Node* ptr = search(node, node->left, nodeToSearch, 'L');
if (ptr != nullptr)
{
return ptr;
}
return search(node, node->right, nodeToSearch, 'R');
}
return nullptr;
}
void deleteNode(Node* rootNode, int X)
{
Node* newNode = search(nullptr, rootNode, X, 'P');
if (newNode == nullptr)
{
std::cout << "Not found" << std::endl;
return;
}
if (newNode->left == nullptr || newNode->right == nullptr)
{
delete newNode;
}
}
void printPreorder(Node* node)
{
if (node != nullptr)
{
std::cout << node->data << " ";
printPreorder(node->left);
printPreorder(node->right);
}
}
int main()
{
int N, rootData, data;
char pos;
std::cin >> N;
std::cin >> rootData;
root = createNode(rootData);
for (int ctr = 2; ctr <= N; ctr++)
{
std::cin >> rootData >> data >> pos;
insertNode(root, rootData, data, pos);
}
int X, dataToDelete;
std::cin >> X;
for (int ctr = 1; ctr <= X; ctr++)
{
std::cin >> dataToDelete;
deleteNode(root, dataToDelete);
if (root == nullptr)
{
std::cout << "Tree is empty" << std::endl;
}
else
{
printPreorder(root);
std::cout << std::endl;
}
}
return 0;
}
OUTPUT:
Input:
12
1 10
15
1 20
11
18
1 15
1 25
3
2 20
3
2 10
3

Output:
10 5 1 8 20 15 25
10 5 1 8 25 15
15 5 1 8 25
EX.NO:7A IMPLEMENTATION OF INFIX TO POSTFIX CONVERSION

AIM:
To write a C++ program to convert infix expression to postfix expression.
1. Start the program.
2. Initialize an empty stack for operators and an empty list for the postfix expression.
3. Scan the infix expression from left to right.
4. If the current token is an operand (number or variable), add it to the postfix expression.
5. If the current token is a left parenthesis '(', push it onto the stack.
6. If the current token is an operator (+, -, *, /, etc.), do the following:
a. While there is an operator at the top of the stack with higher precedence than the
current operator or both operators have the same precedence and the current operator
is left associative, pop operators from the stack and add them to the postfix
expression.
b. Push the current operator onto the stack.
7. If the current token is a right parenthesis ')', do the following:
a. Pop operators from the stack and add them to the postfix expression until a left
parenthesis '(' is encountered.
b. Pop and discard the left parenthesis.
8. Repeat steps 3-6 until all tokens have been scanned.
9. Pop any remaining operators from the stack and add them to the postfix expression.
10. The postfix expression in the list is the result.
11. Stop the Program.

Result:
Thus the C++ program to convert infix expression to postfix expression was executed
and verified successfully.
Program
#include <iostream>
#include <stack>
#include <string>
using namespace std;
// Function to check if a character is an operator
bool isOperator(char c) {
if (c == '+' || c == '-' || c == '*' || c == '/' || c == '%' || c == '^')
return true;
return false;
}
// Function to get the precedence of an operator
int getPrecedence(char c) {
if (c == '+' || c == '-')
return 1;
else if (c == '*' || c == '/' || c == '%')
return 2;
else if (c == '^')
return 3;
return -1; // invalid operator
}
// Function to convert infix expression to postfix expression
string infixToPostfix(string expression) {
stack<char> stk;
string postfix = "";
for (int i = 0; i < expression.length(); i++) {
if (expression[i] == ' ' || expression[i] == '\t') // ignore white spaces and tabs
continue;
else if (isOperator(expression[i])) { // if operator
if (expression[i] == '^') { // right associative operator
while (!stk.empty() && getPrecedence(stk.top()) > getPrecedence(expression[i]))
{
postfix += stk.top();
stk.pop();
}
} else { // left associative operator
while (!stk.empty() && getPrecedence(stk.top()) >=
getPrecedence(expression[i])) {
postfix += stk.top();
stk.pop();
}
}
stk.push(expression[i]);
} else if (expression[i] == '(') { // if opening parenthesis
stk.push(expression[i]);
} else if (expression[i] == ')') { // if closing parenthesis
while (!stk.empty() && stk.top() != '(') {
postfix += stk.top();
stk.pop();
}
stk.pop(); // remove opening parenthesis
} else { // if operand
while (i < expression.length() && !isOperator(expression[i]) && expression[i] != '('
&& expression[i] != ')') {
postfix += expression[i];
i++;
}
i--; // to compensate for the extra increment in the for loop
}
}
while (!stk.empty()) { // add remaining operators
postfix += stk.top();
stk.pop();
}
return postfix;
}
int main(int argc, char** argv) {
string expression;
getline(cin, expression);
string postfix = infixToPostfix(expression);
cout<< postfix << endl;
return 0;
}

Example Input/Output 1:
Input:
A*B*(C+D)%R+F-G/H*J
Output:
AB*CD+*R%F+GH/J*-

Example Input/Output 2:
Input:
a+b*(c^d-e)^(f+g*h)-i
Output:
abcd^e-fgh*+^*+i-
EX.NO:7B IMPLEMENTATION OF POLYNOMIAL OPERATIONS USING LINKED LIST

AIM:
To write a C++ program to add two polynomial expressions.

ALGORITHM
1. Start the Program.
2. Initialize an empty result polynomial.
3. Identify the polynomial with the highest degree among the two polynomials.
4. Iterate through each term in the polynomial with the highest degree:
5. Add the coefficient of the term from the first polynomial to the coefficient of the
corresponding term in the second polynomial.
6. Create a new term with the updated coefficient and the same degree.
7. Add the new term to the result polynomial.
8. Iterate through the remaining terms in the polynomial with the lower degree:
9. Add each term to the result polynomial without any changes.
10. Return the result polynomial.
11. Stop the program.

Result:
Thus the C++ program to add two polynomial expression was executed and verified
successfully.
Program
#include <iostream>
#include <stdio>
#include <string>
using namespace std;
class Node
{
public:
int coefficient, exponent;
Node *next;
Node(int c, int e)
{
coefficient = c;
exponent = e;
next = NULL;
}
};
class PolynomialExpression
{
public:
Node *head, *tail;
PolynomialExpression()
{
head = NULL;
tail = NULL;
}
void appendNode(int, int);
void printPolynomial();
friend PolynomialExpression add(PolynomialExpression, PolynomialExpression);
};
void PolynomialExpression::appendNode(int c, int e)
{
Node *newNode = new Node(c, e);
if(head == NULL)
{
head = newNode;
tail = newNode;
}
else
{
Node *prev = NULL, *curr = head;
while(curr != NULL && curr->exponent>e)
{
prev = curr;
curr = curr->next;
}
if(curr != NULL && curr->exponent == e)
{
curr->coefficient += c;
if(curr->coefficient == 0)
{
if(curr == head)
{
head = curr->next;
}
else if(curr == tail)
{
tail = prev;
prev->next = NULL;
}
else
{
prev->next = curr->next;
}
delete curr;
}
else
{
delete newNode;
}
}
else
{
if(curr == head)
{
head = newNode;
}
else
{
prev->next = newNode;
}
newNode->next = curr;
if(curr == NULL)
{
tail = newNode;
}
}
}
}
PolynomialExpression add(PolynomialExpression exp1, PolynomialExpression
exp2)
{
PolynomialExpression result;
Node *temp1 = exp1.head, *temp2 = exp2.head;
while(temp1 != NULL && temp2 != NULL)
{
if(temp1->exponent == temp2->exponent)
{
int sum = temp1->coefficient + temp2->coefficient;
if(sum != 0)
{
result.appendNode(sum, temp1->exponent);
}
temp1 = temp1->next;
temp2 = temp2->next;
}
else if(temp1->exponent>temp2->exponent)
{
result.appendNode(temp1->coefficient, temp1->exponent);
temp1 = temp1->next;
}
else
{
result.appendNode(temp2->coefficient, temp2->exponent);
temp2 = temp2->next;
}
}
while(temp1 != NULL)
{
result.appendNode(temp1->coefficient, temp1->exponent);
temp1 = temp1->next;
}
while(temp2 != NULL)
{
result.appendNode(temp2->coefficient, temp2->exponent);
temp2 = temp2->next;
}
return result;
}
PolynomialExpression getPolynomialExpression(string polynomialStr)
{
PolynomialExpression exp;
int len = polynomialStr.length();
int i = 0;
while(i<len)
{
int sign = 1;
if(polynomialStr[i] == ‘-‘)
{
sign = -1;
i++;
}
else if(polynomialStr[i] == ‘+’)
{
sign = 1;
i++;
}
int coefficient = 0, exponent = 0;
while(i < len && polynomialStr[i]>=’0’ && polynomialStr[i] <= ‘9’)
{
coefficient = coefficient * 10 + (polynomialStr[i] - ’0’);
i++;
}
if(i < len && polynomialStr[i] == ‘x’)
{
i++;
if(i < len && polynomialStr[i] == ‘^’)
{
i++;
while(i < len && polynomialStr[i] >= ‘0’ && polynomialStr[i] <= ‘9’)
{
exponent = exponent * 10 + (polynomialStr[i] – ‘0’);
i++;
}
}
else
{
exponent = 1;
}
}
else
{
exponent = 0;
}
coefficient *= sign;
exp.appendNode(coefficient, exponent);
}
return exp;
}
void PolynomialExpression::printPolynomial()
{
Node *temp = head;
while(temp != NULL)
{
cout <<showpos <<temp->coefficient;
cout <<noshowpos <<”x^”<<temp->exponent;
temp = temp->next;
}
}
int main()
{
string polynomialStr1, polynomialStr2;
cin >>polynomialStr1>>polynomialStr2;
int len1 = polynomialStr1.length();
int len2 = polynomialStr2.length();
if(len1<5 || len1>1000)
{
cout <<”Length of expression 1 not in boundary” ;
}
if(len2 <5 || len2>1000)
{
cout <<”Length of expression 2 not in boundary”;
}
PolynomialExpression exp1 = getPolynomialExpression(polynomialStr1);
PolynomialExpression exp2 = getPolynomialExpression(polynomialStr2);
PolynomialExpression result = add(exp1, exp2);
printf(“Polynomial Addition: “ );
result.printPolynomial();
}
OUTPUT

Input:
+2x^4+3x^2-1x^1
-2x^5+3x^4+2x^2-2x^1

Ouptut:
Polynomial Addition: -2x^5+5x^4+5x^2-3x^1

Input:
-10x^10-2x^7+2x^4-9x^2
10x^10+5x^8-7x^7+4x^5

Ouptut:
Polynomial Addition: +5x^8-9x^7+4x^5+2x^4-9x^2
EX.NO:8A IMPLEMENTATION OF MAXHEAP
Aim
To write a C++ program to implement a Max heap
Algorithm
Step 1 − Create a new node at the end of heap.
Step 2 − Assign new value to the node.
Step 3 − Compare the value of this child node with its parent.
Step 4 − If value of parent is less than child, then swap them.
Step 5 − Repeat step 3 & 4 until Heap property holds.

Result
Thus the C++ program for implementation of max heap is executed successfully.
Program
#include <iostream>
#include<vector>
#define MAXSIZE 100
using namespace std;
void insert(vector<int> &maxHeap,int val)
{
if(maxHeap.size()-1++MAXSIZE)
{
cout<<”Heap is full”<<endl; return;
}
maxHeap.push_back(val);
int child = maxHeap.size()-1; int parent = child/2; while(child>1)
{
if(maxHeap[child]>maxHeap[parent])
{
int x =maxHeap[child]; maxHeap[child]=maxHeap[parent]; maxHeap[parent]=x;
child=parent; parent=child/2;
}
else
{
break;
}
}
}
void extractMax(vector <int >&maxHeap)
{
int x=maxHeap[1]; maxHeap[1]=maxHeap[maxHeap.Size()-1]; maxHeap[maxHeap.size()-
1]=x; maxHeap.pop_back();
int parent=1; int child;
while(parent<maxHeap.size()-1)
{
if(parent*2==maxHeap.size()-1)
{
child=2*parent;
}
else
{
child=maxHeap[2*parent]>maxHeap[2*parent+1]?2*parent:2*parent+1;
}
if(child>maxHeap.size()-1
{
break;
}
if (maxHeap[parent]<maxHeap[child])
{
int t=maxxHeap[parent]; maxHeap[parent]=maxHeap[child]; maxHeap[child]=t;
parent=child;
}
else
{
break;
}
}
return x;
}
void display(vector<int> &maxHeap_
{
if(maxHeap.size()<=1)
{
cout<<:Heap is empty”<<endl; return;
}
for(int index=1;index<=maxHeap.size()-1;index++)
{
cout<<maxHeap[index]<<””;
}
cout<<endl;
}
int main()
{
int N,queryType, val; cin>>N; maxHeap.push_back(-1); for(int ctr=1;ctr<=N;ctr++)
{
cin>>queryType; switch(queryType)
{

case 1:
cin>>val; insert(maxHeap, val); break;
case 2: if(maxHeap.size()>1)
{
cout<<extractMax(maxHeap)<<endl;
}
else (
cout<<”Heap is empty”<< endl;
}
break; case 3:
display(maxHeap); break;
}
}
return 0;
}
Input:
21
1 10
1 20
1 30
1 15
15
11
3
2
3
2
3
2
3
2
3
2
3
2
3
2
3
2
3
Output:
30 15 20 10 5 1
30
20 15 1 10 5
20
15 10 1 5
15
10 5 1
10
51
5
1
1
Heap is empty
Heap is empty
Heap is empty
EX.NO:8B IMPLEMENTATION OF MINHEAP

Aim
To write a C++ program to implement a Min heap
Algorithm
Step 1 − Create a new node at the end of heap.
Step 2 − Assign new value to the node.
Step 3 − Compare the value of this child node with its parent.
Step 4 − If value of parent is greater than child, then swap them.
Step 5 − Repeat step 3 & 4 until Heap property holds.

Result
Thus the C++ program for implementation of max heap is executed successfully.
Program
#include<iostream>
#include<vector>
#define MAXSIZE 100
using namespace std;
void insert(vector <int> &minHeap,int val)
{
if(minHeap.size()-1==MAXSIZE)
{
cout<<”Heap is full”<<endl; return;
}
minHeap.push_back(val);
int child=minHeapo.size()-1; int parent=child/2; while(child>1)
{
if(minHeap[child]<minHeap[parent])
{
int x=minHeap[child]; minHeap[child]=minHeap[parent]; minHeap[parent]=x;
child=parent; parent=child/2;
}
else
{
break;
}
}
}
int extractMin(vector<int> &minHeap)
{
int x=minHeap[1]; minHeap[1]=minHeap[minHeap.size()-1]; minHeap[minHeap.size()-
1]=x; minHeap.pop_back();
int parent=1; int child;
while(parent<minHeap.size()-1)
{
if(parent*2==minHeap.size()-1) child=2*parent;
else child=minHeap[2*parent]<minHeap[2*parent+1]?2*parent:2*parent+1; break;
if(minHeap[parent]>minHeap[child])
{
int t=minHeap[parent]; minHeap[parent]=minHeap[child]; minHeap[child]=t;
parent=child;
}
else
{
break;
}
}
return x;
}
void display(vector <int> &minHeap)
{
if(minHeap.size()<=1)
{
cout<<”Heap is empty”<<endl; return;
}
for (int index=1;index<=minHeap.size()-1;index++)
{
cout<<minHeap[index]<<” “;
}
cout<<endl;
}
int main()
{
int N, queryType, val; cin>> N;
vector<int> minHeap; minHeap.push_back(-1); for(int ctr=1;ctr<=N; ctr++)
{
cin>>queryType;
switch(queryType)
{
case 1; cin>>val;
insert(minHeap, val); break;
case 2: if(minHeap.size()>1)
{
cout<< extractMin(minHeap)<<endl;
}
else
{
cout<<”Heap is empty”<<endl;
}
break; case 3:
display(minHeap); break;
}
}
return 0;
}
Input:
21
1 10
1 20
1 30
1 15
15
11
3
2
3
2
3
2
3
2
3
2
3
2
3
2
3
Output:
1 10 5 20 15 30
1
5 10 30 20 15
5
10 15 30 20
10
15
20 30
20
30
30
Heap is empty
Heap is empty
Heap is empty
Ex.No.: 9.A NUMBER OF GROUPS OF FRUITS
Aim
To write a C++ program to implement the number of fruits in groups.
Algorithm
Step 1: Start
Step 2: Give the number of rows and columns
Step 3: If the fruit is present in the cell, it should be indicated by 1 or else it should be indicated by 0
Step 4: The fruits can be of different types, if the fruits belong to the same type, it should be arranged in
adjacent cells
Step 5: Print the number of groups in matrix of R*C
Step 6: Stop
Result
Thus, the C++ program for number of groups of fruits is executed successfully
Program
#include <iostream>
#include <vector>
using namespace std;
vector<vector<int>> grid;
vector<vector<bool>> visited;
int groupCount = 0;
int R, C;
void dfs(int row, int col)
{
if (row >= 0 && row < R && col >= 0 && col < C && !visited[row][col])
{
visited[row][col] = true;
if (grid[row][col] == 1) {
for (int dr = -1; dr <= 1; dr++) {
for (int dc = -1; dc <= 1; dc++) {
int new_row = row + dr;
int new_col = col + dc;
dfs(new_row, new_col);
}
}
}
}
}
int main()
{
cin >> R >> C;
grid.resize(R, vector<int>(C));
visited.resize(R, vector<bool>(C, false));
for (int row = 0; row < R; row++) {
for (int col = 0; col < C; col++) {
cin >> grid[row][col];
}
}
for (int row = 0; row < R; row++) {
for (int col = 0; col < C; col++) {
if (!visited[row][col] && grid[row][col] == 1) {
groupCount++;
dfs(row, col);
}
}
}
cout << groupCount << endl;
return 0;
}
Example input/output 1:
input:
35
10001
01011
10001
Output:2
Explanation:
The first group is indicated by the letter F,
F0001
0F011
F0001
The second group is indicated by the letter S,
1000S
010SS
1000S
EX.NO:9B BINARY TREE ( INSERT & DELETE)
AIM:
To write a C++ program to implement binary search tree.

Program
18. Start the program.
19. Create a structure for a node in the BST. Each node should have a value, a left child pointer,
and a right child pointer.
20. Initialize an empty root node as null.
21. To insert a value into the BST:
22. If the root is null, create a new node with the given value and make it the root.
23. If the value is less than the current node's value, go to the left subtree recursively.
24. If the value is greater than the current node's value, go to the right subtree recursively.
25. Repeat the above steps until you reach an empty space in the tree, then insert the new node
there.
26. To search for a value in the BST:
27. Start at the root node.
28. If the value is equal to the current node's value, return the node.
29. If the value is less than the current node's value, go to the left subtree recursively.
30. If the value is greater than the current node's value, go to the right subtree recursively.
31. If you reach a null node, the value is not present in the BST.
32. To delete a node from the BST:
a. Find the node to be deleted.
b. If the node has no children, simply remove it from the tree.
c. If the node has one child, replace the node with its child.
d. If the node has two children, find the node's in-order successor (the smallest value in
the right subtree) and replace the node's value with the successor's value. Then,
recursively delete the successor node.
33. To traverse the BST:
a. In-order traversal: Traverse the left subtree, visit the current node, then traverse
the right subtree.
b. Pre-order traversal: Visit the current node, traverse the left subtree, then traverse
the right subtree.
c. Post-order traversal: Traverse the left subtree, traverse the right subtree, then visit
the current node.
34. Stop the program.

Result:
Thus the C++ program to implement binary search tree was executed and verified
successfully.
Program
#include<iostream>
using namespace std;
template<class T>
class Node
{
public:
T data;
Node<T> *left,*right;
};
template<class T>
class bintree
{
Node<T> *root;
public:
bool search(T ele)
{
bool flag=false;
Search1(root,ele,flag);
return flag;
}
void Search1(Node<T> *rt,T ele,bool &exist)
{
if(rt!=NULL)
{
if(rt->data==ele)
{
exist=true;
return;
}
Search1(rt->left,ele,exist);
Search1(rt->right,ele,exist);
}
}
void insert(T ele,T parent)
{
if(root==NULL)
{
Node<T> *temp=new Node<T>;
temp->data=ele;
temp->left=temp->right=NULL;
root=temp;
return;
}
else
{
bool h=false;
Search(root,parent,h);
if(h)
{
ins(root,ele,parent);
}
else
cout<<"\nParent not found";
}
}
void ins(Node<T> *rt,T ele,T parent)
{
if(rt!=NULL)
{
if(parent!=(rt)->data)
{
ins(&(rt)->left,ele,parent);
ins(&(rt)->right,ele,parent);
}
else
{
if((rt)->left==NULL||(rt)->right==NULL)
{
Node<T> *temp;
temp->data=ele;
temp->left=temp->right=NULL;
if((rt)->left==NULL)
{
(rt)->left=temp;
}
else
{
if((rt)->right==NULL)
(rt)->right=temp;
}
}
else
cout<<"\n ****Insertion not possible*****";
return;
}
}
}
void deletion(T ele)
{
bool h;
Search(root,ele,h);
if(h)
{
del(root,ele);
}
else
cout<<"\n ****Element not found*****";
}
void del(Node<T> *rt,T ele)
{
if((rt)!=NULL)
{
if((rt)->data!=ele)
{
del(&(rt)->left,ele);
del(&(rt)->right,ele);
}
else
{
if((rt)->left!=NULL&&(rt)->right!=NULL)
{
Node<T> *temp=(rt)->right,*pt=NULL;
while(temp->left)
{
pt=temp;
temp=temp->left;
}
if(pt!=NULL)
{
pt->left=temp->right;
temp->left=(rt)->left;
temp->right=(rt)->right;
(rt)=temp;
}
else
{
(rt)->right->left=(rt)->left;
(rt)=(rt)->right;
}
}
else
if((rt)->left==NULL&&(rt)->right!=NULL)
(rt)=(rt)->right;
else
if((rt)->left!=NULL&&(rt)->right==NULL)
(rt)=(rt)->left;
else (rt)=NULL;
}
}
}
void display()
{
cout<<"\n The binary tree is:";
cout<<"\nInorder :";
inorder(root);
}
void inorder(Node<T> *rt)
{
if(rt!=NULL)
{
inorder(rt->left);
cout<<" "<<rt->data;
inorder(rt->right);
}
}
};
int main()
{
bintree<int> b;
int ch,ele,pt;
while(1)
{
cout<<"\n 1.Insertion 2.Deletion 3.Display 4.Search 5.Exit";
cout<<"\n Enter ur choice:";
cin>>ch;
switch(ch)
{
case 1:
cout<<"\n Enter element value:";
cin>>ele;
cout<<"\n Enter Parent element:";
cin>>pt;
b.insert(ele,pt);
break;
case 2:
cout<<"\n Enter element value to delete:";
cin>>ele;
b.deletion(ele);
break;
case 3:
cout<<endl;
b.display();
break;
case 4:
cout<<"\n Enter element value to search:";
cin>>ele;
if(b.search(ele))
cout<<"\n Element found";
else
cout<<"\n Element not found";
break;
case 5:
return 0;
default:
cout<<" \n Invalid choice";
}
b.display();
cout<<endl;
}
return 0;
}

Example Input/Output :
Input:
93
31L
32R
14L
15R
26L
27R
6 10 R
5 20 L
4652
15

Output:
3 1 4 5 20 2 10 7
3 1 4 20 2 10 7
Cannot merge two nodes
3 1 4 20 2 10 7
Not found
3 1 4 20 2 10 7
Ex.No.: 10 STRING PATTERN – OCCURRENCE COUNT
Aim :
To write a C++ program to find the no of occurrences of a particular pattern in a string.
Algorithm:
1. Initialize a variable count to 0 to keep track of the number of occurrences.
2. Initialize a variable n to the length of string s.
3. Initialize a variable m to the length of pattern P.
4. Iterate i from 0 to n - m (inclusive):
• Check if s[i:i+m] (substring of length m starting from index i) is equal to pattern P.
• If they are equal, increment count by 1.
5. Print the value of count as the output.
Result :
Thus the C++ Program for string – pattern occurrence count is compiled and verified successfully.
Program
#include <bits/stdc++.h>
using namespace std;
void computeLPSArray(string pattern , int lps[])
{
int len = 0;
int i = 1;
int m = pattern.length();
lps[0] = 0;
while (i < m) {
if (pattern[i] == pattern[len]) {
len++;
lps[i] = len;
i++;
} else {
if (len != 0) {
len = lps[len - 1];
} else {
lps[i] = 0;
i++;
}
}
}
}
int main()
{
string str, pat;
cin >> str >> pat;
int len = str.length();
int patLen = pat.length();
int lps[patLen];
computeLPSArray (pat, lps);
int lpsindex = 0, match = 0;
for(int index = 0; index < len;)
{
if(pat[lpsindex] == str[index])
{
lpsindex++;
index++;
if(lpsindex == patLen)
{
match++;
lpsindex = 0;
}
}
else
{
if(lpsindex != 0)
{
lpsindex = lps[lpsindex-1];
}
else
{
index++;
}
}
}
cout << "Count="<< match;
return 0;
} // end of main function

Example input/Output 1:
input :
AaabcbababcaabcdAbcd
abc
output:
Count=3
Explanation :
The pattern occurs 3 times in the given string
AaabcbababcaabcdAbcd
Hence the output is Count=3

Example Input/output 3:
input:
Aa#12aBabc#123abc#abc#123
abc#123

output:
Count=2

You might also like