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

C++ DSA CODE

The document contains various C++ implementations of data structures and algorithms, including stacks using arrays and linked lists, queues using arrays and linked lists, hash tables, binary trees, the Tower of Hanoi, balanced brackets checking, bucket sort, and heap sort. Each section provides code examples and explanations for the respective data structure or algorithm. The implementations demonstrate basic operations such as insertion, deletion, and traversal.
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)
5 views

C++ DSA CODE

The document contains various C++ implementations of data structures and algorithms, including stacks using arrays and linked lists, queues using arrays and linked lists, hash tables, binary trees, the Tower of Hanoi, balanced brackets checking, bucket sort, and heap sort. Each section provides code examples and explanations for the respective data structure or algorithm. The implementations demonstrate basic operations such as insertion, deletion, and traversal.
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/ 22

STACK USING ARRAYS

#include<iostream>
using namespace std;
class stack
{
private:
int stk[10];
int size;
int top;
public:
void initialize()
{
size=5;
top=-1;
}
void push();
void pop();
void display();
};
void stack::push()
{
int value;
cout<<"enter the element to be pushed"<<endl;
cin>>value;
if(top==size)
{
cout<<"stack is full"<<endl;
}
else
{
top=top+1;
stk[top]=value;
cout<<"the element "<<value<<" is inserted at the top of stack"<<endl;
}
}
void stack::pop()
{
if(top==-1)
{
cout<<"stack is empty"<<endl;
}
else
{
int value;
value=stk[top];
top=top-1;
cout<<"the value popped is "<<value<<endl;
}
}
void stack::display()
{
if(top==-1)
{
cout<<"stack is empty"<<endl;
}
else
{
cout<<"the present stack elements are "<<endl;
for(int i=top;i>=0;i--)
{
cout<<stk[i]<<endl;
}
}
}
main()
{
stack s;
s.initialize();
int rpt=1,choice;
while(rpt)
{
cout<<"********************************"<<endl;
cout<<"enter 1 to push()"<<endl;
cout<<"enter 2 to pop()"<<endl;
cout<<"enter 3 to display()"<<endl;
cout<<"********************************"<<endl;
cout<<"enter ur choice"<<endl;
cin>>choice;
switch(choice)
{
case 1:
s.push();
break;
case 2:
s.pop();
break;
case 3:
s.display();
break;
}
cout<<"do u want to repeat? if yes press 1, else press 0"<<endl;
cin>>rpt;
}
}

STACK USING LINKED LIST


// stack implementataion using linked list
#include<iostream>
using namespace std;
struct node
{
int info;
node *next;
};
node *head,*tail;
class stack
{
private:
int size;
int counter;
public:
stack()
{
head=NULL;
tail=NULL;
size=5;
counter=0;
}
void push();
void pop();
void display();
};
void stack::push()
{
int value;
cout<<"enter the value to be pushed"<<endl;
cin>>value;
if(size==counter)
{
cout<<"stack is full"<<endl;
}
else
{
if(head==NULL)
{
node *temp=new(node);
temp->info=value;
temp->next=NULL;
head=temp;
tail=temp;
counter=counter+1;
}
else
{
node *temp=new(node);
temp->info=value;
head->next=temp;
temp->next=NULL;
head=temp;
counter=counter+1;
}
}
}
void stack::display()
{
if(tail==NULL)
{
cout<<"stack is empty"<<endl;
}
else
{
node *temp;
temp=tail;
cout<<"stack elements are"<<endl;
while(temp!=NULL)
{
cout<<temp->info<<"->";
temp=temp->next;
}
cout<<"NULL"<<endl;
}
}
void stack::pop()
{
if(tail==NULL)
{
cout<<"stack is empty"<<endl;
}
else
{
node *temp1,*temp2;
temp1=tail;
while(temp1->next!=NULL)
{
temp2=temp1;
temp1=temp1->next;
}
cout<<"the popped element is="<<temp1->info<<endl;
temp2->next=NULL;
}
}
main()
{
stack s1;
int rpt=1,choice;
while(rpt)
{
cout<<"***************************************"<<endl;
cout<<"enter 1 to push()"<<endl;
cout<<"enter 2 to display()"<<endl;
cout<<"enter 3 to pop()"<<endl;
cout<<"***************************************"<<endl;
cout<<"enter ur choice"<<endl;
cin>>choice;
switch(choice)
{
case 1:
s1.push();
break;
case 2:
s1.display();
break;
case 3:
s1.pop();
break;
}
cout<<"do u wan to continue? if yes, press 1, else press 0"<<endl;
cin>>rpt;
}

}
//queue using arrays
#include<iostream>
using namespace std;
class queue
{
private:
int q[10];
int size;
int front, rear;
public:
queue()
{
size=4;
front=-1;rear=-1;
}
void insert();
void remove();
void display();
};
void queue::insert()
{
if(rear>=size)
{
cout<<"queue overflows"<<endl;
}
else
{ int value;
cout<<"enter the value to be inserted"<<endl;
cin>>value;
rear=rear+1;
q[rear]=value;
cout<<"the value "<<value<<" is inserted in queue from the rear end"<<endl;
}
}
void queue::remove()
{
if(front==rear)
{
cout<<"queue underflows"<<endl;
}
else
{
front=front+1;
cout<<"the removed value from the queue is="<<q[front]<<endl;
}
}
void queue::display()
{
if(front==rear)
{
cout<<"queue underflows"<<endl;
}
else
{
cout<<"the queue elements are "<<endl;
for(int i=front+1;i<=rear;i++)
{
cout<<q[i]<<" ";
}
cout<<endl;
}
}
main()
{
queue q1;
int choice,rpt=1;
while(rpt)
{
cout<<"**********************************"<<endl;
cout<<"enter 1 to insert"<<endl;
cout<<"enter 2 to delete"<<endl;
cout<<"enter 3 to display"<<endl;
cout<<"**********************************"<<endl;
cout<<"enter ur choice"<<endl;
cin>>choice;
switch(choice)
{
case 1:
q1.insert();
break;
case 2:
q1.remove();
break;
case 3:
q1.display();
break;
}
cout<<"do u want to repeat? if yes press 1, else press 0"<<endl;
cin>>rpt;
}
}

// queue using linked list


#include<iostream>
using namespace std;
struct node
{
int info;
node *next;
};
node *front,*rear;
class queue
{
int counter;
int size;
public:
queue()
{
front=NULL;
rear=NULL;
counter=0;
size=5;
}
void insert();
void remove();
void display();
};
void queue::insert()
{
int value;
cout<<"enter the value to be inserted"<<endl;
cin>>value;
if(counter==size)
{
cout<<"queue is full"<<endl;
}
else
{
if(front==NULL)
{
node *temp=new(node);
temp->info=value;
temp->next=NULL;
front=temp;
rear=temp;
counter=counter+1;
}
else
{
node *temp=new(node);
temp->info=value;
temp->next=NULL;
rear->next=temp;
rear=temp;
counter=counter+1;
}
}
}
void queue::remove()
{
if(front==NULL)
{
cout<<"queue is empty"<<endl;
}
else
{
cout<<"removed item from the queue="<<front->info<<endl;
front=front->next;
}
}
void queue::display()
{
if(front==NULL)
{
cout<<"queue is empty"<<endl;
}
else
{
cout<<"queue elements are"<<endl;
node *temp;
temp=front;
while(temp!=NULL)
{
cout<<temp->info<<" ";
temp=temp->next;
}
cout<<endl;
}
}
main()
{
queue q1;
int choice, rpt=1;
while(rpt)
{
cout<<"*****************************"<<endl;
cout<<"enter 1 to insert"<<endl;
cout<<"enter 2 to remove"<<endl;
cout<<"enter 3 to display"<<endl;
cout<<"*****************************"<<endl;
cout<<"enter ur choice"<<endl;
cin>>choice;
switch(choice)
{
case 1:
q1.insert();
break;
case 2:
q1.remove();
break;
case 3:
q1.display();
break;
}
cout<<"do u want to reapeat? if yes, press 1, else press 0"<<endl;
cin>>rpt;
}
}

//implementataion of hash table


#include<iostream>
#include<cstdlib>
#include<string>
#include<cstdio>
using namespace std;
const int T_S = 10;
class HashTableEntry {
public:
int k;
int v;
HashTableEntry(int k, int v) {
this->k= k;
this->v = v;
}
};
class HashMapTable {
private:
HashTableEntry **t;
public:
HashMapTable() {
t = new HashTableEntry*[T_S];
for (int i = 0; i< T_S; i++) {
t[i] = NULL;
}
for (int i = 0; i< T_S; i++) {
cout<<t[i]<<endl;
}
}
int HashFunc(int k) {
return k % T_S;
}
void Insert(int k, int v) {
int h = HashFunc(k);
while (t[h] != NULL && t[h]->k != k) {
h = HashFunc(h + 1);
}
if (t[h] != NULL)
delete t[h];
t[h] = new HashTableEntry(k, v);
}
int SearchKey(int k) {
int h = HashFunc(k);
while (t[h] != NULL && t[h]->k != k) {
h = HashFunc(h + 1);
}
if (t[h] == NULL)
return -1;
else
return t[h]->v;
}
void Remove(int k) {
int h = HashFunc(k);
while (t[h] != NULL) {
if (t[h]->k == k)
break;
h = HashFunc(h + 1);
}
if (t[h] == NULL) {
cout<<"No Element found at key "<<k<<endl;
return;
} else {
delete t[h];
}
cout<<"Element Deleted"<<endl;
}
void display()
{
int i;
cout<<"index "<<"\t"<<"key "<<"\t"<<"value "<<endl;
for(i=0;i<10;i++)
{
if(t[i]==NULL)
{
cout<<i<<"\t"<<"null"<<"\t"<<"null"<<endl;
}
else
{
cout<<i<<"\t"<<t[i]->k<<"\t"<<t[i]->v<<endl;
}
}
}
/*~HashMapTable() {
for (int i = 0; i < T_S; i++) {
if (t[i] != NULL)
delete t[i];
delete[] t;
}
}*/
};
int main() {
HashMapTable hash;
int k, v;
int c;
while (1) {
cout<<"1.Insert element into the table"<<endl;
cout<<"2.Search element from the key"<<endl;
cout<<"3.Delete element at a key"<<endl;
cout<<"4.display"<<endl;
cout<<"5.Exit"<<endl;
cout<<"Enter your choice: ";
cin>>c;
switch(c) {
case 1:
cout<<"Enter element to be inserted: ";
cin>>v;
cout<<"Enter key at which element to be inserted: ";
cin>>k;
hash.Insert(k, v);
break;
case 2:
cout<<"Enter key of the element to be searched: ";
cin>>k;
if (hash.SearchKey(k) == -1) {
cout<<"No element found at key "<<k<<endl;
continue;
} else {
cout<<"Element at key "<<k<<" : ";
cout<<hash.SearchKey(k)<<endl;
}
break;
case 3:
cout<<"Enter key of the element to be deleted: ";
cin>>k;
hash.Remove(k);
break;
case 4:
hash.display();
break;
case 5:
exit(1);
default:
cout<<"\nEnter correct option\n";
}
}
return 0;
}

// implementation of binary tree


#include<iostream>
using namespace std;
struct node {
int data;
node *left;
node *right;
};
class binary_tree
{
public:
node *createNode(int val)
{
node *temp = new node;
temp->data = val;
temp->left = temp->right = NULL;
return temp;
}
node* insertNode(node* node, int val)
{
if (node == NULL)
return createNode(val);
if (val < node->data)
node->left = insertNode(node->left, val);
else if (val > node->data)
node->right = insertNode(node->right, val);
return node;
}
void inorder(node *root)
{
if (root != NULL)
{
inorder(root->left);
cout<<root->data<<" ";
inorder(root->right);
}
}
void preorder(node *root)
{
if (root != NULL)
{
cout<<root->data<<" ";
preorder(root->left);
preorder(root->right);
}
}
void postorder(node *root)
{
if (root != NULL)
{
postorder(root->left);
postorder(root->right);
cout<<root->data<<" ";
}
}
};
int main() {
binary_tree b;
node *root = NULL;
root = b.insertNode(root, 6);
b.insertNode(root, 24);
b.insertNode(root, 8);
b.insertNode(root, 1);
b.insertNode(root, 5);
b.insertNode(root, 10);
cout<<"In-Order traversal of the Binary Search Tree is: "<<endl;
b.inorder(root);
cout<<endl;
cout<<"Pre-Order traversal of the Binary Search Tree is: "<<endl;
b.preorder(root);
cout<<endl;
cout<<"Post-Order traversal of the Binary Search Tree is: "<<endl;
b.postorder(root);
cout<<endl;

}
TOWER OF HANOI
#include <iostream>
using namespace std;

//tower of HANOI function implementation


void TOH(int n, char Sour, char Aux, char Des)
{
if (n == 1) {
cout << "Move Disk " << n << " from " << Sour << " to " << Des << endl;
return;
}

TOH(n - 1, Sour, Des, Aux);


cout << "Move Disk " << n << " from " << Sour << " to " << Des << endl;
TOH(n - 1, Aux, Sour, Des);
}

//main program
int main()
{
int n;

cout << "Enter no. of disks:";


cin >> n;
//calling the TOH
TOH(n, 'A', 'B', 'C');

return 0;
}

Balanced Brackets
// C++ program to check for balanced brackets.

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

// Function to check if brackets are balanced


bool areBracketsBalanced(string expr)
{
// Declare a stack to hold the previous brackets.
stack<char> temp;
for (int i = 0; i < expr.length(); i++) {
if (temp.empty()) {

// If the stack is empty


// just push the current bracket
temp.push(expr[i]);
}
else if ((temp.top() == '(' && expr[i] == ')')
|| (temp.top() == '{' && expr[i] == '}')
|| (temp.top() == '[' && expr[i] == ']')) {

// If we found any complete pair of bracket


// then pop
temp.pop();
}
else {
temp.push(expr[i]);
}
}
if (temp.empty()) {

// If stack is empty return true


return true;
}
return false;
}

// Driver code
int main()
{
string expr = "{()}[]";

// Function call
if (areBracketsBalanced(expr))
cout << "Balanced";
else
cout << "Not Balanced";
return 0;
}

Bucket Sort – Data Structures and Algorithms


Tutorials
// C++ program to sort an
// array using bucket sort
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;

// Function to sort arr[] of


// size n using bucket sort
void bucketSort(float arr[], int n)
{

// 1) Create n empty buckets


vector<float> b[n];

// 2) Put array elements


// in different buckets
for (int i = 0; i < n; i++) {

// Index in bucket
int bi = n * arr[i];
b[bi].push_back(arr[i]);
}

// 3) Sort individual buckets


for (int i = 0; i < n; i++)
sort(b[i].begin(), b[i].end());

// 4) Concatenate all buckets into arr[]


int index = 0;
for (int i = 0; i < n; i++)
for (int j = 0; j < b[i].size(); j++)
arr[index++] = b[i][j];
}
// Driver program to test above function
int main()
{
float arr[]
= { 0.897, 0.565, 0.656, 0.1234, 0.665, 0.3434 };
int n = sizeof(arr) / sizeof(arr[0]);
bucketSort(arr, n);

cout << "Sorted array is \n";


for (int i = 0; i < n; i++)
cout << arr[i] << " ";
return 0;
}

C++ Program for Heap Sort


// C++ program for implementation of Heap Sort
#include <iostream>
using namespace std;

// To heapify a subtree rooted with node i which is


// an index in arr[]. n is size of heap
void heapify(int arr[], int n, int i)
{
int largest = i; // Initialize largest as root Since we are using 0 based indexing
int l = 2 * i + 1; // left = 2*i + 1
int r = 2 * i + 2; // right = 2*i + 2

// If left child is larger than root


if (l < n && arr[l] > arr[largest])
largest = l;

// If right child is larger than largest so far


if (r < n && arr[r] > arr[largest])
largest = r;

// If largest is not root


if (largest != i) {
swap(arr[i], arr[largest]);

// Recursively heapify the affected sub-tree


heapify(arr, n, largest);
}
}

// main function to do heap sort


void heapSort(int arr[], int n)
{
// Build heap (rearrange array)
for (int i = n / 2 - 1; i >= 0; i--)
heapify(arr, n, i);

// One by one extract an element from heap


for (int i = n - 1; i >= 0; i--) {
// Move current root to end
swap(arr[0], arr[i]);

// call max heapify on the reduced heap


heapify(arr, i, 0);
}
}

/* A utility function to print array of size n */


void printArray(int arr[], int n)
{
for (int i = 0; i < n; ++i)
cout << arr[i] << " ";
cout << "\n";
}

// Driver program
int main()
{
int arr[] = { 60 ,20 ,40 ,70, 30, 10};
int n = sizeof(arr) / sizeof(arr[0]);
//heapify algorithm
// the loop must go reverse you will get after analyzing manually
// (i=n/2 -1) because other nodes/ ele's are leaf nodes
// (i=n/2 -1) for 0 based indexing
// (i=n/2) for 1 based indexing
for(int i=n/2 -1;i>=0;i--){
heapify(arr,n,i);
}

cout << "After heapifying array is \n";


printArray(arr, n);

heapSort(arr, n);

cout << "Sorted array is \n";


printArray(arr, n);

return 0;
}
//code by Prajwal Chougale

You might also like