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

Data Structure is All Here You Need

Data structure all basic codes

Uploaded by

opfarasat1
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)
22 views

Data Structure is All Here You Need

Data structure all basic codes

Uploaded by

opfarasat1
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/ 67

------------------------------------------------------------

Data Structure Theory


By Syed Waleed
------------------------------------------------------------------------------
Linked List
-----------------------------------------------------------------------
#include<iostream>
#include<cstring>
using namespace std;

class Node{
public:
string name;
int value;
Node* next;
Node(string n,int v){
value=v;
name= n;
next= NULL;
}
};
class list{
public:
Node* head;
Node* tail;
list(){
head= NULL;
tail= NULL;
}
void insert(string name,int score){
Node* data = new Node(name,score);
Node* temp;
temp = head;
if(head == NULL){
head = data;
}
else{
while(temp->next!=NULL){
temp=temp->next;
}
temp->next= data;
}
}

void addinfront(string na,int val){


Node* n = new Node(na,val);
n->next = head;
head = n;
cout<<"Inserted at first"<<endl;
}
void addinend(string na,int val){
Node* n = new Node(na,val);
Node* temp= head;
while(temp->next!=NULL){
temp=temp->next;
}
temp->next = n;
n->next= tail;
cout<<"Inserted at end"<<endl;
}
void addinpos(int pos,string na,int val){
Node* n= new Node(na,val);
Node* curr;
Node* pre;
curr = head;
for(int i=0;i<pos;i++){
pre= curr;
curr= curr->next;
}
pre->next=n;
n->next= curr;
}
int search(string name){
Node* temp= head;
while(temp!= NULL){
if(temp->name==name){
cout<<" Student : "<<name <<" Found"<<endl;
cout<<"Student Score :"<< temp->value <<endl;
return 0;
}
temp = temp->next;
}
cout<<"Student name doesnot found...!"<<endl;
}
void display(){
Node* temp;
temp = head;
while(temp != NULL)
{

cout<<"Student Name :"<<temp->name<<endl;


cout<<"Marks :"<<temp->value<<endl;
temp = temp->next;
}
}
void deleteatfront(){
head = head->next;
cout<<"Head deleted"<<endl;
}
void deleteatend(){
Node* temp=head;
Node* pre;
while(temp->next!=NULL){
pre=temp->next;
temp= temp->next;
}
tail= pre;
tail->next=NULL;
delete temp;
cout<<"Deleted at the end"<<endl;
}
};
int main(){
cout<<"-------------Student Portal---------------"<<endl;
list l1;
l1.insert("Alice",90);
l1.insert("Bob",85);
l1.insert("Carol",78);
l1.insert("David",95);

l1.addinfront("Eve",88);
l1.addinend("Frank",89);
l1.addinpos(2,"Grace",95);
l1.search("Carol");
l1.display();
l1.deleteatfront();
// l1.deleteatend();

l1.display();

return 0;
}

Dry Run:

-----------------------------------------------------------------------
Stack
---------------------------------------------------------------------
#include<iostream>
using namespace std;

class stack{
public:
int max=10;
int top;
int n;
int *mystack;
stack(int e){
mystack = new int[e];
n=e;
top=-1;
}
bool push(int item){
if(top>=(max-1)){
cout<<"stack overflow..!!!!"<<endl;
return false;
}
else{
mystack[++top]=item;
cout<<"Item pushed :"<<item<<endl;
return true;
}
}
int pop(){
if(top<0){
cout<<"stack underflow...!!"<<endl;
return 0;
}
else{
int item= mystack[top--];
return item;
}
}
bool isempty(){
return(top<0);
}
int peek(){
if(top<0){
cout<<"stack is empty...!!!"<<endl;
return 0;
}
else{
int item = mystack[top];
return item;
}
}
int size(){
return top+1;
}
int isfull(){
if(top== n-1){
cout<<"Stack is full"<<endl;
return 0;
}else{
cout<<"stack has very space"<<endl;
return 0;
}
}
};
int main(){
stack s1(3);
s1.push(10);
s1.push(20);
s1.pop();
s1.peek();
s1.size();
s1.isfull();
s1.isempty();
return 0;
}

Dry Run:
---------------------------------------------------------------------
Queue
--------------------------------------------------------------------
#include <iostream>
using namespace std;

class LinearQueue {
int *arr;
int front, rear, capacity;

public:
LinearQueue(int size) {
capacity = size;
arr = new int[capacity];
front = -1;
rear = -1;
}

~LinearQueue() {
delete[] arr;
}

void enqueue(int val) {


if (rear == capacity - 1) {
cout << "Queue is full." << endl;
return;
}
if (front == -1) front = 0;
arr[++rear] = val;
cout << "Patron " << val << " added to the queue." << endl;
}

void dequeue() {
if (front == -1 || front > rear) {
cout << "Queue is empty." << endl;
return;
}
cout << "Patron " << arr[front++] << " removed from the queue." << endl;
}
void displayQueue() {
if (front == -1 || front > rear) {
cout << "Queue is empty." << endl;
return;
}
cout << "Current queue: ";
for (int i = front; i <= rear; i++) {
cout << arr[i] << " ";
}
cout << endl;
}
};

int main() {
LinearQueue q1(5);
q1.enqueue(101);
q1.enqueue(102);
q1.enqueue(103);
q1.displayQueue();
q1.dequeue();
q1.displayQueue();
q1.enqueue(104);
q1.enqueue(105);
q1.enqueue(106);
q1.displayQueue();
q1.dequeue();
q1.displayQueue();
return 0;
}

Dry Run:
--------------------------------------------------------------------
Bubble Sort
---------------------------------------------------------------------
#include<iostream>
using namespace std;

int main(){

int arr[5]={5,3,1,7,4};
int n =5;
for(int i=0;i<n;i++){
for(int j = i+1; j<n;j++){
if(arr[j]<arr[i]){
int temp = arr[i];
arr[i]= arr[j];
arr[j]= temp;
}
}
}
for(int i=0;i<5;i++){
cout<<arr[i]<<" ";
}

Dry Run:
-------------------------------------------------------------------
Selection Sort
--------------------------------------------------------------------
#include<iostream>
using namespace std;

int main(){

int arr[5]={4,7,1,3,9};
int n=5;

for(int i=0;i<n-1;i++){
for(int j=i+1;j<n;j++){
if(arr[j]<arr[i]){
int temp = arr[i];
arr[i]= arr[j];
arr[j]= temp;
}
}
}
for(int i=0;i<5;i++){
cout<<arr[i]<<" ";
}

Dry Run:
-----------------------------------------------------------------------
Insertion Sort
---------------------------------------------------------------------
#include<iostream>
using namespace std;

int main(){

int arr[5]={3,9,2,0,1};
int n=5;

for(int i=1;i<n;i++){
int current = arr[i];
int j=i-1;
while(arr[j]>current && j>=0){
arr[j+1]=arr[j];
j--;
}
arr[j+1]=current;
}
for(int i=0;i<5;i++){
cout<<arr[i]<<" ";
}

}
Dry Run:

-----------------------------------------------------------------------
Merge Sort
----------------------------------------------------------------------
#include<iostream>
using namespace std;

void merge(int arr[],int l,int mid,int r){


int size1= mid - l +1;
int size2 = r-mid;
int left[size1],right[size2];
for(int i=0;i<size1;i++){
left[i]=arr[l+i];
}
for(int i=0;i<size2;i++){
right[i]=arr[mid+1+i];
}

int i=0,j=0,k=l;

while(i<size1 && j<size2){


if(left[i] <= right[j]){
arr[k]=left[i];
k++;i++;
}else{
arr[k]=right[j];
k++;j++;
}
}
while(i<size1){
arr[k]=left[i];
k++;i++;
}
while(j<size2){
arr[k]=right[j];
k++;j++;
}

void mergesort(int arr[],int l,int r){


if(l<r){
int mid = (l+r)/2;
mergesort(arr,l,mid);
mergesort(arr,mid+1,r);
merge(arr,l,mid,r);
}
}

int main(){
int arr[5]={5,1,8,3,0};
mergesort(arr,0,4);
for(int i=0;i<5;i++){
cout<<arr[i]<<" ";
}

Dry Run:
Merge Sort Function:

Merge Function:
----------------------------------------------------------------------
Quick Sort:
---------------------------------------------------------------------
#include<iostream>
using namespace std;

void swap(int arr[],int i, int j){


int temp = arr[i];
arr[i]= arr[j];
arr[j] = temp;
}

int partition(int arr[],int l, int r){


int pivot = arr[r];
int i= l-1;
for(int j=l;j<r;j++){
if(arr[j]<=pivot){
i++;
swap(arr,i,j);
}
}
swap(arr,i+1,r);
return i+1;
}

void quicksort(int arr[],int l,int r){

if(l<r){
int pi = partition(arr,l,r);
quicksort(arr,l,pi-1);
quicksort(arr,pi+1,r);
}
}

int main(){
int arr[5]={3,1,9,7,0};
quicksort(arr,0,4);
for(int i=0;i<5;i++){
cout<<arr[i]<<" ";
}
return 0;
}

Dry Run:
-------------------------------------------------------------------
Radix Sort:
--------------------------------------------------------------------
Dry Run:
-------------------------------------------------------------------
Binary Search
--------------------------------------------------------------------

Dry Run:
-----------------------------------------------------------------------
Sample BST
----------------------------------------------------------------------
#include<iostream>
using namespace std;
class Node{
public:
int data;
Node* left;
Node* right;
Node(int d):data(d){
left = right = NULL;
}
};

void insert(Node*& root, int data){


if(root == NULL){
root = new Node(data);
return;
}
if(data < root->data){
insert(root->left,data);
}else{
insert(root->right,data);
}
}
void inorder(Node* root){
if(root){
inorder(root->left);
cout << root->data << " ";
inorder(root->right);
}
}
Node* min(Node* node)
{
Node* cur = node;
while(cur && cur->left)
{
cur = cur->left;
}
return cur;
}
Node* deleteNode(Node* node, int val)
{
if(!node)
return node;

if (val < node->data)


node->left = deleteNode(node->left,val);
else if(val > node->data)
node->right = deleteNode(node->right,val);
else
{
if(!node->left)
{
Node* tmp = node->right;
delete node;
return tmp;
}
else if(!node->right)
{
Node* tmp = node->left;
delete node;
return tmp;
}
Node* tmp = min(node->right);
node->data = tmp->data;
node->right = deleteNode(node->right,tmp->data);
}
return node;
}

int main(){
Node* root = NULL;
insert(root,16);
insert(root,5);
insert(root,3);
insert(root,9);
deleteNode(root,3);
cout << root->data<<" ";
inorder(root);
return 0;
}
Dry Run:

Traversal :
PreOrder: 1st Touch
InderOrder: 2nd Touch
PosOrder: 3rd Touch

#include <iostream>
#include <string>
using namespace std;

class BookNode {
public:
string isbn;
string title;
BookNode* left;
BookNode* right;

BookNode(string ISBN, string Title) {


isbn = ISBN;
title = Title;
left = NULL;
right = NULL;
}
};

BookNode* insert(BookNode* root, string ISBN, string Title) {


if (root == NULL) {
return new BookNode(ISBN, Title);
}
if (ISBN < root->isbn) {
root->left = insert(root->left, ISBN, Title);
} else {
root->right = insert(root->right, ISBN, Title);
}
return root;
}

void inorder_traversal(BookNode* root) {


if (root != NULL) {
inorder_traversal(root->left);
cout << "ISBN: " << root->isbn << " Title: " << root->title << endl;
inorder_traversal(root->right);
}
}

void preorder_traversal(BookNode* root) {


if (root != NULL) {
cout << "ISBN: " << root->isbn << " Title: " << root->title << endl;
preorder_traversal(root->left);
preorder_traversal(root->right);
}
}

void postorder_traversal(BookNode* root) {


if (root != NULL) {
postorder_traversal(root->left);
postorder_traversal(root->right);
cout << "ISBN: " << root->isbn << " Title: " << root->title << endl;
}
}

int main() {
BookNode* root = NULL;

// Inserting books into the BST


root = insert(root, "978-3-16-148410-0", "Book A");
root = insert(root, "978-1-86197-876-9", "Book B");
root = insert(root, "978-0-262-13472-9", "Book C");
root = insert(root, "978-0-12-374750-1", "Book D");

cout << "Inorder Traversal (Ascending order by ISBN):" << endl;


inorder_traversal(root);

cout << "\nPreorder Traversal:" << endl;


preorder_traversal(root);

cout << "\nPostorder Traversal:" << endl;


postorder_traversal(root);

return 0;
}

-------------------------------------------------------------------------------------------------

Binary Tree To BST


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

class Node {
public:
int data;
Node* left;
Node* right;
Node(int d) : data(d), left(nullptr), right(nullptr) {}
};

// Insert nodes into binary tree


Node* insertnode(Node* node, int value) {
if (!node)
return new Node(value);

if (!node->left)
node->left = insertnode(node->left, value);
else if (!node->right)
node->right = insertnode(node->right, value);
else
insertnode(node->left, value);

return node;
}

// Helper to find the rightmost node in a subtree (used for deletion in binary
tree)
Node* findRightmost(Node* root) {
while (root && root->right) {
root = root->right;
}
return root;
}

// Recursive deletion for binary tree (not a BST)


Node* deleteInBinaryTree(Node* root, int key) {
if (!root) return nullptr;

if (root->data == key) {
// If the node has two children, replace it with the rightmost node in
its left subtree
if (root->left && root->right) {
Node* rightmost = findRightmost(root->left);
root->data = rightmost->data;
root->left = deleteInBinaryTree(root->left, rightmost->data);
}
// If the node has one child or no children, replace it with that child
or nullptr
else {
Node* child = root->left ? root->left : root->right;
delete root;
return child;
}
} else {
root->left = deleteInBinaryTree(root->left, key);
root->right = deleteInBinaryTree(root->right, key);
}
return root;
}

// Inorder traversal for displaying the tree


void inorder(Node* root) {
if (!root) return;
inorder(root->left);
cout << " " << root->data;
inorder(root->right);
}

// Store inorder traversal of binary tree in array


void storeinorder(Node* root, int arr[], int& i) {
if (!root) return;
storeinorder(root->left, arr, i);
arr[i++] = root->data;
storeinorder(root->right, arr, i);
}

// Sort the array


void sort(int arr[], int n) {
for (int i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
if (arr[i] > arr[j]) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
}

// Convert sorted array to BST


void arraytobst(Node* root, int arr[], int& i) {
if (!root) return;
arraytobst(root->left, arr, i);
root->data = arr[i++];
arraytobst(root->right, arr, i);
}

// BST deletion
Node* deleteInBST(Node* root, int key) {
if (!root) return root;

// Traverse to the node to be deleted


if (key < root->data)
root->left = deleteInBST(root->left, key);
else if (key > root->data)
root->right = deleteInBST(root->right, key);
else {
// Node found, delete it
if (!root->left) {
Node* temp = root->right;
delete root;
return temp;
}
if (!root->right) {
Node* temp = root->left;
delete root;
return temp;
}

// Node with two children: Find the inorder successor


Node* successor = root->right;
while (successor->left)
successor = successor->left;

root->data = successor->data;
root->right = deleteInBST(root->right, successor->data);
}
return root;
}

int main() {
// Construct binary tree
Node* root = nullptr;
root = insertnode(root, 9);
root = insertnode(root, 1);
root = insertnode(root, 3);
root = insertnode(root, 2);
root = insertnode(root, 7);
root = insertnode(root, 4);
root = insertnode(root, 5);

// Display inorder traversal of the binary tree


cout << "Inorder traversal of the binary tree: ";
inorder(root);
cout << endl;

// Delete a node in the binary tree


root = deleteInBinaryTree(root, 3);
cout << "Binary tree after deleting node 3: ";
inorder(root);
cout << endl;

// Convert binary tree to BST


int arr[7];
int i = 0;
storeinorder(root, arr, i);
sort(arr, i);
i = 0;
arraytobst(root, arr, i);

// Display inorder traversal of the BST


cout << "Inorder traversal of the BST: ";
inorder(root);
cout << endl;

// Delete a node in the BST


root = deleteInBST(root, 7);
cout << "BST after deleting node 7: ";
inorder(root);
cout << endl;

return 0;
}

-------------------------------------------------------------------
AVL Tree:
-----------------------------------------------------------------
Exam Question AVL insertion,Deletion and Search : #include<iostream>
using namespace std;

class AVLtree{
public:
int price;
int height;
AVLtree*left;
AVLtree* right;
AVLtree(int p):price(p),height(1),left(NULL),right(NULL){}
};
AVLtree* rightrotation(AVLtree* y){
AVLtree* x = y->left;
AVLtree* T2 = x->right;
x->right = y;
y->left = T2;
return x;
}
AVLtree* leftrotation(AVLtree* x){
AVLtree* y = x->right;
AVLtree* T2 = y->left;
y->left = x;
x->right = T2;
return y;
}
int max(int a,int b){
int mx=0;
if(a>b)
mx=a;
else
mx=b;

return mx;
}
int height(AVLtree* root){
if(!root)
return -1;

return root->height;
}
int balancefactor(AVLtree* root){
return height(root->left) - height(root->right);
}
AVLtree* insertion(AVLtree* root, int price){
if(!root){
return new AVLtree(price);
}
if(price < root->price){
root->left = insertion(root->left,price);
}else if(price > root->price){
root->right = insertion(root->right,price);
}else{
cout<<" No Duplication is Allowed."<<endl;
}

root->height = 1 + max(height(root->left),height(root->right));
int BF = balancefactor(root);

if(BF > 1 && price < root->left->price){


return rightrotation(root);
}else if(BF > 1 && price > root->left->price){
root->left = leftrotation(root);
return rightrotation(root);
}else if( BF < 1 && price < root->right->price){
root->right = rightrotation(root->right);
return leftrotation(root);
}else if( BF < 1 && price > root->right->price){
return leftrotation(root);
}
return root;
}
AVLtree* searchNearestPrice(AVLtree* root, int budget) {
if (!root) {
return NULL;
}

if (root->price == budget) {
return root;
}

if (budget < root->price) {


AVLtree* left = searchNearestPrice(root->left, budget);
if (left != NULL) {
return left;
} else {
return root;
}
} else {
AVLtree* right = searchNearestPrice(root->right, budget);
if (right != NULL) {
return right;
} else {
return root;
}
}

}
AVLtree* minimum(AVLtree * node){
AVLtree* current = node;
while(!current && current->left ==NULL ){
current = current->left;
}
return current;
}
AVLtree* deletenode(AVLtree* root,int key){
if(root == NULL)
return root;
if(key < root->price){
root->left = deletenode(root->left,key);
}else if(key > root->price){
root->right = deletenode(root->right,key);
}else{
if(root->left == NULL || root->right == NULL){
AVLtree* temp;
if(root->left != NULL){
temp = root->left;
}else{
temp = root->right;
}
if(temp ==NULL){
temp = root;
root =NULL;
}else{
root =temp;
}
}else{
AVLtree* temp =minimum(root->right);
root->price = temp->price;
root->right = deletenode(root->right,temp->price);
}

}
if(root == NULL){
return root;
}

root->height = 1 + max(height(root->left),height(root->right));
int BF = balancefactor(root);

if(BF > 1 && key < root->left->price){


return rightrotation(root);
}else if(BF > 1 && key > root->left->price){
root->left = leftrotation(root);
return rightrotation(root);
}else if( BF < 1 && key < root->right->price){
root->right = rightrotation(root->right);
return leftrotation(root);
}else if( BF < 1 && key > root->right->price){
return leftrotation(root);
}
return root;
}
int main(){
AVLtree* product_price = NULL;
product_price = insertion(product_price, 321);
product_price = insertion(product_price, 400);
product_price = insertion(product_price, 550);
product_price = insertion(product_price, 620);
product_price = insertion(product_price, 870);

cout << "Enter Your Budget: " << endl;


int budget = 0;
cin >> budget;

AVLtree* nearestProduct = searchNearestPrice(product_price, budget);

if (nearestProduct != NULL) {
cout << "Suggested Product Price: " << nearestProduct->price << endl;
} else {
cout << "No product found within the budget." << endl;
}

return 0;
}

Dry Run:
----------------------------------------------------------------------
2-3 Tree
--------------------------------------------------------------------
1 Parent 2 Child
2 Parent 3 Child

Dry Run:
------------------------------------------------------------------
B-Tree
---------------------------------------------------------------------
If order is 3 then child will be 3 and keys in one node
will be 3-1 = 2
Dry Run:
---------------------------------------------------------------------
Heap
---------------------------------------------------------------------
Exam Question Heap: #include<iostream>
using namespace std;

class Minheap{
public:
int* arr;
int position;
int size;
Minheap(int s):size(s),position(0){
arr = new int[s];
}
int left(int i){
return i *2 +1;
}
int right(int i){
return i *2 +2;
}
int parent(int i){
return (i -1)/2;
}
void insertion(int score){
if(position == size){
cout<<"Heap is full, can not add more in Heap."<<endl;
}
arr[position] = score;
heapifyup(position);
position++;
}
void heapifyup(int pos){
while( pos != 0 && arr[parent(pos)] > arr[pos]){
swap(arr[parent(pos)],arr[pos]);
pos = parent(pos);
}
}
void heapifydown(int curr){
int min = curr;
int l =left(curr);
int r = right(curr);
if(l < position && arr[l] < arr[min]){
min = l;
}
if(r < position && arr[r] < arr[min]){
min = r;
}
if(min != curr){
swap(arr[min],arr[curr]);
heapifydown(min);
}
}
void deletemin(){
if(position == 0){
cout<<"No more scores"<<endl;
}
cout<<arr[0] <<" ";
arr[0] = arr[position -1];
position--;
heapifydown(0);
}
};
int main(){
int scores[7]={ 45,20,35,10,50,30,25 };
Minheap heap(7);
for(int i=0; i<7 ;i++){
heap.insertion(scores[i]);
}
cout << "Top Three Performers:";
for (int i = 0; i < 3; i++) {
heap.deletemin();
}
cout << endl;

cout << "Worst Performers: ";


for (int i = 0; i < 4; i++) {
heap.deletemin();
}
cout << endl;
return 0;
}

----------------------------------------------------------------------
Heap Sort
----------------------------------------------------------------------
#include <iostream>
using namespace std;

// Function to heapify a subtree rooted at index i

void heapify(int arr[], int n, int i) {

int largest = i; // Initialize largest as root

int left = 2 * i + 1; // Left child

int right = 2 * i + 2; // Right child

// If left child is larger than root

if (left < n && arr[left] > arr[largest]) {

largest = left;

// If right child is larger than the current largest

if (right < n && arr[right] > arr[largest]) {

largest = right;

// If largest is not root

if (largest != i) {

swap(arr[i], arr[largest]); // Swap root with the largest

heapify(arr, n, largest); // Recursively heapify the affected subtree

// Function to perform heap sort

void heapSort(int arr[], int n) {

// Build a max heap

for (int i = n / 2 - 1; i >= 0; i--) {

heapify(arr, n, i);

}
// Extract elements from heap one by one

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

// Move current root to the end

swap(arr[0], arr[i]);

// Call max heapify on the reduced heap

heapify(arr, i, 0);

int main() {

int arr[] = {14, 24, 12, 11, 25, 18, 35}; // Input array

int n = sizeof(arr) / sizeof(arr[0]);

cout << "Original array: ";

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

cout << arr[i] << " ";

cout << endl;

// Perform heap sort

heapSort(arr, n);

cout << "Sorted array: ";

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

cout << arr[i] << " ";

cout << endl;

return 0;
}

Dry Run:
----------------------------------------------------------------------
Priority Queue
----------------------------------------------------------------------
Priority Queue : #include <iostream>

using namespace std;

// Node class for the priority queue

class Node {

public:

int value; // The value of the element

int priority; // The priority of the element

Node* next; // Pointer to the next node in the queue

// Constructor to initialize node

Node(int val, int pri) : value(val), priority(pri), next(nullptr) {}

};

// PriorityQueue class

class PriorityQueue {

private:

Node* front; // Pointer to the front of the queue

public:

// Constructor to initialize the priority queue

PriorityQueue() : front(nullptr) {}

// Destructor to free the memory of all nodes

~PriorityQueue() {
while (front) {

Node* temp = front;

front = front->next;

delete temp;

// Insert a new element with a given priority

void insert(int val, int pri) {

Node* newNode = new Node(val, pri); // Create a new node with value and priority

// If the queue is empty or the new node has higher priority than the front

if (!front || pri > front->priority) {

newNode->next = front; // New node points to current front

front = newNode; // New node becomes the front

} else {

// Traverse the queue to find the correct position

Node* current = front;

while (current->next && current->next->priority >= pri) {

current = current->next;

// Insert the new node in its correct position

newNode->next = current->next;

current->next = newNode;

// Remove the element with the highest priority (front of the queue)

void remove() {

if (!front) { // Check if the queue is empty

cout << "Queue is empty!" << endl;


return;

Node* temp = front; // Store the front node to delete it

front = front->next; // Move front to the next node

delete temp; // Delete the old front node

// Peek at the element with the highest priority

int peek() const {

if (!front) { // Check if the queue is empty

cout << "Queue is empty!" << endl;

return -1; // Return an error value

return front->value; // Return the value of the front node

// Print all elements in the queue

void printQueue() const {

if (!front) { // Check if the queue is empty

cout << "Queue is empty!" << endl;

return;

// Traverse the queue and print each node's value and priority

Node* current = front;

while (current) {

cout << "(" << current->value << ", " << current->priority << ") ";

current = current->next;

cout << endl;

}
};

int main() {

PriorityQueue pq;

// Insert elements with different priorities

pq.insert(10, 3); // Element 10 with priority 3

pq.insert(20, 5); // Element 20 with priority 5

pq.insert(30, 2); // Element 30 with priority 2

pq.insert(40, 4); // Element 40 with priority 4

// Display the queue after insertion

cout << "Priority Queue: ";

pq.printQueue();

// Show the element with the highest priority

cout << "Element with highest priority: " << pq.peek() << endl;

// Remove the highest-priority element and display the updated queue

pq.remove();

cout << "After removing the highest priority element: ";

pq.printQueue();

// Remove another element and display the updated queue

pq.remove();

cout << "After removing another element: ";

pq.printQueue();

return 0;

}
--------------------------------------------------------------------
Hashing:
---------------------------------------------------------------------
Separate Chain Hashing:
#include<iostream>
#include<string.h>

// SEPERATE CHAIN HASHING

using namespace std;

class Node{
public:
string data;
Node* next;
Node(string d):data(d){
next = NULL;
}
};
int ascii(string word){
int as = 0;
for(int i=0; i< word.length();i++){
as += word[i];
}
return as;
}
class Hashtable{
public:
Node* hashtable[100];
Hashtable(){
for(int i = 0; i< 100;i++){
hashtable[i] = NULL;
}
}

void insert (string key, string sdata){


int index = ascii(key) % 100;
Node* newnode = new Node(sdata);
if(hashtable[index] == NULL){
hashtable[index] = newnode;
}else{
Node* temp = hashtable[index];
while(temp->next != NULL){
temp = temp->next;
}
temp->next = newnode;
}
}

void display(){
for(int i= 0; i<100 ; i++){
if(hashtable[i] != NULL){
cout<< i << " : ";
Node* temp = hashtable[i];
while(temp != NULL){
cout<<temp->data<<" -> ";
temp = temp->next;
}
cout<<" NULL"<<endl;
}
}
}
void search(string key){
for(int i= 0; i< 100; i++){
Node * temp = hashtable[i];
if(hashtable[i] != NULL){
while(temp != NULL){
if(key == temp->data){
cout<< key <<" Found "<< "at :"<< i <<endl;
return;
}
temp = temp->next;
}
}
}
cout<<key <<" is Not Found"<<endl;
}
};
int main(){

Hashtable table;

table.insert("AB","FASTUNI");
table.insert("AB","DHASUFFA");
table.insert("AC","IBA");
table.insert("AD","GIKI");
table.insert("AE","IQRA");
table.insert("AG","SZABIST");
table.insert("AZ","PIAS");
table.display();
table.search("IBA");
table.search("PIAS");
return 0;

Linear Probing:
#include<iostream>

// Linear Probing

using namespace std;

class Hashtable{
public:
int * hashtable;
Hashtable(){
hashtable = new int[10];
for(int i=0;i<100 ;i++){
hashtable[i] = -1;
}
}

void insert(int key){


int index = key % 10;
while(hashtable[index] != -1){

index = (index +1) % 10;


}
hashtable[index] = key;
}
void remove(int key){
for(int i=0;i< 100 ;i++){
if(hashtable [ i ] == key){
hashtable[i] = -1;
}
}
}
void search(int key){
for(int i=0;i< 100;i++){
if(hashtable[i] == key){
cout<< key <<" Found at "<< i<<endl;
return;
}
}
cout<<key <<" is not Found"<<endl;
}
void display(){
for(int i=0;i< 100;i++){
if(hashtable[i] != -1){
cout<<hashtable[i]<< " -- ";
}
}
}
};
int main(){

Hashtable table;
table.insert(1);
table.insert(3);
table.insert(4);
table.insert(5);
table.insert(7);
table.display();
cout<< endl;
cout<<" Remove 4 :"<<endl;
table.remove(4);
table.display();
cout<< endl;
table.search(5);
table.search(6);

}
Double Hashing:
Exam Question Double Hashing: #include<iostream>

#include<string>

using namespace std;

class Node {

public:

string key;

int frequency;

bool isoccupied;

Node() {

key = " ";

frequency = 0;

isoccupied = false;

Node(string s): key(s), frequency(0), isoccupied(false) {}

};

class Hashtable {

public:

Node* hashtable;

int tablesize;

int itemcount;

Hashtable() {

tablesize = 10;

itemcount = 0;
hashtable = new Node[tablesize];

int function1(string key) {

int hash = 0;

for(int i = 0; i < key.length(); i++) {

hash = (hash * 21 + key[i]) % tablesize;

return hash;

int function2(string key) {

int hash = 0;

for(int i = 0; i < key.length(); i++) {

hash = (hash * 31 + key[i]) % tablesize;

return (hash == 0) ? 1 : (tablesize - 1 - hash) % tablesize;

void resize() {

int oldsize = tablesize;

tablesize *= 2;

Node* oldtable = hashtable;

hashtable = new Node[tablesize];

for(int i = 0; i < oldsize; i++) {

insert(oldtable[i].key, oldtable[i].frequency);

delete[] oldtable;

oldtable = nullptr;

}
void insert(string key, int freq = 1) {

if (itemcount > tablesize / 2) {

resize();

int index = function1(key);

int step = function2(key);

while (hashtable[index].isoccupied && hashtable[index].key != key) {

index = (index + step) % tablesize;

if (!hashtable[index].isoccupied) {

hashtable[index].key = key;

hashtable[index].frequency = freq;

hashtable[index].isoccupied = true;

itemcount++;

} else {

hashtable[index].frequency += freq;

void display() {

for(int i = 0; i < tablesize; i++) {

if(hashtable[i].isoccupied) {

cout << hashtable[i].key << " : " << hashtable[i].frequency << endl;

};

int main() {
Hashtable table;

table.insert("hello");

table.insert("world");

table.insert("hello");

table.insert("example");

table.insert("frequency");

table.insert("world");

cout << "Word Frequencies:\n";

table.display();

return 0;

Sorting in Hashing:
Sorting in Hashing: #include<iostream>

#include<string>

using namespace std;

int size = 20;

class Booknode{

public:

string name;

Booknode* next;

Booknode(string n):name(n),next(nullptr){}

};

class hashbookshelf{

public:

int size = 20;


Booknode* shelves[20];

hashbookshelf(){

for(int i = 0 ; i< size; i++){

shelves[i] = NULL;

int hashfunction(string key){

int ascii = 0;

for(int i =0;i< key.length() ; i++){

ascii += key[i];

return ascii % 20;

int partition(string arr[],int l,int r){

string pivot = arr[r];

int i = l-1;

for(int j =l ; j< r ; j++){

if(arr[j] < pivot ){

i++;

swap(arr[i],arr[j]);

swap(arr[i+1],arr[r]);

return i+1;

void quicksort(string arr[],int l,int r){

if(l<r){

int pi = partition(arr,l,r);

quicksort(arr,l,pi-1);
quicksort(arr,pi+1,r);

int linkedlisttoarray(Booknode* head, string array[]){

if(head == NULL){

return 0;

int count = 0;

while(head != NULL){

array[count++] = head->name;

head = head->next;

return count;

Booknode* arraytolinkedlist(string array[],int count){

if(count == 0)

return NULL;

Booknode* head = new Booknode(array[0]);

Booknode* temp = head;

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

temp->next = new Booknode(array[i]);

temp = temp->next;

return head;

void addbook(string name){

int index = hashfunction(name);


cout<<"Adding book : "<<name <<" at index :"<<index<<endl;

Booknode* newNode = new Booknode(name);

if(shelves[index] == NULL){

shelves[index] = newNode;

else{

Booknode* temp = shelves[index];

while( temp->next != NULL){

temp = temp->next;

temp->next = newNode;

sortshelf(index);

void sortshelf(int index){

string books[20];

int count = linkedlisttoarray(shelves[index],books);

quicksort(books,0,count-1);

shelves[index] = arraytolinkedlist(books,count);

void deletebook(string name){

int index = hashfunction(name);

cout<<"Deleting book : "<<name <<" at index : "<<index<<endl;

Booknode* curr = shelves[index];

Booknode* prev = NULL;

while( curr != NULL && curr->name != name){

prev = curr;
curr = curr->next;

if(curr != NULL){

if(prev == NULL){

shelves[index] = curr->next;

}else{

prev->next = curr->next;

delete curr;

void displayallbooks(){

string allbooks[100];

int count = 0;

for(int i=0 ; i< 20 ;i++){

Booknode* curr = shelves[i];

while(curr != NULL){

allbooks[count++] = curr->name;

curr = curr->next;

quicksort(allbooks,0,count-1);

cout<<"All Books in Sorted Form :"<<endl;

for(int i=0 ; i< count ; i++){

cout<<allbooks[i]<<endl;

};

int main() {
hashbookshelf bookshelf;

bookshelf.addbook("AB");

bookshelf.addbook("CD");

bookshelf.addbook("EF");

bookshelf.addbook("AC");

bookshelf.addbook("AZ");

bookshelf.displayallbooks();

bookshelf.deletebook("AC");

bookshelf.displayallbooks();

return 0;

Dry Run:
----------------------------------------------------------------------
KMP String Algo & Graph Traversal
---------------------------------------------------------------------
Dry Run:
--------------------------------------------------------------------
Bruit Force Algo
-------------------------------------------------------------------
--------------------------------------------------------------
Dijeckstra Algo and Kruskal Algo and Topological
Sorting
---------------------------------------------------------------
-----------------------------------------------------------------
Use Provided Slides for more prep of graphs
---------------------------------------------------------------------

----------------------------------------------------------------------
Best of Luck
----------------------------------------------------------------------

You might also like