All Codes DSA
All Codes DSA
position
#include <iostream>
using namespace std;
class Node
{
public:
int data;
Node* next;
Node(int data)
{
this -> data = data;
this -> next = NULL;
}
};
//insert at Start
if(posidon == 1)
{
insertAtHead(head, d);
return;
}
Node* temp = head;
int cnt = 1;
int main()
{
Node* node1 = new Node(1);
print(head);
insertAtPosidon(tail,head, 4, 22);
print(head);
}
class Queue {
private:
Node *front, *rear;
public:
Queue()
{
front = rear = NULL;
}
void dequeue()
{
Node *temp = front;
if (front == NULL) {
cout << "Queue is empty" << endl;
return;
}
if (front == rear) {
front = rear = NULL;
} else {
front = front->next;
}
delete temp;
}
void display()
{
Node *temp = front;
while (temp != NULL) {
cout << temp->data << " ";
temp = temp->next;
}
cout << endl;
}
};
int main() {
Queue q;
q.enqueue(4);
q.enqueue(1);
q.enqueue(3);
cout << "Elements in queue ajer enqueue: ";
q.display();
q.dequeue();
cout << "Elements in queue ajer first dequeue: ";
q.display();
q.enqueue(8);
cout << "Elements in queue ajer second enqueue: ";
q.display();
q.dequeue();
cout << "Elements in queue ajer second dequeue: ";
q.display();
return 0;
}
// Node structure
struct Node {
int data;
Node *next;
};
if (temp == NULL)
return head;
prev->next = temp->next;
delete temp;
return head;
}
// FuncMon to delete all prime nodes from the stack
Node *deletePrimes(Node *head)
{
Node *temp = head;
int main() {
Node *head = NULL;
head = push(head, 20);
head = push(head, 15);
head = push(head, 19);
head = push(head, 7);
head = push(head, 17);
head = push(head, 11);
cout << "Original Stack: ";
printStack(head);
head = deletePrimes(head);
cout << "Stack after deleting prime nodes: ";
printStack(head);
return 0;
}
Stack using LL
// C++ program to Implement a stack
// using singly linked list
#include <bits/stdc++.h>
using namespace std;
// Constructor
Node(int n)
{
this->data = n;
this->link = NULL;
}
};
class Stack {
Node* top;
public:
Stack() { top = NULL; }
// Function to remove
// a key from given queue q
void pop()
{
Node* temp;
// Check for stack underflow
if (top == NULL) {
cout << "\nStack Underflow" << endl;
exit(1);
}
else {
// Driven Program
int main()
{
// Creating a stack
Stack s;
return 0;
}
#include <bits/stdc++.h>
using namespace std;
struct QNode {
int data;
QNode* next;
QNode(int d)
{
data = d;
next = NULL;
}
};
struct Queue {
QNode *front, *rear;
Queue() { front = rear = NULL; }
void enQueue(int x)
{
// Create a new LL node
QNode* temp = new QNode(x);
// Function to remove
// a key from given queue q
void deQueue()
{
// If queue is empty, return NULL.
if (front == NULL)
return;
delete (temp);
}
};
// Driver code
int main()
{
Queue q;
q.enQueue(10);
q.enQueue(20);
q.deQueue();
q.deQueue();
q.enQueue(30);
q.enQueue(40);
q.enQueue(50);
q.deQueue();
cout << "Queue Front : " << ((q.front != NULL) ? (q.front)->data : -1)<< endl;
cout << "Queue Rear : " << ((q.rear != NULL) ? (q.rear)->data : -1);
}
Fractional Knapsack
// DARSH GUPTA 20BEC0563
#include<iostream>
#include<algorithm>
using namespace std;
struct Item
{
int value, weight;
double rago;
};
int main()
{
int W = 60; // Maximum weight the thief can carry
Item arr[] = {{30, 5}, {40, 10}, {45, 15}, {77, 22}, {90, 25}}; // Values and weights of items
int n = sizeof(arr) / sizeof(arr[0]);
for(int i=0; i<n; i++)
arr[i].rago = (double) arr[i].value / arr[i].weight; // Calculate value per unit weight rago
double maxvalue = fracgonalKnapsack(W, arr, n);
cout << "Maximum value that can be carried by the thief: " << maxvalue << endl;
return 0;
}
0/1 Knapsack
/* A Naive recursive implementation of
0-1 Knapsack problem */
#include <bits/stdc++.h>
using namespace std;
// Base Case
if (n == 0 || W == 0)
return 0;
// Driver code
int main()
{
int profit[] = { 60, 100, 120 };
int weight[] = { 10, 20, 30 };
int W = 50;
int n = sizeof(profit) / sizeof(profit[0]);
cout << knapSack(W, weight, profit, n);
return 0;
}
if (wt[i] > W) {
// Driver Code
int main()
{
int profit[] = { 60, 100, 120 };
int weight[] = { 10, 20, 30 };
int W = 50;
int n = sizeof(profit) / sizeof(profit[0]);
cout << knapSack(W, weight, profit, n);
return 0;
}
class Node
{
public:
int data;
Node *left;
Node *right;
Node (int data)
{
this->data = data;
this->left = NULL;
this->right = NULL;
}
};
postOrder (root->left);
postOrder (root->right);
cout << root->data << " ";
}
}
int main ()
{
Node *root = NULL;
int data[] = { 14, 12, 3, 5, 9, 7, 5, 4, 12, 13, 22 };
int n = sizeof (data) / sizeof (data[0]);
for (int i = 0; i < n; i++)
{
root = insert (root, data[i]);
}
cout << "Pre-Order Traversal of the binary tree: " << endl;
preOrder (root);
cout << endl;
cout << "In-Order Traversal of the binary tree: " << endl;
inOrder (root);
cout << endl;
cout << "Post-Order Traversal of the binary tree: " << endl;
postOrder (root);
cout << endl;
return 0;
}
BST Deletion
// 20BEC0563 DARSH GUPTA
#include <iostream>
using namespace std;
class Node {
public:
int data;
Node *leR;
Node *right;
Node(int data) {
this->data = data;
this->leR = NULL;
this->right = NULL;
}
};
else {
if (root->leR == NULL) {
Node *temp = root->right;
delete root;
return temp;
}
else if (root->right == NULL) {
Node *temp = root->leR;
delete root;
return temp;
}
else {
Node *temp = findMinNode(root->right);
root->data = temp->data;
root->right = deleteNode(root->right, temp->data);
}
}
return root;
}
int main() {
Node *root = NULL;
int data[] = {11, 6, 8, 19, 4, 10, 5, 17, 43, 49, 31};
int n = sizeof(data) / sizeof(data[0]);
for (int i = 0; i < n; i++) {
root = insert(root, data[i]);
}
cout << "Binary Search Tree: ";
inOrder(root);
cout << endl;
cout << "ARer deledng 19: ";
root = deleteNode(root, 19);
inOrder(root);
cout << endl;
cout << "ARer deledng 11: ";
root = deleteNode(root, 11);
inOrder(root);
cout << endl;
cout << "ARer deledng 5: ";
root = deleteNode(root, 5);
inOrder(root);
cout << endl;
return 0;
}
temp->data = data;
temp->left = temp->right = NULL;
return temp;
}
if (*postIndex >= 0)
{
// Driver Code
int main ()
{
int post[] = {1, 7, 5, 50, 40, 10};
int size = sizeof(post) / sizeof(post[0]);
return 0;
}
return root;
}
/* UTILITY FUNCTIONS */
/* Function to find index of the maximum value in arr[start...end] */
int max (int arr[], int strt, int end)
{
int i, max = arr[strt], maxind = strt;
for(i = strt + 1; i <= end; i++)
{
if(arr[i] > max)
{
max = arr[i];
maxind = i;
}
}
return maxind;
}
/* Driver code*/
int main()
{
/* Assume that inorder traversal of following tree is given
40
/\
10 30
/ \
5 28 */
Caesar Cipher
// DARSH GUPTA 20BEC0563
// CAESAR CIPHER
#include <iostream>
using namespace std;
string encrypt(string text, int shiM)
{
string result = "";
for (int i = 0; i < text.length(); i++)
{
if (isupper(text[i]))
result += char(int(text[i] + shiM - 65) % 26 + 65);
else
result += char(int(text[i] + shiM - 97) % 26 + 97);
}
return result;
}
int main()
{
string text;
int shiM;
Insertion Sort
// C++ program for insertion sort
// Darsh Gupta 20BEC0563
#include <iostream>
using namespace std;
// Driver code
int main()
{
int arr[] = {4,3,2,10,12,1,5,6};
int N = sizeof(arr) / sizeof(arr[0]);
inser6onSort(arr, N);
printArray(arr, N);
return 0;
}
Merge Sort
// Merge sort in C++
#include <iostream>
using namespace std;
// Divide the array into two subarrays, sort them and merge them
void mergeSort(int arr[], int l, int r) {
if (l < r) {
// m is the point where the array is divided into two subarrays
int m = l + (r - l) / 2;
mergeSort(arr, l, m);
mergeSort(arr, m + 1, r);
// Driver program
int main() {
int arr[] = {6, 5, 12, 10, 9, 1};
int size = sizeof(arr) / sizeof(arr[0]);
Bubble Sort
// Optimized implementation of Bubble sort
#include <bits/stdc++.h>
using namespace std;
Quick Sort
// DARSH GUPTA 20BEC0563
#include<iostream>
using namespace std;
int par66on( int arr[], int s, int e) {
int pivot = arr[s];
int cnt = 0;
for(int i = s+1; i<=e; i++) {
if(arr[i] <=pivot) {
cnt++;
}
}
//place pivot at right posi6on
int pivotIndex = s + cnt;
swap(arr[pivotIndex], arr[s]);
//leZ and right wala part smbhal lete h
int i = s, j = e;
while(i < pivotIndex && j > pivotIndex) {
while(arr[i] <= pivot)
{
i++;
}
while(arr[j] > pivot) {
j--;
}
if(i < pivotIndex && j > pivotIndex) {
swap(arr[i++], arr[j--]);
}
}
return pivotIndex;
}
void quickSort(int arr[], int s, int e) {
//base case
if(s >= e)
return ;
//perform par66on
int p = par66on(arr, s, e);
//Sort leZ part
quickSort(arr, s, p-1);
//Sort Right Part
quickSort(arr, p+1, e);
}
int main() {
int arr[8] = {2,7,3,9,1,6,8,4};
int n = 8;
quickSort(arr, 0, n-1);
for(int i=0; i<n; i++)
{
cout << arr[i] << " ";
} cout << endl;
return 0;
}
BFS Graphs
// Program to print BFS traversal from a given
// source vertex. BFS(int s) traverses ver4ces
// reachable from s.
#include <bits/stdc++.h>
using namespace std;
// This class represents a directed graph using
// adjacency list representaton
class Graph {
int V; // No. of ver4ces
// Pointer to an array containing adjacency
// lists
vector<list<int> > adj;
public:
Graph(int V); // Constructor
// func4on to add an edge to graph
void addEdge(int v, int w);
// prints BFS traversal from a given source s
void BFS(int s);
};
Graph::Graph(int V)
{
this->V = V;
adj.resize(V);
}
void Graph::BFS(int s)
{
// Mark all the ver4ces as not visited
vector<bool> visited;
visited.resize(V, false);
// Create a queue for BFS
list<int> queue;
// Mark the current node as visited and enqueue it
visited[s] = true;
queue.push_back(s);
while (!queue.empty()) {
// Dequeue a vertex from queue and print it
s = queue.front();
cout << s << " ";
queue.pop_front();
// Get all adjacent ver4ces of the dequeued
// vertex s. If a adjacent has not been visited,
// then mark it visited and enqueue it
for (auto adjacent : adj[s])
{
if (!visited[adjacent]) {
visited[adjacent] = true;
queue.push_back(adjacent);
}
}
}
}
// Driver code
int main()
{
string exp = "231*+9-";
// Function call
cout << "postfix evaluation: " << evaluatePostfix(exp);
return 0;
}
Dijkstras Algo
// C++ program for Dijkstra's single source shortest path
// algorithm. The program is for adjacency matrix
// representa4on of the graph
#include <iostream>
using namespace std;
#include <limits.h>
// Number of ver4ces in the graph
#define V 9
// A u4lity func4on to find the vertex with minimum
// distance value, from the set of ver4ces not yet included
// in shortest path tree
int minDistance(int dist[], bool sptSet[])
{
// Ini4alize min value
int min = INT_MAX, min_index;
for (int v = 0; v < V; v++)
if (sptSet[v] == false && dist[v] <= min)
min = dist[v], min_index = v;
return min_index;
}
// A u4lity func4on to print the constructed distance
// array
void printSolu4on(int dist[])
{
cout << "Vertex \t Distance from Source" << endl;
for (int i = 0; i < V; i++)
{
char c = i + '0' + 17;
cout << c << " \t\t\t\t" << dist[i] << endl;
}
}
// Func4on that implements Dijkstra's single source
// shortest path algorithm for a graph represented using
// adjacency matrix representa4on
void dijkstra(int graph[V][V], int src)
{
int dist[V]; // The output array. dist[i] will hold the
// shortest
// distance from src to i
bool sptSet[V]; // sptSet[i] will be true if vertex i is
// included in shortest
// path tree or shortest distance from src to i is
// finalized
// Ini4alize all distances as INFINITE and stpSet[] as
// false
for (int i = 0; i < V; i++)
dist[i] = INT_MAX, sptSet[i] = false;
// Distance of source vertex from itself is always 0
dist[src] = 0;
// Find shortest path for all ver4ces
for (int count = 0; count < V - 1; count++) {
// Pick the minimum distance vertex from the set of
// ver4ces not yet processed. u is always equal to
// src in the first itera4on.
int u = minDistance(dist, sptSet);
// Mark the picked vertex as processed
sptSet[u] = true;
// Update dist value of the adjacent ver4ces of the
// picked vertex.
for (int v = 0; v < V; v++)
// Update dist[v] only if is not in sptSet,
// there is an edge from u to v, and total
// weight of path from src to v through u is
// smaller than current value of dist[v]
if (!sptSet[v] && graph[u][v]
&& dist[u] != INT_MAX
&& dist[u] + graph[u][v] < dist[v])
dist[v] = dist[u] + graph[u][v];
}
// print the constructed distance array
printSolu4on(dist);
}
// driver's code
int main()
{
/* Let us create the example graph discussed above */
int graph[V][V] = { { 0, 5, 7, 0, 0, 0, 0, 0, 0 },
{ 5, 0, 10, 4, 0, 0, 17, 0, 0},
{ 7, 10, 0, 3, 15, 0, 0, 0, 0},
{ 0, 4, 3, 0, 1, 0, 0, 0, 0},
{ 0, 0, 15, 1, 0, 3, 0, 0, 0},
{ 0, 0, 0, 0, 3, 0, 2, 0, 0},
{ 0, 17, 0, 0, 0, 2, 0, 15, 4},
{ 0, 0, 0, 0, 0, 0, 15, 0, 2},
{ 0, 0, 0, 0, 0, 0, 4, 2, 0 }
};
// Func4on call
dijkstra(graph, 0);
return 0;
}