mirror of
https://github.com/TheAlgorithms/C-Plus-Plus.git
synced 2026-04-02 02:02:23 +08:00
Major rework to improve code quality and add automation checks (#805)
* delete secant method - it is identical to regula falsi * document + improvize root finding algorithms * attempt to document gaussian elimination * added file brief * commented doxygen-mainpage, added files-list link * corrected files list link path * files-list link correction - this time works :) * document successive approximations * cleaner equation * updating DIRECTORY.md * documented kmp string search * document brute force string search * document rabin-karp string search * fixed mainpage readme * doxygen v1.8.18 will suppress out the #minipage in the markdown * cpplint correction for header guard style * github action to auto format source code per cpplint standard * updated setting to add 1 space before `private` and `public` keywords * auto rename files and auto format code * added missing "run" for step * corrected asignmemt operation * fixed trim and assign syntax * added git move for renaming bad filenames * added missing pipe for trim * added missing space * use old and new fnames * store old fname using echo * move files only if there is a change in filename * put old filenames in quotes * use double quote for old filename * escape double quotes * remove old_fname * try escape characters and echo" * add file-type to find * cleanup echo * ensure all trim variables are also in quotes * try escape -quote again * remove second escpe quote * use single quote for first check * use carets instead of quotes * put variables in brackets * remove -e from echo * add debug echos * try print0 flag * find command with while instead of for-loop * find command using IFS instead * 🎉 IFS fix worked - escaped quotes for git mv * protetc each word in git mv .. * filename exists in lower cases - renamed * 🎉 git push enabled * updating DIRECTORY.md * git pull & then push * formatting filenamesd7af6fdc8c* formatting source-code ford7af6fdc8c* remove allman break before braces * updating DIRECTORY.md * added missing comma lost in previous commit * orchestrate all workflows * fix yml indentation * force push format changes, add title to DIRECTORY.md * pull before proceeding * reorganize pull commands * use master branches for actions * rename .cc files to .cpp * added class destructor to clean up dynamic memory allocation * rename to awesome workflow * commented whole repo cpplint - added modified files lint check * removed need for cpplint * attempt to use actions/checkout@master * temporary: no dependency on cpplint * formatting filenames153fb7b8a5* formatting source-code for153fb7b8a5* updating DIRECTORY.md * fix diff filename * added comments to the code * added test case * formatting source-code fora850308fba* updating DIRECTORY.md * added machine learning folder * added adaline algorithm * updating DIRECTORY.md * fixed issue [LWG2192](https://cplusplus.github.io/LWG/issue2192) for std::abs on MacOS * add cmath for same bug: [LWG2192](https://cplusplus.github.io/LWG/issue2192) for std::abs on MacOS * formatting source-code forf8925e4822* use STL's inner_product * formatting source-code forf94a330594* added range comments * define activation function * use equal initial weights * change test2 function to predict * activation function not friend * previous commit correction * added option for predict function to return value before applying activation function as optional argument * added test case to classify points lying within a sphere * improve documentation for adaline * formatting source-code for15ec4c3aba* added cmake to geometry folder * added algorithm include for std::max * add namespace - machine_learning * add namespace - statistics * add namespace - sorting * added sorting algos to namespace sorting * added namespace string_search * formatting source-code forfd69530515* added documentation to string_search namespace * feat: Add BFS and DFS algorithms to check for cycle in a directed graph * Remove const references for input of simple types Reason: overhead on access * fix bad code sorry for force push * Use pointer instead of the non-const reference because apparently google says so. * Remove a useless and possibly bad Graph constuctor overload * Explicitely specify type of vector during graph instantiation * updating DIRECTORY.md * find openMP before adding subdirectories * added kohonen self organizing map * updating DIRECTORY.md * remove older files and folders from gh-pages before adding new files * remove chronos library due to inacceptability by cpplint * use c++ specific static_cast instead * initialize radom number generator * updated image links with those from CPP repository * rename computer.... folder to numerical methods * added durand kerner method for root computation for arbitrarily large polynomials * fixed additional comma * fix cpplint errors * updating DIRECTORY.md * convert to function module * update documentation * move openmp to main loop * added two test cases * use INT16_MAX * remove return statement from omp-for loop and use "break" * run tests when no input is provided and skip tests when input polynomial is provided * while loop cannot have break - replaced with continue and check is present in the main while condition * (1) break while loop (2) skip runs on break_loop instead of hard-break * add documentation images * use long double for errors and tolerance checks * make iterator variable i local to threads * add critical secions to omp threads * bugfix: move file writing outside of the parallel loop othersie, there is no gurantee of the order of roots written to file * rename folder to data_structures * updating DIRECTORY.md * fix ambiguous symbol `size` * add data_structures to cmake * docs: enable tree view, add timestamp in footer, try clang assistaed parsing * doxygen - open links in external window * remove invalid parameter from function docs * use HTML5 img tag to resize images * move file to proper folder * fix documentations and cpplint * formatting source-code foraacaf9828c* updating DIRECTORY.md * cpplint: add braces for multiple statement if * add explicit link to badges * remove duplicate line Signed-off-by: Krishna Vedala <7001608+kvedala@users.noreply.github.com> * remove namespace indentation * remove file associations in settings * add author name * enable cmake in subfolders of data_structures * create and link object file * cpp lint fixes and instantiate template classes * cpp lint fixes and instantiate template classes Signed-off-by: Krishna Vedala <7001608+kvedala@users.noreply.github.com> * cpplint - ignore `build/include` Signed-off-by: Krishna Vedala <7001608+kvedala@users.noreply.github.com> * disable redundant gcc compilation in cpplint workflow Signed-off-by: Krishna Vedala <7001608+kvedala@users.noreply.github.com> * template header files contain function codes as well and removed redundant subfolders Signed-off-by: Krishna Vedala <7001608+kvedala@users.noreply.github.com> * updating DIRECTORY.md * remove semicolons after functions in a class Signed-off-by: Krishna Vedala <7001608+kvedala@users.noreply.github.com> * cpplint header guard style Signed-off-by: Krishna Vedala <7001608+kvedala@users.noreply.github.com> * remove semilon Signed-off-by: Krishna Vedala <7001608+kvedala@users.noreply.github.com> * added LU decomposition algorithm Signed-off-by: Krishna Vedala <7001608+kvedala@users.noreply.github.com> * added QR decomposition algorithm Signed-off-by: Krishna Vedala <7001608+kvedala@users.noreply.github.com> * use QR decomposition to find eigen values Signed-off-by: Krishna Vedala <7001608+kvedala@users.noreply.github.com> * updating DIRECTORY.md * use std::rand for thread safety Signed-off-by: Krishna Vedala <7001608+kvedala@users.noreply.github.com> * move srand to main() Signed-off-by: Krishna Vedala <7001608+kvedala@users.noreply.github.com> * cpplint braces correction Signed-off-by: Krishna Vedala <7001608+kvedala@users.noreply.github.com> * updated eigen value documentation Signed-off-by: Krishna Vedala <7001608+kvedala@users.noreply.github.com> * fix matrix shift doc Signed-off-by: Krishna Vedala <7001608+kvedala@users.noreply.github.com> * rename CONTRIBUTION.md to CONTRIBUTING.md #836 * remove 'sort alphabetical order' check * added documentation check * remove extra paranthesis * added gitpod * added gitpod link from README * attempt to add vscode gitpod extensions * update gitpod extensions * add gitpod extensions cmake-tools and git-graph * remove gitpod init and add commands * use init to one time install doxygen, graphviz, cpplint * use gitpod dockerfile * add ninja build system to docker * remove configure task * add github prebuild specs to gitpod * disable gitpod addcommit * update documentation for kohonen_som * added ode solve using forward euler method * added mid-point euler ode solver * fixed itegration step equation * added semi-implicit euler ODE solver * updating DIRECTORY.md * fix cpplint issues - lines 117 and 124 * added documentation to ode group * corrected semi-implicit euler function * updated docs and test cases better structure * replace `free` with `delete` operator * formatting source-code forf55ab50cf2* updating DIRECTORY.md * main function must return * added machine learning group * added kohonen som topology algorithm * fix graph image path * updating DIRECTORY.md * fix braces * use snprintf instead of sprintf * use static_cast * hardcode character buffer size * fix machine learning groups in documentation * fix missing namespace function * replace kvedala fork references to TheAlgorithms * fix bug in counting_sort Co-authored-by: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Co-authored-by: Anmol3299 <mittalanmol22@gmail.com>
This commit is contained in:
20
data_structures/CMakeLists.txt
Normal file
20
data_structures/CMakeLists.txt
Normal file
@@ -0,0 +1,20 @@
|
||||
# If necessary, use the RELATIVE flag, otherwise each source file may be listed
|
||||
# with full pathname. RELATIVE may makes it easier to extract an executable name
|
||||
# automatically.
|
||||
file( GLOB APP_SOURCES RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.cpp )
|
||||
# file( GLOB APP_SOURCES ${CMAKE_SOURCE_DIR}/*.c )
|
||||
# AUX_SOURCE_DIRECTORY(${CMAKE_CURRENT_SOURCE_DIR} APP_SOURCES)
|
||||
foreach( testsourcefile ${APP_SOURCES} )
|
||||
# I used a simple string replace, to cut off .cpp.
|
||||
string( REPLACE ".cpp" "" testname ${testsourcefile} )
|
||||
add_executable( ${testname} ${testsourcefile} )
|
||||
|
||||
set_target_properties(${testname} PROPERTIES LINKER_LANGUAGE CXX)
|
||||
if(OpenMP_CXX_FOUND)
|
||||
target_link_libraries(${testname} OpenMP::OpenMP_CXX)
|
||||
endif()
|
||||
install(TARGETS ${testname} DESTINATION "bin/data_structures")
|
||||
|
||||
endforeach( testsourcefile ${APP_SOURCES} )
|
||||
|
||||
add_subdirectory(cll)
|
||||
148
data_structures/avltree.cpp
Normal file
148
data_structures/avltree.cpp
Normal file
@@ -0,0 +1,148 @@
|
||||
/**
|
||||
* \file
|
||||
* \brief A simple tree implementation using nodes
|
||||
*
|
||||
* \todo update code to use C++ STL library features and OO structure
|
||||
* \warning This program is a poor implementation and does not utilize any of
|
||||
* the C++ STL features.
|
||||
*/
|
||||
#include <algorithm>
|
||||
#include <iostream>
|
||||
#include <queue>
|
||||
|
||||
typedef struct node {
|
||||
int data;
|
||||
int height;
|
||||
struct node *left;
|
||||
struct node *right;
|
||||
} node;
|
||||
|
||||
/** Create and return a new Node */
|
||||
node *createNode(int data) {
|
||||
node *nn = new node();
|
||||
nn->data = data;
|
||||
nn->height = 0;
|
||||
nn->left = NULL;
|
||||
nn->right = NULL;
|
||||
return nn;
|
||||
}
|
||||
|
||||
/** Returns height of tree */
|
||||
int height(node *root) {
|
||||
if (root == NULL)
|
||||
return 0;
|
||||
return 1 + std::max(height(root->left), height(root->right));
|
||||
}
|
||||
|
||||
/** Returns difference between height of left and right subtree */
|
||||
int getBalance(node *root) { return height(root->left) - height(root->right); }
|
||||
|
||||
/** Returns Node after Right Rotation */
|
||||
node *rightRotate(node *root) {
|
||||
node *t = root->left;
|
||||
node *u = t->right;
|
||||
t->right = root;
|
||||
root->left = u;
|
||||
return t;
|
||||
}
|
||||
|
||||
/** Returns Node after Left Rotation */
|
||||
node *leftRotate(node *root) {
|
||||
node *t = root->right;
|
||||
node *u = t->left;
|
||||
t->left = root;
|
||||
root->right = u;
|
||||
return t;
|
||||
}
|
||||
|
||||
/** Returns node with minimum value in the tree */
|
||||
node *minValue(node *root) {
|
||||
if (root->left == NULL)
|
||||
return root;
|
||||
return minValue(root->left);
|
||||
}
|
||||
|
||||
/** Balanced Insertion */
|
||||
node *insert(node *root, int item) {
|
||||
node *nn = createNode(item);
|
||||
if (root == NULL)
|
||||
return nn;
|
||||
if (item < root->data)
|
||||
root->left = insert(root->left, item);
|
||||
else
|
||||
root->right = insert(root->right, item);
|
||||
int b = getBalance(root);
|
||||
if (b > 1) {
|
||||
if (getBalance(root->left) < 0)
|
||||
root->left = leftRotate(root->left); // Left-Right Case
|
||||
return rightRotate(root); // Left-Left Case
|
||||
} else if (b < -1) {
|
||||
if (getBalance(root->right) > 0)
|
||||
root->right = rightRotate(root->right); // Right-Left Case
|
||||
return leftRotate(root); // Right-Right Case
|
||||
}
|
||||
return root;
|
||||
}
|
||||
|
||||
/** Balanced Deletion */
|
||||
node *deleteNode(node *root, int key) {
|
||||
if (root == NULL)
|
||||
return root;
|
||||
if (key < root->data)
|
||||
root->left = deleteNode(root->left, key);
|
||||
else if (key > root->data)
|
||||
root->right = deleteNode(root->right, key);
|
||||
|
||||
else {
|
||||
// Node to be deleted is leaf node or have only one Child
|
||||
if (!root->right) {
|
||||
node *temp = root->left;
|
||||
delete (root);
|
||||
root = NULL;
|
||||
return temp;
|
||||
} else if (!root->left) {
|
||||
node *temp = root->right;
|
||||
delete (root);
|
||||
root = NULL;
|
||||
return temp;
|
||||
}
|
||||
// Node to be deleted have both left and right subtrees
|
||||
node *temp = minValue(root->right);
|
||||
root->data = temp->data;
|
||||
root->right = deleteNode(root->right, temp->data);
|
||||
}
|
||||
// Balancing Tree after deletion
|
||||
return root;
|
||||
}
|
||||
|
||||
/** LevelOrder (Breadth First Search) */
|
||||
void levelOrder(node *root) {
|
||||
std::queue<node *> q;
|
||||
q.push(root);
|
||||
while (!q.empty()) {
|
||||
root = q.front();
|
||||
std::cout << root->data << " ";
|
||||
q.pop();
|
||||
if (root->left)
|
||||
q.push(root->left);
|
||||
if (root->right)
|
||||
q.push(root->right);
|
||||
}
|
||||
}
|
||||
|
||||
/** Main function */
|
||||
int main() {
|
||||
// Testing AVL Tree
|
||||
node *root = NULL;
|
||||
int i;
|
||||
for (i = 1; i <= 7; i++) root = insert(root, i);
|
||||
std::cout << "LevelOrder: ";
|
||||
levelOrder(root);
|
||||
root = deleteNode(root, 1); // Deleting key with value 1
|
||||
std::cout << "\nLevelOrder: ";
|
||||
levelOrder(root);
|
||||
root = deleteNode(root, 4); // Deletin key with value 4
|
||||
std::cout << "\nLevelOrder: ";
|
||||
levelOrder(root);
|
||||
return 0;
|
||||
}
|
||||
174
data_structures/binary_search_tree.cpp
Normal file
174
data_structures/binary_search_tree.cpp
Normal file
@@ -0,0 +1,174 @@
|
||||
/**
|
||||
* \file
|
||||
* \brief A simple tree implementation using structured nodes
|
||||
*
|
||||
* \todo update code to use C++ STL library features and OO structure
|
||||
* \warning This program is a poor implementation - C style - and does not
|
||||
* utilize any of the C++ STL features.
|
||||
*/
|
||||
#include <iostream>
|
||||
|
||||
struct node {
|
||||
int val;
|
||||
node *left;
|
||||
node *right;
|
||||
};
|
||||
|
||||
struct queue {
|
||||
node *t[100];
|
||||
int front;
|
||||
int rear;
|
||||
};
|
||||
|
||||
queue q;
|
||||
|
||||
void enqueue(node *n) { q.t[q.rear++] = n; }
|
||||
|
||||
node *dequeue() { return (q.t[q.front++]); }
|
||||
|
||||
void Insert(node *n, int x) {
|
||||
if (x < n->val) {
|
||||
if (n->left == NULL) {
|
||||
node *temp = new node;
|
||||
temp->val = x;
|
||||
temp->left = NULL;
|
||||
temp->right = NULL;
|
||||
n->left = temp;
|
||||
} else {
|
||||
Insert(n->left, x);
|
||||
}
|
||||
} else {
|
||||
if (n->right == NULL) {
|
||||
node *temp = new node;
|
||||
temp->val = x;
|
||||
temp->left = NULL;
|
||||
temp->right = NULL;
|
||||
n->left = temp;
|
||||
} else {
|
||||
Insert(n->right, x);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
int findMaxInLeftST(node *n) {
|
||||
while (n->right != NULL) {
|
||||
n = n->right;
|
||||
}
|
||||
return n->val;
|
||||
}
|
||||
|
||||
void Remove(node *p, node *n, int x) {
|
||||
if (n->val == x) {
|
||||
if (n->right == NULL && n->left == NULL) {
|
||||
if (x < p->val) {
|
||||
p->right = NULL;
|
||||
} else {
|
||||
p->left = NULL;
|
||||
}
|
||||
} else if (n->right == NULL) {
|
||||
if (x < p->val) {
|
||||
p->right = n->left;
|
||||
} else {
|
||||
p->left = n->left;
|
||||
}
|
||||
} else if (n->left == NULL) {
|
||||
if (x < p->val) {
|
||||
p->right = n->right;
|
||||
} else {
|
||||
p->left = n->right;
|
||||
}
|
||||
} else {
|
||||
int y = findMaxInLeftST(n->left);
|
||||
n->val = y;
|
||||
Remove(n, n->right, y);
|
||||
}
|
||||
} else if (x < n->val) {
|
||||
Remove(n, n->left, x);
|
||||
} else {
|
||||
Remove(n, n->right, x);
|
||||
}
|
||||
}
|
||||
|
||||
void BFT(node *n) {
|
||||
if (n != NULL) {
|
||||
std::cout << n->val << " ";
|
||||
enqueue(n->left);
|
||||
enqueue(n->right);
|
||||
BFT(dequeue());
|
||||
}
|
||||
}
|
||||
|
||||
void Pre(node *n) {
|
||||
if (n != NULL) {
|
||||
std::cout << n->val << " ";
|
||||
Pre(n->left);
|
||||
Pre(n->right);
|
||||
}
|
||||
}
|
||||
|
||||
void In(node *n) {
|
||||
if (n != NULL) {
|
||||
In(n->left);
|
||||
std::cout << n->val << " ";
|
||||
In(n->right);
|
||||
}
|
||||
}
|
||||
|
||||
void Post(node *n) {
|
||||
if (n != NULL) {
|
||||
Post(n->left);
|
||||
Post(n->right);
|
||||
std::cout << n->val << " ";
|
||||
}
|
||||
}
|
||||
|
||||
int main() {
|
||||
q.front = 0;
|
||||
q.rear = 0;
|
||||
int value;
|
||||
int ch;
|
||||
node *root = new node;
|
||||
std::cout << "\nEnter the value of root node :";
|
||||
std::cin >> value;
|
||||
root->val = value;
|
||||
root->left = NULL;
|
||||
root->right = NULL;
|
||||
do {
|
||||
std::cout << "\n1. Insert"
|
||||
<< "\n2. Delete"
|
||||
<< "\n3. Breadth First"
|
||||
<< "\n4. Preorder Depth First"
|
||||
<< "\n5. Inorder Depth First"
|
||||
<< "\n6. Postorder Depth First";
|
||||
|
||||
std::cout << "\nEnter Your Choice : ";
|
||||
std::cin >> ch;
|
||||
int x;
|
||||
switch (ch) {
|
||||
case 1:
|
||||
std::cout << "\nEnter the value to be Inserted : ";
|
||||
std::cin >> x;
|
||||
Insert(root, x);
|
||||
break;
|
||||
case 2:
|
||||
std::cout << "\nEnter the value to be Deleted : ";
|
||||
std::cin >> x;
|
||||
Remove(root, root, x);
|
||||
break;
|
||||
case 3:
|
||||
BFT(root);
|
||||
break;
|
||||
case 4:
|
||||
Pre(root);
|
||||
break;
|
||||
case 5:
|
||||
In(root);
|
||||
break;
|
||||
case 6:
|
||||
Post(root);
|
||||
break;
|
||||
}
|
||||
} while (ch != 0);
|
||||
|
||||
return 0;
|
||||
}
|
||||
144
data_structures/binaryheap.cpp
Normal file
144
data_structures/binaryheap.cpp
Normal file
@@ -0,0 +1,144 @@
|
||||
/**
|
||||
* \file
|
||||
* \brief A C++ program to demonstrate common Binary Heap Operations
|
||||
*/
|
||||
#include <climits>
|
||||
#include <iostream>
|
||||
#include <utility>
|
||||
|
||||
/** A class for Min Heap */
|
||||
class MinHeap {
|
||||
int *harr; ///< pointer to array of elements in heap
|
||||
int capacity; ///< maximum possible size of min heap
|
||||
int heap_size; ///< Current number of elements in min heap
|
||||
|
||||
public:
|
||||
/** Constructor
|
||||
* \param[in] capacity initial heap capacity
|
||||
*/
|
||||
MinHeap(int capacity);
|
||||
|
||||
/** to heapify a subtree with the root at given index
|
||||
*/
|
||||
void MinHeapify(int);
|
||||
|
||||
int parent(int i) { return (i - 1) / 2; }
|
||||
|
||||
/** to get index of left child of node at index i */
|
||||
int left(int i) { return (2 * i + 1); }
|
||||
|
||||
/** to get index of right child of node at index i */
|
||||
int right(int i) { return (2 * i + 2); }
|
||||
|
||||
/** to extract the root which is the minimum element */
|
||||
int extractMin();
|
||||
|
||||
/** Decreases key value of key at index i to new_val */
|
||||
void decreaseKey(int i, int new_val);
|
||||
|
||||
/** Returns the minimum key (key at root) from min heap */
|
||||
int getMin() { return harr[0]; }
|
||||
|
||||
/** Deletes a key stored at index i */
|
||||
void deleteKey(int i);
|
||||
|
||||
/** Inserts a new key 'k' */
|
||||
void insertKey(int k);
|
||||
};
|
||||
|
||||
/** Constructor: Builds a heap from a given array a[] of given size */
|
||||
MinHeap::MinHeap(int cap) {
|
||||
heap_size = 0;
|
||||
capacity = cap;
|
||||
harr = new int[cap];
|
||||
}
|
||||
|
||||
// Inserts a new key 'k'
|
||||
void MinHeap::insertKey(int k) {
|
||||
if (heap_size == capacity) {
|
||||
std::cout << "\nOverflow: Could not insertKey\n";
|
||||
return;
|
||||
}
|
||||
|
||||
// First insert the new key at the end
|
||||
heap_size++;
|
||||
int i = heap_size - 1;
|
||||
harr[i] = k;
|
||||
|
||||
// Fix the min heap property if it is violated
|
||||
while (i != 0 && harr[parent(i)] > harr[i]) {
|
||||
std::swap(harr[i], harr[parent(i)]);
|
||||
i = parent(i);
|
||||
}
|
||||
}
|
||||
|
||||
/** Decreases value of key at index 'i' to new_val. It is assumed that new_val
|
||||
* is smaller than harr[i].
|
||||
*/
|
||||
void MinHeap::decreaseKey(int i, int new_val) {
|
||||
harr[i] = new_val;
|
||||
while (i != 0 && harr[parent(i)] > harr[i]) {
|
||||
std::swap(harr[i], harr[parent(i)]);
|
||||
i = parent(i);
|
||||
}
|
||||
}
|
||||
|
||||
// Method to remove minimum element (or root) from min heap
|
||||
int MinHeap::extractMin() {
|
||||
if (heap_size <= 0)
|
||||
return INT_MAX;
|
||||
if (heap_size == 1) {
|
||||
heap_size--;
|
||||
return harr[0];
|
||||
}
|
||||
|
||||
// Store the minimum value, and remove it from heap
|
||||
int root = harr[0];
|
||||
harr[0] = harr[heap_size - 1];
|
||||
heap_size--;
|
||||
MinHeapify(0);
|
||||
|
||||
return root;
|
||||
}
|
||||
|
||||
/** This function deletes key at index i. It first reduced value to minus
|
||||
* infinite, then calls extractMin()
|
||||
*/
|
||||
void MinHeap::deleteKey(int i) {
|
||||
decreaseKey(i, INT_MIN);
|
||||
extractMin();
|
||||
}
|
||||
|
||||
/** A recursive method to heapify a subtree with the root at given index
|
||||
* This method assumes that the subtrees are already heapified
|
||||
*/
|
||||
void MinHeap::MinHeapify(int i) {
|
||||
int l = left(i);
|
||||
int r = right(i);
|
||||
int smallest = i;
|
||||
if (l < heap_size && harr[l] < harr[i])
|
||||
smallest = l;
|
||||
if (r < heap_size && harr[r] < harr[smallest])
|
||||
smallest = r;
|
||||
if (smallest != i) {
|
||||
std::swap(harr[i], harr[smallest]);
|
||||
MinHeapify(smallest);
|
||||
}
|
||||
}
|
||||
|
||||
// Driver program to test above functions
|
||||
int main() {
|
||||
MinHeap h(11);
|
||||
h.insertKey(3);
|
||||
h.insertKey(2);
|
||||
h.deleteKey(1);
|
||||
h.insertKey(15);
|
||||
h.insertKey(5);
|
||||
h.insertKey(4);
|
||||
h.insertKey(45);
|
||||
std::cout << h.extractMin() << " ";
|
||||
std::cout << h.getMin() << " ";
|
||||
h.decreaseKey(2, 1);
|
||||
std::cout << h.getMin();
|
||||
return 0;
|
||||
}
|
||||
69
data_structures/circular_queue_using_linked_list.cpp
Normal file
69
data_structures/circular_queue_using_linked_list.cpp
Normal file
@@ -0,0 +1,69 @@
|
||||
#include <iostream>
|
||||
|
||||
struct node {
|
||||
int data;
|
||||
struct node *next;
|
||||
};
|
||||
class Queue {
|
||||
node *front;
|
||||
node *rear;
|
||||
|
||||
public:
|
||||
Queue() {
|
||||
front = NULL;
|
||||
rear = NULL;
|
||||
}
|
||||
void createNode(int val) {
|
||||
node *ptr;
|
||||
node *nn;
|
||||
nn = new node;
|
||||
ptr = front;
|
||||
nn->data = val;
|
||||
nn->next = NULL;
|
||||
front = nn;
|
||||
rear = nn;
|
||||
}
|
||||
void enqueue(int val) {
|
||||
if (front == NULL || rear == NULL) {
|
||||
createNode(val);
|
||||
} else {
|
||||
node *ptr;
|
||||
node *nn;
|
||||
ptr = front;
|
||||
nn = new node;
|
||||
nn->data = val;
|
||||
rear->next = nn;
|
||||
nn->next = front;
|
||||
rear = nn;
|
||||
}
|
||||
}
|
||||
void dequeue() {
|
||||
node *n;
|
||||
n = front;
|
||||
front = front->next;
|
||||
delete (n);
|
||||
}
|
||||
void traverse() {
|
||||
node *ptr;
|
||||
ptr = front;
|
||||
do {
|
||||
std::cout << ptr->data << " ";
|
||||
ptr = ptr->next;
|
||||
} while (ptr != rear->next);
|
||||
std::cout << front->data << std::endl;
|
||||
}
|
||||
};
|
||||
int main(void) {
|
||||
Queue q;
|
||||
q.enqueue(10);
|
||||
q.enqueue(20);
|
||||
q.enqueue(30);
|
||||
q.enqueue(40);
|
||||
q.enqueue(50);
|
||||
q.enqueue(60);
|
||||
q.enqueue(70);
|
||||
q.traverse();
|
||||
q.dequeue();
|
||||
q.traverse();
|
||||
return 0;
|
||||
}
|
||||
5
data_structures/cll/CMakeLists.txt
Normal file
5
data_structures/cll/CMakeLists.txt
Normal file
@@ -0,0 +1,5 @@
|
||||
add_executable( cll
|
||||
cll.cpp
|
||||
main_cll.cpp
|
||||
)
|
||||
install(TARGETS cll DESTINATION "bin/data_structures")
|
||||
110
data_structures/cll/cll.cpp
Normal file
110
data_structures/cll/cll.cpp
Normal file
@@ -0,0 +1,110 @@
|
||||
/*
|
||||
A simple class for Cicular Linear Linked List
|
||||
*/
|
||||
#include "cll.h"
|
||||
using namespace std;
|
||||
|
||||
/* Constructor */
|
||||
cll::cll() {
|
||||
head = NULL;
|
||||
total = 0;
|
||||
}
|
||||
|
||||
cll::~cll() { /* Desstructure, no need to fill */
|
||||
}
|
||||
|
||||
/* Display a list. and total element */
|
||||
void cll::display() {
|
||||
if (head == NULL)
|
||||
cout << "List is empty !" << endl;
|
||||
else {
|
||||
cout << "CLL list: ";
|
||||
node *current = head;
|
||||
for (int i = 0; i < total; i++) {
|
||||
cout << current->data << " -> ";
|
||||
current = current->next;
|
||||
}
|
||||
cout << head->data << endl;
|
||||
cout << "Total element: " << total << endl;
|
||||
}
|
||||
}
|
||||
|
||||
/* List insert a new value at head in list */
|
||||
void cll::insert_front(int new_data) {
|
||||
node *newNode;
|
||||
newNode = new node;
|
||||
newNode->data = new_data;
|
||||
newNode->next = NULL;
|
||||
if (head == NULL) {
|
||||
head = newNode;
|
||||
head->next = head;
|
||||
} else {
|
||||
node *current = head;
|
||||
while (current->next != head) {
|
||||
current = current->next;
|
||||
}
|
||||
newNode->next = head;
|
||||
current->next = newNode;
|
||||
head = newNode;
|
||||
}
|
||||
total++;
|
||||
}
|
||||
|
||||
/* List insert a new value at head in list */
|
||||
void cll::insert_tail(int new_data) {
|
||||
node *newNode;
|
||||
newNode = new node;
|
||||
newNode->data = new_data;
|
||||
newNode->next = NULL;
|
||||
if (head == NULL) {
|
||||
head = newNode;
|
||||
head->next = head;
|
||||
} else {
|
||||
node *current = head;
|
||||
while (current->next != head) {
|
||||
current = current->next;
|
||||
}
|
||||
current->next = newNode;
|
||||
newNode->next = head;
|
||||
}
|
||||
total++;
|
||||
}
|
||||
|
||||
/* Get total element in list */
|
||||
int cll::get_size() { return total; }
|
||||
|
||||
/* Return true if the requested item (sent in as an argument)
|
||||
is in the list, otherwise return false */
|
||||
bool cll::find_item(int item_to_find) {
|
||||
if (head == NULL) {
|
||||
cout << "List is empty !" << endl;
|
||||
return false;
|
||||
} else {
|
||||
node *current = head;
|
||||
while (current->next != head) {
|
||||
if (current->data == item_to_find)
|
||||
return true;
|
||||
current = current->next;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/* Overloading method*/
|
||||
int cll::operator*() { return head->data; }
|
||||
|
||||
/* Overload the pre-increment operator.
|
||||
The iterator is advanced to the next node. */
|
||||
void cll::operator++() {
|
||||
if (head == NULL) {
|
||||
cout << "List is empty !" << endl;
|
||||
} else {
|
||||
node *current = head;
|
||||
while (current->next != head) {
|
||||
current = current->next;
|
||||
}
|
||||
current->next = head->next;
|
||||
head = head->next;
|
||||
}
|
||||
total--;
|
||||
}
|
||||
43
data_structures/cll/cll.h
Normal file
43
data_structures/cll/cll.h
Normal file
@@ -0,0 +1,43 @@
|
||||
/*
|
||||
* Simple data structure CLL (Cicular Linear Linked List)
|
||||
* */
|
||||
#include <cctype>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <iostream>
|
||||
|
||||
#ifndef CLL_H
|
||||
#define CLL_H
|
||||
/*The data structure is a linear linked list of integers */
|
||||
struct node {
|
||||
int data;
|
||||
node* next;
|
||||
};
|
||||
|
||||
class cll {
|
||||
public:
|
||||
cll(); /* Construct without parameter */
|
||||
~cll();
|
||||
void display(); /* Show the list */
|
||||
|
||||
/******************************************************
|
||||
* Useful method for list
|
||||
*******************************************************/
|
||||
void insert_front(int new_data); /* Insert a new value at head */
|
||||
void insert_tail(int new_data); /* Insert a new value at tail */
|
||||
int get_size(); /* Get total element in list */
|
||||
bool find_item(int item_to_find); /* Find an item in list */
|
||||
|
||||
/******************************************************
|
||||
* Overloading method for list
|
||||
*******************************************************/
|
||||
int operator*(); /* Returns the info contained in head */
|
||||
/* Overload the pre-increment operator.
|
||||
The iterator is advanced to the next node. */
|
||||
void operator++();
|
||||
|
||||
protected:
|
||||
node* head;
|
||||
int total; /* Total element in a list */
|
||||
};
|
||||
#endif
|
||||
43
data_structures/cll/main_cll.cpp
Normal file
43
data_structures/cll/main_cll.cpp
Normal file
@@ -0,0 +1,43 @@
|
||||
#include "cll.h"
|
||||
using namespace std;
|
||||
|
||||
int main() {
|
||||
/* Test CLL */
|
||||
cout << "----------- Test construct -----------" << endl;
|
||||
cll list1;
|
||||
list1.display();
|
||||
cout << "----------- Test insert front -----------" << endl;
|
||||
list1.insert_front(5);
|
||||
cout << "After insert 5 at front: " << endl;
|
||||
list1.display();
|
||||
cout << "After insert 10 3 7 at front: " << endl;
|
||||
list1.insert_front(10);
|
||||
list1.insert_front(3);
|
||||
list1.insert_front(7);
|
||||
list1.display();
|
||||
cout << "----------- Test insert tail -----------" << endl;
|
||||
cout << "After insert 18 19 20 at tail: " << endl;
|
||||
list1.insert_tail(18);
|
||||
list1.insert_tail(19);
|
||||
list1.insert_tail(20);
|
||||
list1.display();
|
||||
cout << "----------- Test find item -----------" << endl;
|
||||
if (list1.find_item(10))
|
||||
cout << "PASS" << endl;
|
||||
else
|
||||
cout << "FAIL" << endl;
|
||||
if (!list1.find_item(30))
|
||||
cout << "PASS" << endl;
|
||||
else
|
||||
cout << "FAIL" << endl;
|
||||
cout << "----------- Test * operator -----------" << endl;
|
||||
int value = *list1;
|
||||
cout << "Value at *list1: " << value << endl;
|
||||
cout << "----------- Test ++ operator -----------" << endl;
|
||||
list1.display();
|
||||
++list1;
|
||||
cout << "After ++list1: " << endl;
|
||||
list1.display();
|
||||
|
||||
return 0;
|
||||
}
|
||||
62
data_structures/disjoint_set.cpp
Normal file
62
data_structures/disjoint_set.cpp
Normal file
@@ -0,0 +1,62 @@
|
||||
#include <iostream>
|
||||
#include <vector>
|
||||
|
||||
using std::cout;
|
||||
using std::endl;
|
||||
using std::vector;
|
||||
|
||||
vector<int> root, rnk;
|
||||
|
||||
void CreateSet(int n) {
|
||||
root = vector<int>(n + 1);
|
||||
rnk = vector<int>(n + 1, 1);
|
||||
for (int i = 1; i <= n; ++i) {
|
||||
root[i] = i;
|
||||
}
|
||||
}
|
||||
|
||||
int Find(int x) {
|
||||
if (root[x] == x) {
|
||||
return x;
|
||||
}
|
||||
return root[x] = Find(root[x]);
|
||||
}
|
||||
|
||||
bool InSameUnion(int x, int y) { return Find(x) == Find(y); }
|
||||
|
||||
void Union(int x, int y) {
|
||||
int a = Find(x), b = Find(y);
|
||||
if (a != b) {
|
||||
if (rnk[a] < rnk[b]) {
|
||||
root[a] = b;
|
||||
} else if (rnk[a] > rnk[b]) {
|
||||
root[b] = a;
|
||||
} else {
|
||||
root[a] = b;
|
||||
++rnk[b];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
int main() {
|
||||
// tests CreateSet & Find
|
||||
int n = 100;
|
||||
CreateSet(n);
|
||||
for (int i = 1; i <= 100; ++i) {
|
||||
if (root[i] != i) {
|
||||
cout << "Fail" << endl;
|
||||
break;
|
||||
}
|
||||
}
|
||||
// tests InSameUnion & Union
|
||||
cout << "1 and 2 are initially not in the same subset" << endl;
|
||||
if (InSameUnion(1, 2)) {
|
||||
cout << "Fail" << endl;
|
||||
}
|
||||
Union(1, 2);
|
||||
cout << "1 and 2 are now in the same subset" << endl;
|
||||
if (!InSameUnion(1, 2)) {
|
||||
cout << "Fail" << endl;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
136
data_structures/doubly_linked_list.cpp
Normal file
136
data_structures/doubly_linked_list.cpp
Normal file
@@ -0,0 +1,136 @@
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <iostream>
|
||||
|
||||
struct node {
|
||||
int val;
|
||||
node *prev;
|
||||
node *next;
|
||||
} * start;
|
||||
|
||||
class double_linked_list {
|
||||
public:
|
||||
double_linked_list() { start = NULL; }
|
||||
void insert(int x);
|
||||
void remove(int x);
|
||||
void search(int x);
|
||||
void show();
|
||||
void reverseShow();
|
||||
};
|
||||
|
||||
void double_linked_list::insert(int x) {
|
||||
node *t = start;
|
||||
if (start != NULL) {
|
||||
while (t->next != NULL) {
|
||||
t = t->next;
|
||||
}
|
||||
node *n = new node;
|
||||
t->next = n;
|
||||
n->prev = t;
|
||||
n->val = x;
|
||||
n->next = NULL;
|
||||
} else {
|
||||
node *n = new node;
|
||||
n->val = x;
|
||||
n->prev = NULL;
|
||||
n->next = NULL;
|
||||
start = n;
|
||||
}
|
||||
}
|
||||
|
||||
void double_linked_list::remove(int x) {
|
||||
node *t = start;
|
||||
while (t != NULL && t->val != x) {
|
||||
t = t->next;
|
||||
}
|
||||
if (t == NULL) {
|
||||
return;
|
||||
}
|
||||
if (t->prev == NULL) {
|
||||
if (t->next == NULL) {
|
||||
start = NULL;
|
||||
} else {
|
||||
start = t->next;
|
||||
start->prev = NULL;
|
||||
}
|
||||
} else if (t->next == NULL) {
|
||||
t->prev->next = NULL;
|
||||
} else {
|
||||
t->prev->next = t->next;
|
||||
t->next->prev = t->prev;
|
||||
}
|
||||
delete t;
|
||||
}
|
||||
|
||||
void double_linked_list::search(int x) {
|
||||
node *t = start;
|
||||
int found = 0;
|
||||
while (t != NULL) {
|
||||
if (t->val == x) {
|
||||
std::cout << "\nFound";
|
||||
found = 1;
|
||||
break;
|
||||
}
|
||||
t = t->next;
|
||||
}
|
||||
if (found == 0) {
|
||||
std::cout << "\nNot Found";
|
||||
}
|
||||
}
|
||||
|
||||
void double_linked_list::show() {
|
||||
node *t = start;
|
||||
while (t != NULL) {
|
||||
std::cout << t->val << "\t";
|
||||
t = t->next;
|
||||
}
|
||||
}
|
||||
|
||||
void double_linked_list::reverseShow() {
|
||||
node *t = start;
|
||||
while (t != NULL && t->next != NULL) {
|
||||
t = t->next;
|
||||
}
|
||||
while (t != NULL) {
|
||||
std::cout << t->val << "\t";
|
||||
t = t->prev;
|
||||
}
|
||||
}
|
||||
|
||||
int main() {
|
||||
int choice, x;
|
||||
double_linked_list ob;
|
||||
do {
|
||||
std::cout << "\n1. Insert";
|
||||
std::cout << "\n2. Delete";
|
||||
std::cout << "\n3. Search";
|
||||
std::cout << "\n4. Forward print";
|
||||
std::cout << "\n5. Reverse print";
|
||||
std::cout << "\n\nEnter you choice : ";
|
||||
std::cin >> choice;
|
||||
switch (choice) {
|
||||
case 1:
|
||||
std::cout << "\nEnter the element to be inserted : ";
|
||||
std::cin >> x;
|
||||
ob.insert(x);
|
||||
break;
|
||||
case 2:
|
||||
std::cout << "\nEnter the element to be removed : ";
|
||||
std::cin >> x;
|
||||
ob.remove(x);
|
||||
break;
|
||||
case 3:
|
||||
std::cout << "\nEnter the element to be searched : ";
|
||||
std::cin >> x;
|
||||
ob.search(x);
|
||||
break;
|
||||
case 4:
|
||||
ob.show();
|
||||
break;
|
||||
case 5:
|
||||
ob.reverseShow();
|
||||
break;
|
||||
}
|
||||
} while (choice != 0);
|
||||
return 0;
|
||||
}
|
||||
134
data_structures/linked_list.cpp
Normal file
134
data_structures/linked_list.cpp
Normal file
@@ -0,0 +1,134 @@
|
||||
#include <iostream>
|
||||
|
||||
struct node {
|
||||
int val;
|
||||
node *next;
|
||||
};
|
||||
|
||||
node *start;
|
||||
|
||||
void insert(int x) {
|
||||
node *t = start;
|
||||
node *n = new node;
|
||||
n->val = x;
|
||||
n->next = NULL;
|
||||
if (start != NULL) {
|
||||
while (t->next != NULL) {
|
||||
t = t->next;
|
||||
}
|
||||
t->next = n;
|
||||
} else {
|
||||
start = n;
|
||||
}
|
||||
}
|
||||
|
||||
void remove(int x) {
|
||||
if (start == NULL) {
|
||||
std::cout << "\nLinked List is empty\n";
|
||||
return;
|
||||
} else if (start->val == x) {
|
||||
node *temp = start;
|
||||
start = start->next;
|
||||
delete temp;
|
||||
return;
|
||||
}
|
||||
|
||||
node *temp = start, *parent = start;
|
||||
|
||||
while (temp != NULL && temp->val != x) {
|
||||
parent = temp;
|
||||
temp = temp->next;
|
||||
}
|
||||
|
||||
if (temp == NULL) {
|
||||
std::cout << std::endl << x << " not found in list\n";
|
||||
return;
|
||||
}
|
||||
|
||||
parent->next = temp->next;
|
||||
delete temp;
|
||||
}
|
||||
|
||||
void search(int x) {
|
||||
node *t = start;
|
||||
int found = 0;
|
||||
while (t != NULL) {
|
||||
if (t->val == x) {
|
||||
std::cout << "\nFound";
|
||||
found = 1;
|
||||
break;
|
||||
}
|
||||
t = t->next;
|
||||
}
|
||||
if (found == 0) {
|
||||
std::cout << "\nNot Found";
|
||||
}
|
||||
}
|
||||
|
||||
void show() {
|
||||
node *t = start;
|
||||
while (t != NULL) {
|
||||
std::cout << t->val << "\t";
|
||||
t = t->next;
|
||||
}
|
||||
}
|
||||
|
||||
void reverse() {
|
||||
node *first = start;
|
||||
if (first != NULL) {
|
||||
node *second = first->next;
|
||||
while (second != NULL) {
|
||||
node *tem = second->next;
|
||||
second->next = first;
|
||||
first = second;
|
||||
second = tem;
|
||||
}
|
||||
start->next = NULL;
|
||||
start = first;
|
||||
} else {
|
||||
std::cout << "\nEmpty list";
|
||||
}
|
||||
}
|
||||
|
||||
int main() {
|
||||
int choice, x;
|
||||
do {
|
||||
std::cout << "\n1. Insert";
|
||||
std::cout << "\n2. Delete";
|
||||
std::cout << "\n3. Search";
|
||||
std::cout << "\n4. Print";
|
||||
std::cout << "\n5. Reverse";
|
||||
std::cout << "\n0. Exit";
|
||||
std::cout << "\n\nEnter you choice : ";
|
||||
std::cin >> choice;
|
||||
switch (choice) {
|
||||
case 1:
|
||||
std::cout << "\nEnter the element to be inserted : ";
|
||||
std::cin >> x;
|
||||
insert(x);
|
||||
break;
|
||||
case 2:
|
||||
std::cout << "\nEnter the element to be removed : ";
|
||||
std::cin >> x;
|
||||
remove(x);
|
||||
break;
|
||||
case 3:
|
||||
std::cout << "\nEnter the element to be searched : ";
|
||||
std::cin >> x;
|
||||
search(x);
|
||||
break;
|
||||
case 4:
|
||||
show();
|
||||
std::cout << "\n";
|
||||
break;
|
||||
case 5:
|
||||
std::cout << "The reversed list: \n";
|
||||
reverse();
|
||||
show();
|
||||
std::cout << "\n";
|
||||
break;
|
||||
}
|
||||
} while (choice != 0);
|
||||
|
||||
return 0;
|
||||
}
|
||||
114
data_structures/linkedlist_implentation_usingarray.cpp
Normal file
114
data_structures/linkedlist_implentation_usingarray.cpp
Normal file
@@ -0,0 +1,114 @@
|
||||
/**
|
||||
* \file
|
||||
* \brief Linked list implementation using Arrays
|
||||
*
|
||||
* The difference between the pointer implementation of linked list and array
|
||||
* implementation of linked list:
|
||||
* 1. The NULL is represented by -1;
|
||||
* 2. Limited size. (in the following case it is 100 nodes at max). But we can
|
||||
* reuse the nodes that are to be deleted by again linking it bacj to the list.
|
||||
*/
|
||||
|
||||
#include <iostream>
|
||||
|
||||
struct Node {
|
||||
int data;
|
||||
int next;
|
||||
};
|
||||
|
||||
Node AvailArray[100]; ///< array that will act as nodes of a linked list.
|
||||
|
||||
int head = -1;
|
||||
int avail = 0;
|
||||
void initialise_list() {
|
||||
for (int i = 0; i <= 98; i++) {
|
||||
AvailArray[i].next = i + 1;
|
||||
}
|
||||
AvailArray[99].next = -1; // indicating the end of the linked list.
|
||||
}
|
||||
|
||||
/** This will return the index of the first free node present in the avail list
|
||||
*/
|
||||
int getnode() {
|
||||
int NodeIndexToBeReturned = avail;
|
||||
avail = AvailArray[avail].next;
|
||||
return NodeIndexToBeReturned;
|
||||
}
|
||||
|
||||
/** This function when called will delete the node with
|
||||
* the index presented as an argument, and will put
|
||||
* back that node into the array.
|
||||
*/
|
||||
void freeNode(int nodeToBeDeleted) {
|
||||
AvailArray[nodeToBeDeleted].next = avail;
|
||||
avail = nodeToBeDeleted;
|
||||
}
|
||||
|
||||
/** The function will insert the given data
|
||||
* into the front of the linked list.
|
||||
*/
|
||||
void insertAtTheBeginning(int data) {
|
||||
int newNode = getnode();
|
||||
AvailArray[newNode].data = data;
|
||||
AvailArray[newNode].next = head;
|
||||
head = newNode;
|
||||
}
|
||||
|
||||
void insertAtTheEnd(int data) {
|
||||
int newNode = getnode();
|
||||
int temp = head;
|
||||
while (AvailArray[temp].next != -1) {
|
||||
temp = AvailArray[temp].next;
|
||||
}
|
||||
// temp is now pointing to the end node.
|
||||
AvailArray[newNode].data = data;
|
||||
AvailArray[newNode].next = -1;
|
||||
AvailArray[temp].next = newNode;
|
||||
}
|
||||
|
||||
void display() {
|
||||
int temp = head;
|
||||
while (temp != -1) {
|
||||
std::cout << AvailArray[temp].data << "->";
|
||||
temp = AvailArray[temp].next;
|
||||
}
|
||||
std::cout << "-1" << std::endl;
|
||||
}
|
||||
|
||||
/** Main function */
|
||||
int main() {
|
||||
initialise_list();
|
||||
int x, y, z;
|
||||
for (;;) {
|
||||
std::cout << "1. Insert At The Beginning" << std::endl;
|
||||
std::cout << "2. Insert At The End" << std::endl;
|
||||
std::cout << "3. Display" << std::endl;
|
||||
std::cout << "4.Exit" << std::endl;
|
||||
std::cout << "Enter Your choice" << std::endl;
|
||||
std::cin >> z;
|
||||
switch (z) {
|
||||
case 1:
|
||||
std::cout << "Enter the number you want to enter" << std::endl;
|
||||
std::cin >> x;
|
||||
insertAtTheBeginning(x);
|
||||
break;
|
||||
case 2:
|
||||
std::cout << "Enter the number you want to enter" << std::endl;
|
||||
std::cin >> y;
|
||||
insertAtTheEnd(y);
|
||||
break;
|
||||
case 3:
|
||||
std::cout
|
||||
<< "The linked list contains the following element in order"
|
||||
<< std::endl;
|
||||
display();
|
||||
break;
|
||||
case 4:
|
||||
return 0;
|
||||
default:
|
||||
std::cout << "The entered choice is not correct" << std::endl;
|
||||
}
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
153
data_structures/list_array.cpp
Normal file
153
data_structures/list_array.cpp
Normal file
@@ -0,0 +1,153 @@
|
||||
#include <iostream>
|
||||
using namespace std;
|
||||
|
||||
struct list {
|
||||
int data[50];
|
||||
int top = 0;
|
||||
bool isSorted = false;
|
||||
|
||||
int BinarySearch(int *array, int first, int last, int x) {
|
||||
if (last < first) {
|
||||
return -1;
|
||||
}
|
||||
int mid = (first + last) / 2;
|
||||
if (array[mid] == x)
|
||||
return mid;
|
||||
else if (x < array[mid])
|
||||
return (BinarySearch(array, first, mid - 1, x));
|
||||
else if (x > array[mid])
|
||||
return (BinarySearch(array, mid + 1, last, x));
|
||||
}
|
||||
|
||||
int LinarSearch(int *array, int x) {
|
||||
for (int i = 0; i < top; i++) {
|
||||
if (array[i] == x) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
|
||||
return -1;
|
||||
}
|
||||
|
||||
int Search(int x) {
|
||||
int pos = -1;
|
||||
|
||||
if (isSorted) {
|
||||
pos = BinarySearch(data, 0, top - 1, x);
|
||||
}
|
||||
|
||||
else {
|
||||
pos = LinarSearch(data, x);
|
||||
}
|
||||
|
||||
if (pos != -1) {
|
||||
cout << "\nElement found at position : " << pos;
|
||||
} else {
|
||||
cout << "\nElement not found";
|
||||
}
|
||||
return pos;
|
||||
}
|
||||
|
||||
void Sort() {
|
||||
int i, j, pos;
|
||||
for (i = 0; i < top; i++) {
|
||||
int min = data[i];
|
||||
for (j = i + 1; j < top; j++) {
|
||||
if (data[j] < min) {
|
||||
pos = j;
|
||||
min = data[pos];
|
||||
}
|
||||
}
|
||||
|
||||
int temp = data[i];
|
||||
data[i] = data[pos];
|
||||
data[pos] = temp;
|
||||
}
|
||||
isSorted = true;
|
||||
}
|
||||
|
||||
void insert(int x) {
|
||||
if (!isSorted) {
|
||||
if (top == 49) {
|
||||
cout << "\nOverflow";
|
||||
} else {
|
||||
data[top] = x;
|
||||
top++;
|
||||
}
|
||||
}
|
||||
|
||||
else {
|
||||
int pos = 0;
|
||||
|
||||
for (int i = 0; i < top - 1; i++) {
|
||||
if (data[i] <= x && x <= data[i + 1]) {
|
||||
pos = i + 1;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (pos == 0) {
|
||||
pos = top - 1;
|
||||
}
|
||||
|
||||
for (int i = top; i > pos; i--) {
|
||||
data[i] = data[i - 1];
|
||||
}
|
||||
top++;
|
||||
data[pos] = x;
|
||||
}
|
||||
}
|
||||
|
||||
void Remove(int x) {
|
||||
int pos = Search(x);
|
||||
cout << "\n" << data[pos] << " deleted";
|
||||
for (int i = pos; i < top; i++) {
|
||||
data[i] = data[i + 1];
|
||||
}
|
||||
top--;
|
||||
}
|
||||
|
||||
void Show() {
|
||||
for (int i = 0; i < top; i++) {
|
||||
cout << data[i] << "\t";
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
int main() {
|
||||
list L;
|
||||
int choice;
|
||||
int x;
|
||||
do {
|
||||
cout << "\n1.Insert";
|
||||
cout << "\n2.Delete";
|
||||
cout << "\n3.Search";
|
||||
cout << "\n4.Sort";
|
||||
cout << "\n5.Print";
|
||||
cout << "\n\nEnter Your Choice : ";
|
||||
cin >> choice;
|
||||
switch (choice) {
|
||||
case 1:
|
||||
cout << "\nEnter the element to be inserted : ";
|
||||
cin >> x;
|
||||
L.insert(x);
|
||||
break;
|
||||
case 2:
|
||||
cout << "\nEnter the element to be removed : ";
|
||||
cin >> x;
|
||||
L.Remove(x);
|
||||
break;
|
||||
case 3:
|
||||
cout << "\nEnter the element to be searched : ";
|
||||
cin >> x;
|
||||
L.Search(x);
|
||||
break;
|
||||
case 4:
|
||||
L.Sort();
|
||||
break;
|
||||
case 5:
|
||||
L.Show();
|
||||
break;
|
||||
}
|
||||
} while (choice != 0);
|
||||
return 0;
|
||||
}
|
||||
92
data_structures/morrisinorder.cpp
Normal file
92
data_structures/morrisinorder.cpp
Normal file
@@ -0,0 +1,92 @@
|
||||
#include <iostream>
|
||||
#include <queue>
|
||||
|
||||
/**************************
|
||||
@author shrutisheoran
|
||||
**************************/
|
||||
|
||||
using namespace std;
|
||||
|
||||
struct Btree {
|
||||
int data;
|
||||
struct Btree *left; // Pointer to left subtree
|
||||
struct Btree *right; // Pointer to right subtree
|
||||
};
|
||||
|
||||
void insert(Btree **root, int d) {
|
||||
Btree *nn = new Btree(); // Creating new node
|
||||
nn->data = d;
|
||||
nn->left = NULL;
|
||||
nn->right = NULL;
|
||||
if (*root == NULL) {
|
||||
*root = nn;
|
||||
return;
|
||||
} else {
|
||||
queue<Btree *> q;
|
||||
// Adding root node to queue
|
||||
q.push(*root);
|
||||
while (!q.empty()) {
|
||||
Btree *node = q.front();
|
||||
// Removing parent node from queue
|
||||
q.pop();
|
||||
if (node->left)
|
||||
// Adding left child of removed node to queue
|
||||
q.push(node->left);
|
||||
else {
|
||||
// Adding new node if no left child is present
|
||||
node->left = nn;
|
||||
return;
|
||||
}
|
||||
if (node->right)
|
||||
// Adding right child of removed node to queue
|
||||
q.push(node->right);
|
||||
else {
|
||||
// Adding new node if no right child is present
|
||||
node->right = nn;
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void morrisInorder(Btree *root) {
|
||||
Btree *curr = root;
|
||||
Btree *temp;
|
||||
while (curr) {
|
||||
if (curr->left == NULL) {
|
||||
cout << curr->data << " ";
|
||||
// If left of current node is NULL then curr is shifted to right
|
||||
curr = curr->right;
|
||||
} else {
|
||||
// Left of current node is stored in temp
|
||||
temp = curr->left;
|
||||
// Moving to extreme right of temp
|
||||
while (temp->right && temp->right != curr) temp = temp->right;
|
||||
// If extreme right is null it is made to point to currrent node
|
||||
// (will be used for backtracking)
|
||||
if (temp->right == NULL) {
|
||||
temp->right = curr;
|
||||
// current node is made to point its left subtree
|
||||
curr = curr->left;
|
||||
}
|
||||
// If extreme right already points to currrent node it it set to
|
||||
// null
|
||||
else if (temp->right == curr) {
|
||||
cout << curr->data << " ";
|
||||
temp->right = NULL;
|
||||
// current node is made to point its right subtree
|
||||
curr = curr->right;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
int main() {
|
||||
// Testing morrisInorder funtion
|
||||
Btree *root = NULL;
|
||||
int i;
|
||||
for (i = 1; i <= 7; i++) insert(&root, i);
|
||||
cout << "Morris Inorder: ";
|
||||
morrisInorder(root);
|
||||
return 0;
|
||||
}
|
||||
88
data_structures/queue.h
Normal file
88
data_structures/queue.h
Normal file
@@ -0,0 +1,88 @@
|
||||
/* This class specifies the basic operation on a queue as a linked list */
|
||||
#ifndef DATA_STRUCTURES_QUEUE_H_
|
||||
#define DATA_STRUCTURES_QUEUE_H_
|
||||
|
||||
#include <cassert>
|
||||
#include <iostream>
|
||||
|
||||
/** Definition of the node */
|
||||
template <class Kind>
|
||||
struct node {
|
||||
Kind data;
|
||||
node<Kind> *next;
|
||||
};
|
||||
|
||||
/** Definition of the queue class */
|
||||
template <class Kind>
|
||||
class queue {
|
||||
public:
|
||||
/** Show queue */
|
||||
void display() {
|
||||
node<Kind> *current = queueFront;
|
||||
std::cout << "Front --> ";
|
||||
while (current != NULL) {
|
||||
std::cout << current->data << " ";
|
||||
current = current->next;
|
||||
}
|
||||
std::cout << std::endl;
|
||||
std::cout << "Size of queue: " << size << std::endl;
|
||||
}
|
||||
|
||||
/** Default constructor*/
|
||||
queue() {
|
||||
queueFront = NULL;
|
||||
queueRear = NULL;
|
||||
size = 0;
|
||||
}
|
||||
|
||||
/** Destructor */
|
||||
~queue() {}
|
||||
|
||||
/** Determine whether the queue is empty */
|
||||
bool isEmptyQueue() { return (queueFront == NULL); }
|
||||
|
||||
/** Add new item to the queue */
|
||||
void enQueue(Kind item) {
|
||||
node<Kind> *newNode;
|
||||
newNode = new node<Kind>;
|
||||
newNode->data = item;
|
||||
newNode->next = NULL;
|
||||
if (queueFront == NULL) {
|
||||
queueFront = newNode;
|
||||
queueRear = newNode;
|
||||
} else {
|
||||
queueRear->next = newNode;
|
||||
queueRear = queueRear->next;
|
||||
}
|
||||
size++;
|
||||
}
|
||||
|
||||
/** Return the first element of the queue */
|
||||
Kind front() {
|
||||
assert(queueFront != NULL);
|
||||
return queueFront->data;
|
||||
}
|
||||
|
||||
/** Remove the top element of the queue */
|
||||
void deQueue() {
|
||||
node<Kind> *temp;
|
||||
if (!isEmptyQueue()) {
|
||||
temp = queueFront;
|
||||
queueFront = queueFront->next;
|
||||
delete temp;
|
||||
size--;
|
||||
} else {
|
||||
std::cout << "Queue is empty !" << std::endl;
|
||||
}
|
||||
}
|
||||
|
||||
/** Clear queue */
|
||||
void clear() { queueFront = NULL; }
|
||||
|
||||
private:
|
||||
node<Kind> *queueFront; /**< Pointer to the front of the queue */
|
||||
node<Kind> *queueRear; /**< Pointer to the rear of the queue */
|
||||
int size;
|
||||
};
|
||||
|
||||
#endif // DATA_STRUCTURES_QUEUE_H_
|
||||
92
data_structures/queue_using_array.cpp
Normal file
92
data_structures/queue_using_array.cpp
Normal file
@@ -0,0 +1,92 @@
|
||||
/*
|
||||
Write a program to implement Linear Queue using array.
|
||||
|
||||
Functions to implement
|
||||
Enqueue (Insertion)
|
||||
Dequeue (Deletion)
|
||||
|
||||
*/
|
||||
#include <iostream>
|
||||
|
||||
#define MAXSIZE 10
|
||||
|
||||
class Queue_Array {
|
||||
int front;
|
||||
int rear;
|
||||
int size;
|
||||
|
||||
public:
|
||||
Queue_Array() {
|
||||
front = -1;
|
||||
rear = -1;
|
||||
size = MAXSIZE;
|
||||
}
|
||||
int *arr = new int[size];
|
||||
void enqueue(int);
|
||||
int dequeue();
|
||||
void display();
|
||||
};
|
||||
|
||||
void Queue_Array::enqueue(int ele) {
|
||||
if (rear == size - 1) {
|
||||
std::cout << "\nStack is full";
|
||||
} else if (front == -1 && rear == -1) {
|
||||
front = rear = 0;
|
||||
arr[rear] = ele;
|
||||
} else if (rear < size) {
|
||||
rear++;
|
||||
arr[rear] = ele;
|
||||
}
|
||||
}
|
||||
|
||||
int Queue_Array::dequeue() {
|
||||
int d;
|
||||
if (front == -1) {
|
||||
std::cout << "\nstack is empty ";
|
||||
return 0;
|
||||
} else if (front == rear) {
|
||||
d = arr[front];
|
||||
front = rear = -1;
|
||||
} else {
|
||||
d = arr[front++];
|
||||
}
|
||||
|
||||
return d;
|
||||
}
|
||||
|
||||
void Queue_Array::display() {
|
||||
if (front == -1) {
|
||||
std::cout << "\nStack is empty";
|
||||
} else {
|
||||
for (int i = front; i <= rear; i++) std::cout << arr[i] << " ";
|
||||
}
|
||||
}
|
||||
|
||||
int main() {
|
||||
int op, data;
|
||||
|
||||
Queue_Array ob;
|
||||
|
||||
std::cout << "\n1. enqueue(Insertion) ";
|
||||
std::cout << "\n2. dequeue(Deletion)";
|
||||
std::cout << "\n3. Display";
|
||||
std::cout << "\n4. Exit";
|
||||
while (1) {
|
||||
std::cout << "\nEnter your choice ";
|
||||
std::cin >> op;
|
||||
if (op == 1) {
|
||||
std::cout << "Enter data ";
|
||||
std::cin >> data;
|
||||
ob.enqueue(data);
|
||||
} else if (op == 2) {
|
||||
data = ob.dequeue();
|
||||
std::cout << "\ndequeue element is:\t" << data;
|
||||
} else if (op == 3) {
|
||||
ob.display();
|
||||
} else if (op == 4) {
|
||||
exit(0);
|
||||
} else {
|
||||
std::cout << "\nWrong choice ";
|
||||
}
|
||||
}
|
||||
}
|
||||
57
data_structures/queue_using_array2.cpp
Normal file
57
data_structures/queue_using_array2.cpp
Normal file
@@ -0,0 +1,57 @@
|
||||
#include <iostream>
|
||||
using namespace std;
|
||||
|
||||
int queue[10];
|
||||
int front = 0;
|
||||
int rear = 0;
|
||||
|
||||
void Enque(int x) {
|
||||
if (rear == 10) {
|
||||
cout << "\nOverflow";
|
||||
} else {
|
||||
queue[rear++] = x;
|
||||
}
|
||||
}
|
||||
|
||||
void Deque() {
|
||||
if (front == rear) {
|
||||
cout << "\nUnderflow";
|
||||
}
|
||||
|
||||
else {
|
||||
cout << "\n" << queue[front++] << " deleted";
|
||||
for (int i = front; i < rear; i++) {
|
||||
queue[i - front] = queue[i];
|
||||
}
|
||||
rear = rear - front;
|
||||
front = 0;
|
||||
}
|
||||
}
|
||||
|
||||
void show() {
|
||||
for (int i = front; i < rear; i++) {
|
||||
cout << queue[i] << "\t";
|
||||
}
|
||||
}
|
||||
|
||||
int main() {
|
||||
int ch, x;
|
||||
do {
|
||||
cout << "\n1. Enque";
|
||||
cout << "\n2. Deque";
|
||||
cout << "\n3. Print";
|
||||
cout << "\nEnter Your Choice : ";
|
||||
cin >> ch;
|
||||
if (ch == 1) {
|
||||
cout << "\nInsert : ";
|
||||
cin >> x;
|
||||
Enque(x);
|
||||
} else if (ch == 2) {
|
||||
Deque();
|
||||
} else if (ch == 3) {
|
||||
show();
|
||||
}
|
||||
} while (ch != 0);
|
||||
|
||||
return 0;
|
||||
}
|
||||
70
data_structures/queue_using_linked_list.cpp
Normal file
70
data_structures/queue_using_linked_list.cpp
Normal file
@@ -0,0 +1,70 @@
|
||||
#include <iostream>
|
||||
using namespace std;
|
||||
|
||||
struct node {
|
||||
int val;
|
||||
node *next;
|
||||
};
|
||||
|
||||
node *front, *rear;
|
||||
|
||||
void Enque(int x) {
|
||||
if (rear == NULL) {
|
||||
node *n = new node;
|
||||
n->val = x;
|
||||
n->next = NULL;
|
||||
rear = n;
|
||||
front = n;
|
||||
}
|
||||
|
||||
else {
|
||||
node *n = new node;
|
||||
n->val = x;
|
||||
n->next = NULL;
|
||||
rear->next = n;
|
||||
rear = n;
|
||||
}
|
||||
}
|
||||
|
||||
void Deque() {
|
||||
if (rear == NULL && front == NULL) {
|
||||
cout << "\nUnderflow";
|
||||
} else {
|
||||
node *t = front;
|
||||
cout << "\n" << t->val << " deleted";
|
||||
front = front->next;
|
||||
delete t;
|
||||
if (front == NULL)
|
||||
rear = NULL;
|
||||
}
|
||||
}
|
||||
|
||||
void show() {
|
||||
node *t = front;
|
||||
while (t != NULL) {
|
||||
cout << t->val << "\t";
|
||||
t = t->next;
|
||||
}
|
||||
}
|
||||
|
||||
int main() {
|
||||
int ch, x;
|
||||
do {
|
||||
cout << "\n1. Enque";
|
||||
cout << "\n2. Deque";
|
||||
cout << "\n3. Print";
|
||||
cout << "\nEnter Your Choice : ";
|
||||
cin >> ch;
|
||||
if (ch == 1) {
|
||||
cout << "\nInsert : ";
|
||||
cin >> x;
|
||||
Enque(x);
|
||||
} else if (ch == 2) {
|
||||
Deque();
|
||||
} else if (ch == 3) {
|
||||
show();
|
||||
}
|
||||
} while (ch != 0);
|
||||
|
||||
return 0;
|
||||
}
|
||||
86
data_structures/queue_using_linkedlist.cpp
Normal file
86
data_structures/queue_using_linkedlist.cpp
Normal file
@@ -0,0 +1,86 @@
|
||||
/*
|
||||
Write a program to implement Queue using linkedlist.
|
||||
*/
|
||||
#include <iostream>
|
||||
|
||||
struct linkedlist {
|
||||
int data;
|
||||
linkedlist *next;
|
||||
};
|
||||
class stack_linkedList {
|
||||
public:
|
||||
linkedlist *front;
|
||||
linkedlist *rear;
|
||||
|
||||
stack_linkedList() { front = rear = NULL; }
|
||||
void enqueue(int);
|
||||
int dequeue();
|
||||
void display();
|
||||
};
|
||||
void stack_linkedList::enqueue(int ele) {
|
||||
linkedlist *temp = new linkedlist();
|
||||
temp->data = ele;
|
||||
temp->next = NULL;
|
||||
|
||||
if (front == NULL)
|
||||
front = rear = temp;
|
||||
else {
|
||||
rear->next = temp;
|
||||
rear = temp;
|
||||
}
|
||||
}
|
||||
int stack_linkedList::dequeue() {
|
||||
linkedlist *temp;
|
||||
int ele;
|
||||
if (front == NULL)
|
||||
std::cout << "\nStack is empty";
|
||||
else {
|
||||
temp = front;
|
||||
ele = temp->data;
|
||||
if (front == rear) // if length of queue is 1;
|
||||
rear = rear->next;
|
||||
front = front->next;
|
||||
delete (temp);
|
||||
}
|
||||
return ele;
|
||||
}
|
||||
void stack_linkedList::display() {
|
||||
if (front == NULL)
|
||||
std::cout << "\nStack is empty";
|
||||
|
||||
else {
|
||||
linkedlist *temp;
|
||||
temp = front;
|
||||
while (temp != NULL) {
|
||||
std::cout << temp->data << " ";
|
||||
temp = temp->next;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
int main() {
|
||||
int op, data;
|
||||
stack_linkedList ob;
|
||||
std::cout << "\n1. enqueue(Insertion) ";
|
||||
std::cout << "\n2. dequeue(Deletion)";
|
||||
std::cout << "\n3. Display";
|
||||
std::cout << "\n4. Exit";
|
||||
|
||||
while (1) {
|
||||
std::cout << "\nEnter your choice ";
|
||||
std::cin >> op;
|
||||
if (op == 1) {
|
||||
std::cout << "Enter data ";
|
||||
std::cin >> data;
|
||||
ob.enqueue(data);
|
||||
} else if (op == 2)
|
||||
data = ob.dequeue();
|
||||
else if (op == 3)
|
||||
ob.display();
|
||||
else if (op == 4)
|
||||
exit(0);
|
||||
else
|
||||
std::cout << "\nWrong choice ";
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
111
data_structures/stack.h
Normal file
111
data_structures/stack.h
Normal file
@@ -0,0 +1,111 @@
|
||||
/* This class specifies the basic operation on a stack as a linked list */
|
||||
#ifndef DATA_STRUCTURES_STACK_H_
|
||||
#define DATA_STRUCTURES_STACK_H_
|
||||
|
||||
#include <cassert>
|
||||
#include <iostream>
|
||||
|
||||
/* Definition of the node */
|
||||
template <class Type>
|
||||
struct node {
|
||||
Type data;
|
||||
node<Type> *next;
|
||||
};
|
||||
|
||||
/* Definition of the stack class */
|
||||
template <class Type>
|
||||
class stack {
|
||||
public:
|
||||
/** Show stack */
|
||||
void display() {
|
||||
node<Type> *current = stackTop;
|
||||
std::cout << "Top --> ";
|
||||
while (current != NULL) {
|
||||
std::cout << current->data << " ";
|
||||
current = current->next;
|
||||
}
|
||||
std::cout << std::endl;
|
||||
std::cout << "Size of stack: " << size << std::endl;
|
||||
}
|
||||
|
||||
/** Default constructor*/
|
||||
stack() {
|
||||
stackTop = NULL;
|
||||
size = 0;
|
||||
}
|
||||
|
||||
/** Destructor */
|
||||
~stack() {}
|
||||
|
||||
/** Determine whether the stack is empty */
|
||||
bool isEmptyStack() { return (stackTop == NULL); }
|
||||
|
||||
/** Add new item to the stack */
|
||||
void push(Type item) {
|
||||
node<Type> *newNode;
|
||||
newNode = new node<Type>;
|
||||
newNode->data = item;
|
||||
newNode->next = stackTop;
|
||||
stackTop = newNode;
|
||||
size++;
|
||||
}
|
||||
|
||||
/** Return the top element of the stack */
|
||||
Type top() {
|
||||
assert(stackTop != NULL);
|
||||
return stackTop->data;
|
||||
}
|
||||
|
||||
/** Remove the top element of the stack */
|
||||
void pop() {
|
||||
node<Type> *temp;
|
||||
if (!isEmptyStack()) {
|
||||
temp = stackTop;
|
||||
stackTop = stackTop->next;
|
||||
delete temp;
|
||||
size--;
|
||||
} else {
|
||||
std::cout << "Stack is empty !" << std::endl;
|
||||
}
|
||||
}
|
||||
|
||||
/** Clear stack */
|
||||
void clear() { stackTop = NULL; }
|
||||
|
||||
/** Overload "=" the assignment operator */
|
||||
stack<Type> &operator=(const stack<Type> &otherStack) {
|
||||
node<Type> *newNode, *current, *last;
|
||||
|
||||
/* If stack is no empty, make it empty */
|
||||
if (stackTop != NULL) {
|
||||
stackTop = NULL;
|
||||
}
|
||||
if (otherStack.stackTop == NULL) {
|
||||
stackTop = NULL;
|
||||
} else {
|
||||
current = otherStack.stackTop;
|
||||
stackTop = new node<Type>;
|
||||
stackTop->data = current->data;
|
||||
stackTop->next = NULL;
|
||||
last = stackTop;
|
||||
current = current->next;
|
||||
/* Copy the remaining stack */
|
||||
while (current != NULL) {
|
||||
newNode = new node<Type>;
|
||||
newNode->data = current->data;
|
||||
newNode->next = NULL;
|
||||
last->next = newNode;
|
||||
last = newNode;
|
||||
current = current->next;
|
||||
}
|
||||
}
|
||||
size = otherStack.size;
|
||||
return *this;
|
||||
}
|
||||
|
||||
private:
|
||||
node<Type> *stackTop; /**< Pointer to the stack */
|
||||
int size;
|
||||
};
|
||||
|
||||
#endif // DATA_STRUCTURES_STACK_H_
|
||||
55
data_structures/stack_using_array.cpp
Normal file
55
data_structures/stack_using_array.cpp
Normal file
@@ -0,0 +1,55 @@
|
||||
#include <iostream>
|
||||
|
||||
int *stack;
|
||||
int top = 0, stack_size;
|
||||
|
||||
void push(int x) {
|
||||
if (top == stack_size) {
|
||||
std::cout << "\nOverflow";
|
||||
} else {
|
||||
stack[top++] = x;
|
||||
}
|
||||
}
|
||||
|
||||
void pop() {
|
||||
if (top == 0) {
|
||||
std::cout << "\nUnderflow";
|
||||
} else {
|
||||
std::cout << "\n" << stack[--top] << " deleted";
|
||||
}
|
||||
}
|
||||
|
||||
void show() {
|
||||
for (int i = 0; i < top; i++) {
|
||||
std::cout << stack[i] << "\n";
|
||||
}
|
||||
}
|
||||
|
||||
void topmost() { std::cout << "\nTopmost element: " << stack[top - 1]; }
|
||||
int main() {
|
||||
std::cout << "\nEnter stack_size of stack : ";
|
||||
std::cin >> stack_size;
|
||||
stack = new int[stack_size];
|
||||
int ch, x;
|
||||
do {
|
||||
std::cout << "\n1. Push";
|
||||
std::cout << "\n2. Pop";
|
||||
std::cout << "\n3. Print";
|
||||
std::cout << "\n4. Print topmost element:";
|
||||
std::cout << "\nEnter Your Choice : ";
|
||||
std::cin >> ch;
|
||||
if (ch == 1) {
|
||||
std::cout << "\nInsert : ";
|
||||
std::cin >> x;
|
||||
push(x);
|
||||
} else if (ch == 2) {
|
||||
pop();
|
||||
} else if (ch == 3) {
|
||||
show();
|
||||
} else if (ch == 4) {
|
||||
topmost();
|
||||
}
|
||||
} while (ch != 0);
|
||||
|
||||
return 0;
|
||||
}
|
||||
57
data_structures/stack_using_linked_list.cpp
Normal file
57
data_structures/stack_using_linked_list.cpp
Normal file
@@ -0,0 +1,57 @@
|
||||
#include <iostream>
|
||||
using namespace std;
|
||||
|
||||
struct node {
|
||||
int val;
|
||||
node *next;
|
||||
};
|
||||
|
||||
node *top;
|
||||
|
||||
void push(int x) {
|
||||
node *n = new node;
|
||||
n->val = x;
|
||||
n->next = top;
|
||||
top = n;
|
||||
}
|
||||
|
||||
void pop() {
|
||||
if (top == NULL) {
|
||||
cout << "\nUnderflow";
|
||||
} else {
|
||||
node *t = top;
|
||||
cout << "\n" << t->val << " deleted";
|
||||
top = top->next;
|
||||
delete t;
|
||||
}
|
||||
}
|
||||
|
||||
void show() {
|
||||
node *t = top;
|
||||
while (t != NULL) {
|
||||
cout << t->val << "\n";
|
||||
t = t->next;
|
||||
}
|
||||
}
|
||||
|
||||
int main() {
|
||||
int ch, x;
|
||||
do {
|
||||
cout << "\n1. Push";
|
||||
cout << "\n2. Pop";
|
||||
cout << "\n3. Print";
|
||||
cout << "\nEnter Your Choice : ";
|
||||
cin >> ch;
|
||||
if (ch == 1) {
|
||||
cout << "\nInsert : ";
|
||||
cin >> x;
|
||||
push(x);
|
||||
} else if (ch == 2) {
|
||||
pop();
|
||||
} else if (ch == 3) {
|
||||
show();
|
||||
}
|
||||
} while (ch != 0);
|
||||
|
||||
return 0;
|
||||
}
|
||||
17
data_structures/student.txt
Normal file
17
data_structures/student.txt
Normal file
@@ -0,0 +1,17 @@
|
||||
3.4 Tom
|
||||
3.2 Kathy
|
||||
2.5 Hoang
|
||||
3.4 Tom
|
||||
3.8 Randy
|
||||
3.9 Kingston
|
||||
3.8 Mickey
|
||||
3.6 Peter
|
||||
3.5 Donald
|
||||
3.8 Cindy
|
||||
3.7 Dome
|
||||
3.9 Andy
|
||||
3.8 Hai
|
||||
3.9 Minnie
|
||||
2.7 Gilda
|
||||
3.9 Vinay
|
||||
3.4 Hiral
|
||||
41
data_structures/test_queue.cpp
Normal file
41
data_structures/test_queue.cpp
Normal file
@@ -0,0 +1,41 @@
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
|
||||
#include "./queue.h"
|
||||
|
||||
int main() {
|
||||
queue<std::string> q;
|
||||
std::cout << "---------------------- Test construct ----------------------"
|
||||
<< std::endl;
|
||||
q.display();
|
||||
std::cout
|
||||
<< "---------------------- Test isEmptyQueue ----------------------"
|
||||
<< std::endl;
|
||||
if (q.isEmptyQueue())
|
||||
std::cout << "PASS" << std::endl;
|
||||
else
|
||||
std::cout << "FAIL" << std::endl;
|
||||
std::cout << "---------------------- Test enQueue ----------------------"
|
||||
<< std::endl;
|
||||
std::cout << "After Hai, Jeff, Tom, Jkingston go into queue: " << std::endl;
|
||||
q.enQueue("Hai");
|
||||
q.enQueue("Jeff");
|
||||
q.enQueue("Tom");
|
||||
q.enQueue("Jkingston");
|
||||
q.display();
|
||||
std::cout << "---------------------- Test front ----------------------"
|
||||
<< std::endl;
|
||||
std::string value = q.front();
|
||||
if (value == "Hai")
|
||||
std::cout << "PASS" << std::endl;
|
||||
else
|
||||
std::cout << "FAIL" << std::endl;
|
||||
std::cout << "---------------------- Test deQueue ----------------------"
|
||||
<< std::endl;
|
||||
q.display();
|
||||
q.deQueue();
|
||||
q.deQueue();
|
||||
std::cout << "After Hai, Jeff left the queue: " << std::endl;
|
||||
q.display();
|
||||
return 0;
|
||||
}
|
||||
59
data_structures/test_stack.cpp
Normal file
59
data_structures/test_stack.cpp
Normal file
@@ -0,0 +1,59 @@
|
||||
#include <iostream>
|
||||
|
||||
#include "./stack.h"
|
||||
|
||||
int main() {
|
||||
stack<int> stk;
|
||||
std::cout << "---------------------- Test construct ----------------------"
|
||||
<< std::endl;
|
||||
stk.display();
|
||||
std::cout
|
||||
<< "---------------------- Test isEmptyStack ----------------------"
|
||||
<< std::endl;
|
||||
if (stk.isEmptyStack())
|
||||
std::cout << "PASS" << std::endl;
|
||||
else
|
||||
std::cout << "FAIL" << std::endl;
|
||||
std::cout << "---------------------- Test push ----------------------"
|
||||
<< std::endl;
|
||||
std::cout << "After pushing 10 20 30 40 into stack: " << std::endl;
|
||||
stk.push(10);
|
||||
stk.push(20);
|
||||
stk.push(30);
|
||||
stk.push(40);
|
||||
stk.display();
|
||||
std::cout << "---------------------- Test top ----------------------"
|
||||
<< std::endl;
|
||||
int value = stk.top();
|
||||
if (value == 40)
|
||||
std::cout << "PASS" << std::endl;
|
||||
else
|
||||
std::cout << "FAIL" << std::endl;
|
||||
std::cout << "---------------------- Test pop ----------------------"
|
||||
<< std::endl;
|
||||
stk.display();
|
||||
stk.pop();
|
||||
stk.pop();
|
||||
std::cout << "After popping 2 times: " << std::endl;
|
||||
stk.display();
|
||||
std::cout << "---------------------- Test overload = operator "
|
||||
"----------------------"
|
||||
<< std::endl;
|
||||
stack<int> stk1;
|
||||
std::cout << "stk current: " << std::endl;
|
||||
stk.display();
|
||||
std::cout << std::endl << "Assign stk1 = stk " << std::endl;
|
||||
stk1 = stk;
|
||||
stk1.display();
|
||||
std::cout << std::endl << "After pushing 8 9 10 into stk1:" << std::endl;
|
||||
stk1.push(8);
|
||||
stk1.push(9);
|
||||
stk1.push(10);
|
||||
stk1.display();
|
||||
std::cout << std::endl << "stk current: " << std::endl;
|
||||
stk.display();
|
||||
std::cout << "Assign back stk = stk1:" << std::endl;
|
||||
stk = stk1;
|
||||
stk.display();
|
||||
return 0;
|
||||
}
|
||||
52
data_structures/test_stack_students.cpp
Normal file
52
data_structures/test_stack_students.cpp
Normal file
@@ -0,0 +1,52 @@
|
||||
/*
|
||||
* This program reads a data file consisting of students' GPAs
|
||||
* followed by their names. The program then prints the highest
|
||||
* GPA and the names of the students with the highest GPA.
|
||||
* It uses stack to store the names of the students
|
||||
* Run:
|
||||
* make all
|
||||
* ./main student.txt
|
||||
************************************************************
|
||||
* */
|
||||
#include <cassert>
|
||||
#include <fstream>
|
||||
#include <iomanip>
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
|
||||
#include "./stack.h"
|
||||
|
||||
int main(int argc, char* argv[]) {
|
||||
double GPA;
|
||||
double highestGPA;
|
||||
std::string name;
|
||||
|
||||
assert(argc == 2);
|
||||
std::ifstream infile;
|
||||
stack<std::string> stk;
|
||||
|
||||
infile.open(argv[1]);
|
||||
std::cout << std::fixed << std::showpoint;
|
||||
std::cout << std::setprecision(2);
|
||||
infile >> GPA >> name;
|
||||
highestGPA = GPA;
|
||||
|
||||
while (infile) {
|
||||
if (GPA > highestGPA) {
|
||||
stk.clear();
|
||||
stk.push(name);
|
||||
highestGPA = GPA;
|
||||
} else if (GPA == highestGPA) {
|
||||
stk.push(name);
|
||||
}
|
||||
infile >> GPA >> name;
|
||||
}
|
||||
std::cout << "Highest GPA: " << highestGPA << std::endl;
|
||||
std::cout << "Students the highest GPA are: " << std::endl;
|
||||
while (!stk.isEmptyStack()) {
|
||||
std::cout << stk.top() << std::endl;
|
||||
stk.pop();
|
||||
}
|
||||
std::cout << std::endl;
|
||||
return 0;
|
||||
}
|
||||
119
data_structures/tree.cpp
Normal file
119
data_structures/tree.cpp
Normal file
@@ -0,0 +1,119 @@
|
||||
#include <iostream>
|
||||
#include <list>
|
||||
using namespace std;
|
||||
|
||||
struct node {
|
||||
int val;
|
||||
node *left;
|
||||
node *right;
|
||||
};
|
||||
|
||||
void CreateTree(node *curr, node *n, int x, char pos) {
|
||||
if (n != NULL) {
|
||||
char ch;
|
||||
cout << "\nLeft or Right of " << n->val << " : ";
|
||||
cin >> ch;
|
||||
if (ch == 'l')
|
||||
CreateTree(n, n->left, x, ch);
|
||||
else if (ch == 'r')
|
||||
CreateTree(n, n->right, x, ch);
|
||||
} else {
|
||||
node *t = new node;
|
||||
t->val = x;
|
||||
t->left = NULL;
|
||||
t->right = NULL;
|
||||
if (pos == 'l') {
|
||||
curr->left = t;
|
||||
} else if (pos == 'r') {
|
||||
curr->right = t;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void BFT(node *n) {
|
||||
list<node *> queue;
|
||||
|
||||
queue.push_back(n);
|
||||
|
||||
while (!queue.empty()) {
|
||||
n = queue.front();
|
||||
cout << n->val << " ";
|
||||
queue.pop_front();
|
||||
|
||||
if (n->left != NULL)
|
||||
queue.push_back(n->left);
|
||||
if (n->right != NULL)
|
||||
queue.push_back(n->right);
|
||||
}
|
||||
}
|
||||
|
||||
void Pre(node *n) {
|
||||
if (n != NULL) {
|
||||
cout << n->val << " ";
|
||||
Pre(n->left);
|
||||
Pre(n->right);
|
||||
}
|
||||
}
|
||||
|
||||
void In(node *n) {
|
||||
if (n != NULL) {
|
||||
In(n->left);
|
||||
cout << n->val << " ";
|
||||
In(n->right);
|
||||
}
|
||||
}
|
||||
|
||||
void Post(node *n) {
|
||||
if (n != NULL) {
|
||||
Post(n->left);
|
||||
Post(n->right);
|
||||
cout << n->val << " ";
|
||||
}
|
||||
}
|
||||
|
||||
int main() {
|
||||
int value;
|
||||
int ch;
|
||||
node *root = new node;
|
||||
cout << "\nEnter the value of root node :";
|
||||
cin >> value;
|
||||
root->val = value;
|
||||
root->left = NULL;
|
||||
root->right = NULL;
|
||||
do {
|
||||
cout << "\n1. Insert";
|
||||
cout << "\n2. Breadth First";
|
||||
cout << "\n3. Preorder Depth First";
|
||||
cout << "\n4. Inorder Depth First";
|
||||
cout << "\n5. Postorder Depth First";
|
||||
|
||||
cout << "\nEnter Your Choice : ";
|
||||
cin >> ch;
|
||||
switch (ch) {
|
||||
case 1:
|
||||
int x;
|
||||
char pos;
|
||||
cout << "\nEnter the value to be Inserted : ";
|
||||
cin >> x;
|
||||
cout << "\nLeft or Right of Root : ";
|
||||
cin >> pos;
|
||||
if (pos == 'l')
|
||||
CreateTree(root, root->left, x, pos);
|
||||
else if (pos == 'r')
|
||||
CreateTree(root, root->right, x, pos);
|
||||
break;
|
||||
case 2:
|
||||
BFT(root);
|
||||
break;
|
||||
case 3:
|
||||
Pre(root);
|
||||
break;
|
||||
case 4:
|
||||
In(root);
|
||||
break;
|
||||
case 5:
|
||||
Post(root);
|
||||
break;
|
||||
}
|
||||
} while (ch != 0);
|
||||
}
|
||||
168
data_structures/trie_modern.cpp
Normal file
168
data_structures/trie_modern.cpp
Normal file
@@ -0,0 +1,168 @@
|
||||
/**
|
||||
* @file
|
||||
*
|
||||
* Copyright 2020 @author Anmol3299
|
||||
* \brief A basic implementation of trie class to store only lower-case strings.
|
||||
*/
|
||||
#include <iostream> // for io operations
|
||||
#include <memory> // for std::shared_ptr<>
|
||||
#include <string> // for std::string class
|
||||
|
||||
/**
|
||||
* A basic implementation of trie class to store only lower-case strings.
|
||||
* You can extend the implementation to all the ASCII characters by changing the
|
||||
* value of @ ALPHABETS to 128.
|
||||
*/
|
||||
class Trie {
|
||||
private:
|
||||
static constexpr size_t ALPHABETS = 26;
|
||||
|
||||
/**
|
||||
* Structure of trie node.
|
||||
* This struct doesn't need a constructor as we are initializing using
|
||||
* intializer list which is more efficient than if we had done so with
|
||||
* constructor.
|
||||
*/
|
||||
struct TrieNode {
|
||||
// An array of pointers of size 26 which tells if a character of word is
|
||||
// present or not.
|
||||
std::shared_ptr<TrieNode> character[ALPHABETS]{nullptr};
|
||||
|
||||
bool isEndOfWord{false};
|
||||
};
|
||||
|
||||
/**
|
||||
* Function to check if a node has some children which can form words.
|
||||
* @param node whose character array of pointers need to be checked for
|
||||
* children.
|
||||
* @return `true` if a child is found
|
||||
* @return `false` if a child is not found
|
||||
*/
|
||||
inline static bool hasChildren(std::shared_ptr<TrieNode> node) {
|
||||
for (size_t i = 0; i < ALPHABETS; i++) {
|
||||
if (node->character[i]) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* A recursive helper function to remove a word from the trie. First, it
|
||||
* recursively traverses to the location of last character of word in the
|
||||
* trie. However, if the word is not found, the function returns a runtime
|
||||
* error. Upon successfully reaching the last character of word in trie, if
|
||||
* sets the isEndOfWord to false and deletes the node if and only if it has
|
||||
* no children, else it returns the current node.
|
||||
* @param word is the string which needs to be removed from trie.
|
||||
* @param curr is the current node we are at.
|
||||
* @param index is the index of the @word we are at.
|
||||
* @return if current node has childern, it returns @ curr, else it returns
|
||||
* nullptr.
|
||||
* @throw a runtime error in case @ word is not found in the trie.
|
||||
*/
|
||||
std::shared_ptr<TrieNode> removeWordHelper(const std::string& word,
|
||||
std::shared_ptr<TrieNode> curr,
|
||||
size_t index) {
|
||||
if (word.size() == index) {
|
||||
if (curr->isEndOfWord) {
|
||||
curr->isEndOfWord = false;
|
||||
}
|
||||
if (hasChildren(curr)) {
|
||||
return curr;
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
size_t idx = word[index] - 'a';
|
||||
|
||||
// Throw a runtime error in case the user enters a word which is not
|
||||
// present in the trie.
|
||||
if (!curr->character[idx]) {
|
||||
throw std::runtime_error(std::move(std::string("Word not found.")));
|
||||
}
|
||||
|
||||
curr->character[idx] =
|
||||
removeWordHelper(word, curr->character[idx], index + 1);
|
||||
|
||||
// This if condition checks if the node has some childern.
|
||||
// The 1st if check, i.e. (curr->character[idx]) is checked specifically
|
||||
// because if the older string is a prefix of some other string, then,
|
||||
// there would be no need to check all 26 characters. Example- str1 =
|
||||
// abbey, str2 = abbex and we want to delete string "abbey", then in
|
||||
// this case, there would be no need to check all characters for the
|
||||
// chars a,b,b.
|
||||
if (curr->character[idx] || hasChildren(curr)) {
|
||||
return curr;
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
public:
|
||||
/// constructor to initialise the root of the trie.
|
||||
Trie() : m_root(std::make_shared<TrieNode>()) {}
|
||||
|
||||
/**
|
||||
* Insert a word into the trie.
|
||||
* @param word which needs to be inserted into the string.
|
||||
*/
|
||||
void insert(const std::string& word) {
|
||||
auto curr = m_root;
|
||||
for (char ch : word) {
|
||||
size_t index = ch - 'a';
|
||||
|
||||
// if a node for current word is not already present in trie, create
|
||||
// a new node for it.
|
||||
if (!curr->character[index]) {
|
||||
curr->character[index] = std::make_shared<TrieNode>();
|
||||
}
|
||||
|
||||
curr = curr->character[index];
|
||||
}
|
||||
curr->isEndOfWord = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Search if a word is present in trie or not.
|
||||
* @param word which is needed to be searched in the trie.
|
||||
* @return True if the word is found in trie and isEndOfWord is set to true.
|
||||
* @return False if word is not found in trie or isEndOfWord is set to
|
||||
* false.
|
||||
*/
|
||||
bool search(const std::string& word) {
|
||||
auto curr = m_root;
|
||||
for (char ch : word) {
|
||||
size_t index = ch - 'a';
|
||||
|
||||
// if any node for a character is not found, then return that the
|
||||
// word cannot be formed.
|
||||
if (!curr->character[index]) {
|
||||
return false;
|
||||
}
|
||||
curr = curr->character[index];
|
||||
}
|
||||
return curr->isEndOfWord;
|
||||
}
|
||||
|
||||
// Function to remove the word which calls the helper function.
|
||||
void removeWord(const std::string& word) {
|
||||
m_root = removeWordHelper(word, m_root, 0);
|
||||
}
|
||||
|
||||
private:
|
||||
// data member to store the root of the trie.
|
||||
std::shared_ptr<TrieNode> m_root;
|
||||
};
|
||||
|
||||
/**
|
||||
* Main function
|
||||
*/
|
||||
int main() {
|
||||
Trie trie;
|
||||
trie.insert("hel");
|
||||
trie.insert("hello");
|
||||
trie.removeWord("hel");
|
||||
std::cout << trie.search("hello") << '\n';
|
||||
|
||||
return 0;
|
||||
}
|
||||
87
data_structures/trie_tree.cpp
Normal file
87
data_structures/trie_tree.cpp
Normal file
@@ -0,0 +1,87 @@
|
||||
#include <stdbool.h>
|
||||
#include <stdio.h>
|
||||
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
|
||||
// structure definition
|
||||
typedef struct trie {
|
||||
struct trie* arr[26];
|
||||
bool isEndofWord;
|
||||
} trie;
|
||||
|
||||
// create a new node for trie
|
||||
trie* createNode() {
|
||||
trie* nn = new trie();
|
||||
for (int i = 0; i < 26; i++) nn->arr[i] = NULL;
|
||||
nn->isEndofWord = false;
|
||||
return nn;
|
||||
}
|
||||
|
||||
// insert string into the trie
|
||||
void insert(trie* root, std::string str) {
|
||||
for (int i = 0; i < str.length(); i++) {
|
||||
int j = str[i] - 'a';
|
||||
if (root->arr[j]) {
|
||||
root = root->arr[j];
|
||||
} else {
|
||||
root->arr[j] = createNode();
|
||||
root = root->arr[j];
|
||||
}
|
||||
}
|
||||
root->isEndofWord = true;
|
||||
}
|
||||
|
||||
// search a string exists inside the trie
|
||||
bool search(trie* root, std::string str, int index) {
|
||||
if (index == str.length()) {
|
||||
if (!root->isEndofWord)
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
int j = str[index] - 'a';
|
||||
if (!root->arr[j])
|
||||
return false;
|
||||
return search(root->arr[j], str, index + 1);
|
||||
}
|
||||
|
||||
/*
|
||||
removes the string if it is not a prefix of any other
|
||||
string, if it is then just sets the endofword to false, else
|
||||
removes the given string
|
||||
*/
|
||||
bool deleteString(trie* root, std::string str, int index) {
|
||||
if (index == str.length()) {
|
||||
if (!root->isEndofWord)
|
||||
return false;
|
||||
root->isEndofWord = false;
|
||||
for (int i = 0; i < 26; i++) return false;
|
||||
return true;
|
||||
}
|
||||
int j = str[index] - 'a';
|
||||
if (!root->arr[j])
|
||||
return false;
|
||||
bool var = deleteString(root, str, index + 1);
|
||||
if (var) {
|
||||
root->arr[j] = NULL;
|
||||
if (root->isEndofWord) {
|
||||
return false;
|
||||
} else {
|
||||
int i;
|
||||
for (i = 0; i < 26; i++)
|
||||
if (root->arr[i])
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
int main() {
|
||||
trie* root = createNode();
|
||||
insert(root, "hello");
|
||||
insert(root, "world");
|
||||
int a = search(root, "hello", 0);
|
||||
int b = search(root, "word", 0);
|
||||
printf("%d %d ", a, b);
|
||||
return 0;
|
||||
}
|
||||
Reference in New Issue
Block a user