0% found this document useful (0 votes)
14 views16 pages

DSA Final

The document contains multiple C++ implementations for data structures including linked lists, queues, directed and undirected graphs, depth-first search (DFS), breadth-first search (BFS), and binary search trees (BST). Each section provides code for creating, manipulating, and traversing these data structures. The examples demonstrate operations such as adding nodes, deleting nodes, searching, and displaying the structures.

Uploaded by

spartaking960
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views16 pages

DSA Final

The document contains multiple C++ implementations for data structures including linked lists, queues, directed and undirected graphs, depth-first search (DFS), breadth-first search (BFS), and binary search trees (BST). Each section provides code for creating, manipulating, and traversing these data structures. The examples demonstrate operations such as adding nodes, deleting nodes, searching, and displaying the structures.

Uploaded by

spartaking960
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 16

Linked list

#include<iostream>
using namespace std;
class Node {
public:
int data;
Node* next;
// constructor
Node(int data) {
this->data = data;
this->next = NULL;
}
//destructor
~Node() {
this->data = data;
if (this->next != NULL) {
delete next;
this->next = NULL;
}
cout << " Memory free for node with data" << data << endl;
}
};
class linkedlist {
private:
Node* head;
Node* tail;
int length;
public:
linkedlist(int data) {
Node* newNode = new Node(data);
head = newNode;
tail = newNode;
length = 1;
}

void addtohead(int data) {


Node* newNode = new Node(data);
if (length == 0) {
head = newNode;
tail = newNode;
}
else {
newNode->next = head;
head = newNode;
}
length++;
}
void addtotail(int data) {
Node* newNode = new Node(data);
if (length == 0) {
head = newNode;
tail = newNode;
}
else {
tail->next = newNode;
tail = newNode;
}
length++;
}
void insertAtposition(int position, int d) {
//insert at position 1;
if (position == 1) {
addtohead(d);
return;
}
//insert at last position;
if (position>length) {
addtotail(d);
return;

}
// inserting at middle
Node* temp = head;
int cnt = 1;
while (cnt < position - 1) {
temp = temp->next;
cnt++;
}
//creating a Node for d;
Node* nodeToinsert = new Node(d);
nodeToinsert->next = temp->next;
temp->next = nodeToinsert;
length++;

}
Node* reverselinkedlist() {
if (head == NULL && head->next == NULL) {
return head;
}
Node* prev = NULL;
Node* curr = head;
Node* forward = NULL;
while (curr != NULL) {
forward = curr->next;
curr->next = prev;
prev = curr;
curr = forward;
}
head= prev;
}
bool search(int key) {
Node* temp = head;
while (temp != NULL) {
if (temp->data == key) {
return true;
}
temp = temp->next;
}
return false;
}
void deleteNode(int position) {
// deleting at 1 node
if (position == 1) {
Node* temp = head;
head = head->next;
temp->next = NULL;
delete temp;
}
else {
//deleting last and any middle node
Node* curr = head;
Node* prev = NULL;
int cnt = 1;
while (cnt < position) {
prev = curr;
curr = curr->next;
cnt++;
}
// last Node;
prev->next = curr->next;
curr->next = NULL;
delete curr;
}

}
Node* reverserdlinkedlist() {
if (head == NULL && head->next == NULL) {
return head;
}
Node* prev = NULL;
Node* forward = NULL;
Node* current = head;
while (current != NULL) {
forward = current->next;
current->next = prev;
prev = current;
current = forward;
}
head = prev;
}

void display() {
Node* temp = head;
while (temp != NULL) {
cout << temp->data << " -> ";
temp = temp->next;
}
cout << "NULL" << endl;
}
};

int main() {
cout << "Orignal linked list" << endl;
linkedlist* mylinkedlist = new linkedlist(13);
//mylinkedlist->addtohead(14);
mylinkedlist->addtohead(15);
// mylinkedlist->addtohead(16);
// mylinkedlist->addtohead(17);
mylinkedlist->addtotail(14);
mylinkedlist->addtotail(17);
//mylinkedlist->addtotail(16);
mylinkedlist->display();
cout << endl;
cout << "After inserting at position in linked list:" << endl;
mylinkedlist->insertAtposition(3,22);
mylinkedlist->display();
cout << endl;
cout << "Reversing linkedlist" << endl;
mylinkedlist->reverselinkedlist();
mylinkedlist->display();
cout << endl;
cout << " Deleting node in linkedlist ";
mylinkedlist->deleteNode(4);
mylinkedlist->display();
cout << endl;

cout << "Search Result for 13: " << (mylinkedlist->search(17) ? "Found" : "Not Found") << endl;
mylinkedlist->display();
cout << endl;
cout << "After reversing linked lis :" << endl;
mylinkedlist->reverserdlinkedlist();

mylinkedlist->display();
return 0;
}
With queue
#include <iostream>
#include <queue>
using namespace std;

queue<int> q;

void insertAtHead(int x) {
q.push(x);
}

void insertAtTail(int x) {
queue<int> temp;
while (!q.empty()) {
temp.push(q.front());
q.pop();
}
q.push(x);
while (!temp.empty()) {
q.push(temp.front());
temp.pop();
}
}

void insertAtPosition(int x, int position) {


if (position < 1 || position > q.size() + 1) {
cout << "Invalid position\n";
return;
}
queue<int> temp;
int count = 1;
while (!q.empty() && count < position) {
temp.push(q.front());
q.pop();
count++;
}
q.push(x);
while (!temp.empty()) {
q.push(temp.front());
temp.pop();
}
}

void deleteFromHead() {
if (q.empty()) {
cout << "Queue is empty\n";
return;
}
q.pop();
}

void deleteFromPosition(int position) {


if (position < 1 || position > q.size()) {
cout << "Invalid position or queue is empty\n";
return;
}
queue<int> temp;
int count = 1;
while (!q.empty() && count < position) {
temp.push(q.front());
q.pop();
count++;
}
q.pop();
while (!temp.empty()) {
q.push(temp.front());
temp.pop();
}
}

void display() {
queue<int> temp = q;
cout << "Queue: ";
while (!temp.empty()) {
cout << temp.front() << " ";
temp.pop();
}
cout << endl;
}

int main() {
cout << "Inserting at head" << endl;
insertAtHead(5);
insertAtHead(3);
display();
cout << endl;
cout << "Inserting at tail:" << endl;
insertAtTail(7);
display();
cout << endl;
cout << "Inserting at any position:" << endl;
insertAtPosition(4, 2);
display();
cout << "displaying queue:" << endl;
display(); // Queue: 3 4 5 7
cout << endl;
cout << "Deleting from head";
deleteFromHead();
display(); // Queue: 4 5 7
cout << endl;
cout << "Deleting at any position:";
deleteFromPosition(2);
cout << endl;
display(); // Queue: 4 7
//deleteFromPosition(3); // Invalid position
return 0;
}

BSF
Directed graph
#include<iostream>
#include <queue>
#include<vector>

using namespace std;

class graph {
int v;
vector<vector<int>> adj; // Adjacency list

public:
graph(int v) { // Constructor for graph
this->v = v;
adj.resize(v);
}

// Function to addEdge
void addEdge(int v, int u) {
adj[v].push_back(u);
}

// BFS function
void BFS(int start) {
vector<bool> visited(v, false); // All set to false initially
queue<int> q; // Creating queue to store vertices to be visited
visited[start] = true; // Mark the start vertex as visited and enqueue it
q.push(start);

while (!q.empty()) { // Continue until all vertices are visited


int vertex = q.front(); // Get the front vertex from the
queue
q.pop(); // Remove the front vertex from the
queue
cout << vertex << " "; // Print the current vertex
for (int neighbor : adj[vertex]) { // Visit all neighbors of
the current vertex
if (!visited[neighbor]) { // If the neighbor is not
visited yet
q.push(neighbor); // Enqueue it to visit later
visited[neighbor] = true; // Mark it as visited
}
}
}
}
};

int main() {
graph g(5);
g.addEdge(0, 3);
g.addEdge(3, 1);
g.addEdge(1, 2);
g.addEdge(1, 4);
// g.addEdge(2, 3);
// g.addEdge(3, 3);
cout << "BFS -> ";
g.BFS(0);
return 0;
}*/

undirected graph
#include<iostream>
#include<queue>
#include<vector>
using namespace std;

class graph {
int v;
vector<vector<int>> adj;
public:
graph(int v) {
this->v = v;
adj.resize(v, vector<int>(v, 0)); // Initialize a v x v matrix with 0s
}
void addEdge(int v, int u) {
adj[v][u] = 1;
adj[u][v] = 1; // Since it's an undirected graph
}
void BSFtraversal(int start) {
vector<bool> visited(v, false);
queue<int> q;
visited[start] = true;
q.push(start);
while (!q.empty()) {
int vertex = q.front();
q.pop();
cout << vertex << " ";
for (int neighbor = 0; neighbor < v; ++neighbor) {
if (adj[vertex][neighbor] == 1 && !visited[neighbor]) {
q.push(neighbor);
visited[neighbor] = true;
}
}
}
}
};

int main() {
graph g(5);
g.addEdge(0, 3);
g.addEdge(3, 1);
g.addEdge(1, 2);
g.addEdge(1, 4);

cout << "BSF traversal->";


g.BSFtraversal(0);
return 0;
}
undirected graph
#include <iostream>
#include <queue>
#include <vector>

using namespace std;

class Graph {
int v;
vector<vector<int>> adjMatrix; // Adjacency matrix

public:
Graph(int v) { // Constructor for graph
this->v = v;
adjMatrix.resize(v, vector<int>(v, 0)); // Initialize adjacency matrix with 0s
}

// Function to addEdge
void addEdge(char v, char u) {
//adj[v, 'A'][u, 'A'] = 1;
//adj[u, 'A'][v, 'A'] = 1;
adjMatrix[v - 'A'][u - 'A'] = 1;
adjMatrix[u - 'A'][v - 'A'] = 1; // Since it's an undirected graph
}

// BFS function
void BFS(char start) {
vector<bool> visited(v, false); // All set to false initially
queue<char> q; // Creating queue to store vertices to be visited
visited[start - 'A'] = true; // Mark the start vertex as visited and enqueue it
q.push(start);

while (!q.empty()) { // Continue until all vertices are visited


char vertex = q.front(); // Get the front vertex from the queue
q.pop(); // Remove the front vertex from the queue
cout << vertex << " "; // Print the current vertex
for (int neighbor = 0; neighbor < v; ++neighbor) { // Visit all neighbors of the current
vertex
if (adjMatrix[vertex - 'A'][neighbor] == 1 && !visited[neighbor]) { // If the neighbor is
not visited yet
q.push(neighbor + 'A'); // Enqueue it to visit later
visited[neighbor] = true; // Mark it as visited
}
}
}
}
};

int main() {
Graph g(8);
g.addEdge('A', 'D');
g.addEdge('A', 'B');
g.addEdge('A', 'C');
g.addEdge('B', 'E');
g.addEdge('B', 'C');
g.addEdge('B', 'C');
g.addEdge('D', 'F');
g.addEdge('D', 'C');
g.addEdge('E', 'C');
g.addEdge('G', 'D');
g.addEdge('G', 'F');
g.addEdge('G', 'H');
g.addEdge('H', 'C');

cout << "printing BFS traversal of graph" << endl;


cout << "BFS -> ";
g.BFS('A');
return 0;
}

DSF
#include <iostream>
#include <vector>
#include <stack>
using namespace std;

class Graph {
int V;
vector<vector<int>> adj;

public:
Graph(int V) {
this->V = V;
this->adj.resize(V);
}

void addEdge(int u, int v) {


adj[u].push_back(v); // Add edge from u to v
}

void DFS(int start) {


vector<bool> visited(V, false);
stack<int> s;
s.push(start);

while (!s.empty()) {
int vertex = s.top();
s.pop();

if (!visited[vertex]) {
cout << vertex << " ";
visited[vertex] = true;

// Push unvisited neighbors onto the back of the queue


for (int neighbor : adj[vertex]) {
if (!visited[neighbor]) {
s.push(neighbor);
}
}
}
}
}
};
int main() {
Graph g(5); // Example with 7 vertices
g.addEdge(0, 2);
g.addEdge(2,1);
g.addEdge(1, 3);
g.addEdge(3, 4);
g.addEdge(4,2);

cout << "DFS traversal using stack: ";


g.DFS(0);

return 0;
}

Binary search tree


#include<iostream>
#include<queue>
using namespace std;
//creating class for node
class node {
public:
int data;
node* left;
node* right;
node(int data) {
this->data = data;
this->left = NULL;
this->right = NULL;
}
};
//insertinBST
node* insertinBST(node* root, int d) {
if (root == NULL) {
root = new node(d);
return root;
}
if (d > root->data) {
root->right = insertinBST(root->right, d);
}
else {
root->left = insertinBST(root->left, d);
}
return root;
}
//takeinput
void takeinput(node*& root) {
int data;
cin >> data;
while (data != -1) {
root = insertinBST(root, data);
cin >> data;
}
}
// levelorder traversal in BST
void levelOrdertraversal(node* root) {
queue<node*>q;
q.push(root);
q.push(NULL);
while (!q.empty()) {
node* temp = q.front();
q.pop();
if (temp == NULL) {
cout << endl;
if (!q.empty()) {
q.push(NULL);
}
}

else {
cout << temp->data << " ";
if (temp->left) {
q.push(temp->left);
}
if (temp->right) {
q.push(temp->right);
}
}
}
}

// inorder traversal
void inorder(node* root){
if (root == NULL) {
return;
}
else {
inorder(root->left);
cout << root->data << " ";
inorder(root->right);
}

}
//preorder traversal
void preorder(node* root) {
if (root == NULL) {
return;
}
else {
cout << root->data << " ";
preorder(root->left);
preorder(root->right);
}
}
// postorder traversal
void postorder(node* root) {
if (root == NULL) {
return;
}
else {
postorder(root->left);
postorder(root->right);
cout << root->data << " ";
}
}
//searching in BST
bool searchinBST(node* root, int x) {
if (root == NULL) {
return false;
}
if (root->data == x) {
return true;
}
if(root->data > x){
return searchinBST(root->left, x);
}
else {
return searchinBST(root->right, x);
}
}
// finding min value in BST
node* minVal(node* root) {
node* temp = root;
while (temp->left != NULL) {
temp = temp->left;
}
return temp;
}
// finding max value in BST
node* maxVal(node* root) {
node* temp = root;
while (temp->right != NULL) {
temp = temp->right;
}
return temp;
}

//Deleting value from BST;


node* DeleteFromBST(node* root, int value) {
if (root == NULL) {
return NULL;
}
if (root->data == value) {
// 0 child
if (root->left == NULL && root->right == NULL) {
delete root;
return NULL;
}
// 1 child
if (root->left != NULL && root->right == NULL) {
node* temp = root->left;
delete root;
return temp;
}
if (root->left == NULL && root->right != NULL) {
node* temp = root->right;
delete root;
return temp;
}
// 2 children
if (root->left != NULL && root->right != NULL) {
node* min = minVal(root->right);
root->data = min->data;
root->right = DeleteFromBST(root->right, min->data);
return root;
}
}
else if (root->data > value) {
root->left = DeleteFromBST(root->left, value);
}
else {
root->right = DeleteFromBST(root->right, value);
}
return root;
}

int main() {
node* root = NULL;
// 50 20 70 10 30 90 110 -1
cout << "Enter data to create BST:" << endl;
takeinput(root);

cout << "Printing level order traversal:" << endl;

levelOrdertraversal(root);
cout << endl;
//inoreder traversal
cout << "printing inorder traversal:" << endl;

inorder(root);
cout << endl;
//preoreder traversal
cout << "printing preorder traversal:" << endl;

preorder(root);
cout << endl;
//postoreder traversal
cout << "printing postorder traversal:" << endl;
postorder(root);
cout << endl;
//Searching in BST
cout << "Searching in BST: " << (searchinBST(root,90) ? "Found" : "Not Found") <<
endl;
cout << endl;
levelOrdertraversal(root);
cout << endl;
//finding minvalue in BST
cout << "min value of binary search tree is " << minVal(root)->data << endl;
//minVal(root);
cout << "max value of binary search tree is " << maxVal(root)->data << endl;
cout << endl;
DeleteFromBST(root, 50);
cout << endl;
cout << "After deleting value from BST:" << endl;
levelOrdertraversal(root);
cout << endl;
//finding minvalue in BST
cout << "min value of binary search tree is " << minVal(root)->data << endl;
//minVal(root);
cout << "max value of binary search tree is " << maxVal(root)->data << endl;
return 0;
}

Binarry tree
#include <iostream>
#include<queue>
using namespace std;
class node {
public:
int data;
node* left;
node*right;
// constructor;
node(int data) {
this->data = data;
this->left = NULL;
this->right = NULL;
}
};
//building tree;
node* buildtree(node* root) {
cout << "Enter data:" << endl;
int data;
cin >> data;
root = new node(data);//Node Creation:
if (data == -1) {
return NULL;
}
cout << "Enter data inserting at left of " << data << endl;
root->left = buildtree(root->left);
cout << "Enter data inserting at right of " << data << endl;
root->right = buildtree(root->right);
return root;
}
// levelOrdertraversal
void levelOrdertraversal(node*root) {
queue<node*>q;
q.push(root);
q.push(NULL);
while (!q.empty()) {
node* temp = q.front();
q.pop();
if (temp == NULL) {
cout << endl;
if (!q.empty()) {
q.push(NULL);
}
}

else {
cout<< temp -> data << " ";
if (temp->left) {
q.push(temp -> left);
}
if (temp->right) {
q.push(temp -> right);
}
}
}
}
void inorder(node* root) {
if (root == NULL) {
return;
}
else {
inorder(root->left);
cout << root->data << " ";
inorder(root->right);
}
}
void preorder(node* root) {
if (root == NULL) {
return;
}
else {
cout << root->data << " ";
preorder(root->left);
preorder(root->right);
}
}
void postorder(node* root) {
if (root == NULL) {
return;
}
else {
postorder(root->left);
postorder(root->right);
cout << root->data << " ";
}
}
int main() {
node* root = NULL;
//creating a tree
root = buildtree(root);
// 1 3 7 -1 -1 11 -1 -1 5 17 -1 -1 -1
//level order
//cout << "printing the level order traversal output" << endl;
//levelOrdertraversal(root);
cout << "Inorder traversal is:";
inorder(root);
cout << endl;
cout << "preorder traversal is:";
preorder(root);
cout << endl;
cout << "postorder traversal is:";
postorder(root);
return 0;
}

You might also like