└── data-structures ├── arrays ├── MyArray.c ├── MyArray.cpp ├── MyArray.java └── my_array.py ├── avl-trees ├── AVLTree.cpp ├── AVLTree.java └── avl_tree.py ├── binary-heaps ├── BinaryHeap.cpp ├── BinaryHeap.java └── binary_heap.c ├── binary-search-trees ├── BST.cpp ├── BST.java └── BST.py ├── binomial-heaps └── BinomialHeaps.cpp ├── doubly-linked-list ├── DoublyLinkedList.cpp ├── DoublyLinkedList.java ├── doubly_linked_list.c └── doubly_linked_list.py ├── dynamic-arrays ├── DynamicArray.cpp └── DynamicArray.java ├── priority-queues ├── PQHeap.cpp ├── PQHeap.java ├── pq_array_ordered.c ├── pq_array_unordered.c └── pq_heap.c ├── queues ├── QueueArray.cpp ├── QueueArray.java ├── QueueLinkedList.cpp ├── QueueLinkedList.java ├── queue_array.c ├── queue_linked_list.c └── queue_linked_list.py ├── red-black-trees ├── RedBlackTree.cpp ├── RedBlackTree.java └── red_black_tree.py ├── singly-linked-list ├── MyLinkedList.cpp ├── MyLinkedList.java ├── my_linked_list.c └── my_linked_list.py ├── splay-trees ├── SplayTree.cpp ├── SplayTree.java └── splay_tree.py ├── stacks ├── MyStack.cpp ├── MyStack.java ├── MyStackLinkedList.cpp ├── MyStackLinkedList.java ├── my_stack.c ├── my_stack.py └── my_stack_linked_list.c └── treaps ├── Treap.cpp └── a.out /data-structures/arrays/MyArray.c: -------------------------------------------------------------------------------- 1 | // array declaration and operations 2 | #include 3 | 4 | // prints the array 5 | void print(int a[], int n) { 6 | int i; 7 | for (i = 0; i < n; i++) { 8 | printf("%d ", a[i]); 9 | } 10 | printf("\n"); 11 | } 12 | 13 | int main() { 14 | int i; 15 | // declares initializes 1d array of 12 integers 16 | int a[12]; 17 | 18 | // keeps track of current number of items in the array 19 | int n = 0; 20 | 21 | // initialize first 10 items (takes O(n) time) 22 | for (i = 0; i < 10; i++) { 23 | a[i] = i + 1; 24 | n = n + 1; 25 | } 26 | 27 | // print and see if it has all 10 items 28 | print(a, n); // prints 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 29 | 30 | // read the item in 5th position (position starts from 0) 31 | printf("%d\n", a[5]); // prints 6 32 | 33 | // write 12 in first position 34 | a[0] = 12; 35 | 36 | // print to see the change 37 | print(a, n); // prints 12, 2, 3, 4, 5, 6, 7, 8, 9, 10 38 | 39 | // insert 100 to first position 40 | for (i = n; i >= 0; i--) { 41 | a[i + 1] = a[i]; // move one step to right 42 | } 43 | 44 | a[0] = 100; // write 100 in first position 45 | n = n + 1; 46 | 47 | // print to verify 48 | print(a, n); // prints 100 12 2 3 4 5 6 7 8 9 10 49 | 50 | // remove the item in the first position 51 | for(i = 0; i < n; i++) { 52 | a[i] = a[i + 1]; 53 | } 54 | 55 | n = n - 1; 56 | 57 | // print to verify 58 | print(a, n); // prints 12 2 3 4 5 6 7 8 9 10 59 | 60 | return 0; 61 | } -------------------------------------------------------------------------------- /data-structures/arrays/MyArray.cpp: -------------------------------------------------------------------------------- 1 | // array declaration and operations 2 | #include 3 | 4 | using namespace std; 5 | 6 | // prints the array 7 | void print(int a[], int n) { 8 | int i; 9 | for (i = 0; i < n; i++) { 10 | cout<= 0; i--) { 43 | a[i + 1] = a[i]; // move one step to right 44 | } 45 | 46 | a[0] = 100; // write 100 in first position 47 | n = n + 1; 48 | 49 | // print to verify 50 | print(a, n); // prints 100 12 2 3 4 5 6 7 8 9 10 51 | 52 | // remove the item in the first position 53 | for(i = 0; i < n; i++) { 54 | a[i] = a[i + 1]; 55 | } 56 | 57 | n = n - 1; 58 | 59 | // print to verify 60 | print(a, n); // prints 12 2 3 4 5 6 7 8 9 10 61 | 62 | return 0; 63 | } -------------------------------------------------------------------------------- /data-structures/arrays/MyArray.java: -------------------------------------------------------------------------------- 1 | // array declaration and operations 2 | 3 | public class MyArray { 4 | private int [] a; 5 | private int n; 6 | 7 | public MyArray() { 8 | a = new int[12]; 9 | n = 0; 10 | } 11 | 12 | public void initialize() { 13 | for (int i = 0; i < 10; i++) { 14 | a[i] = i+1; 15 | } 16 | n = 10; 17 | } 18 | 19 | // print the array 20 | public void print() { 21 | for (int i = 0; i < n; i++) { 22 | System.out.print(a[i] + " "); 23 | } 24 | System.out.println(); 25 | } 26 | 27 | public int get(int i) { 28 | return a[i]; 29 | } 30 | 31 | public void set(int position, int value) { 32 | a[position] = value; 33 | } 34 | 35 | public void insert(int position, int value) { 36 | for (int i = n; i >= position; i--) { 37 | a[i + 1] = a[i]; 38 | } 39 | a[position] = value; 40 | n = n + 1; 41 | } 42 | 43 | public void delete(int position) { 44 | for(int i = 0; i < n; i++) { 45 | a[i] = a[i + 1]; 46 | } 47 | n = n - 1; 48 | } 49 | 50 | public static void main(String [] args) { 51 | MyArray arr = new MyArray(); 52 | 53 | // initialize the array (takes O(n) time) 54 | arr.initialize(); 55 | 56 | // print to verify 57 | arr.print(); // prints 1 2 3 4 5 6 7 8 9 10 58 | 59 | // read the item in 5th position (position starts from 0) 60 | System.out.println(arr.get(5)); // prints 6 61 | 62 | // write 12 in first position 63 | arr.set(0, 12); // prints 12 2 3 4 5 6 7 8 9 10 64 | 65 | // print to verify 66 | arr.print(); // 12 2 3 4 5 6 7 8 9 10 67 | 68 | // insert 100 in first position 69 | arr.insert(0, 100); // 100 12 2 3 4 5 6 7 8 9 10 70 | 71 | // print to verify 72 | arr.print(); 73 | 74 | // remove item in first position 75 | arr.delete(0); // 12 2 3 4 5 6 7 8 9 10 76 | 77 | // print to verify 78 | arr.print(); 79 | } 80 | } -------------------------------------------------------------------------------- /data-structures/arrays/my_array.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Bibeknam/algorithmtutorprograms/bbbc4ff16b15a2fd50308c996e236d124a024b85/data-structures/arrays/my_array.py -------------------------------------------------------------------------------- /data-structures/avl-trees/AVLTree.cpp: -------------------------------------------------------------------------------- 1 | // AVL tree implementation in C++ 2 | // Author: Algorithm Tutor 3 | 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | // data structure that represents a node in the tree 10 | struct Node { 11 | int data; // holds the key 12 | Node *parent; // pointer to the parent 13 | Node *left; // pointer to left child 14 | Node *right; // pointer to right child 15 | int bf; // balance factor of the node 16 | }; 17 | 18 | typedef Node *NodePtr; 19 | 20 | // class AVLTree implements the operations in AVL tree 21 | class AVLTree { 22 | private: 23 | NodePtr root; 24 | 25 | // initializes the nodes with appropirate values 26 | // all the pointers are set to point to the null pointer 27 | void initializeNode(NodePtr node, int key) { 28 | node->data = key; 29 | node->parent = nullptr; 30 | node->left = nullptr; 31 | node->right = nullptr; 32 | node->bf = 0; 33 | } 34 | 35 | void preOrderHelper(NodePtr node) { 36 | if (node != nullptr) { 37 | cout<data<<" "; 38 | preOrderHelper(node->left); 39 | preOrderHelper(node->right); 40 | } 41 | } 42 | 43 | void inOrderHelper(NodePtr node) { 44 | if (node != nullptr) { 45 | inOrderHelper(node->left); 46 | cout<data<<" "; 47 | inOrderHelper(node->right); 48 | } 49 | } 50 | 51 | void postOrderHelper(NodePtr node) { 52 | if (node != nullptr) { 53 | postOrderHelper(node->left); 54 | postOrderHelper(node->right); 55 | cout<data<<" "; 56 | } 57 | } 58 | 59 | NodePtr searchTreeHelper(NodePtr node, int key) { 60 | if (node == nullptr || key == node->data) { 61 | return node; 62 | } 63 | 64 | if (key < node->data) { 65 | return searchTreeHelper(node->left, key); 66 | } 67 | return searchTreeHelper(node->right, key); 68 | } 69 | 70 | NodePtr deleteNodeHelper(NodePtr node, int key) { 71 | // search the key 72 | if (node == nullptr) return node; 73 | else if (key < node->data) node->left = deleteNodeHelper(node->left, key); 74 | else if (key > node->data) node->right = deleteNodeHelper(node->right, key); 75 | else { 76 | // the key has been found, now delete it 77 | 78 | // case 1: node is a leaf node 79 | if (node->left == nullptr && node->right == nullptr) { 80 | delete node; 81 | node = nullptr; 82 | } 83 | 84 | // case 2: node has only one child 85 | else if (node->left == nullptr) { 86 | NodePtr temp = node; 87 | node = node->right; 88 | delete temp; 89 | } 90 | 91 | else if (node->right == nullptr) { 92 | NodePtr temp = node; 93 | node = node->left; 94 | delete temp; 95 | } 96 | 97 | // case 3: has both children 98 | else { 99 | NodePtr temp = minimum(node->right); 100 | node->data = temp->data; 101 | node->right = deleteNodeHelper(node->right, temp->data); 102 | } 103 | 104 | } 105 | 106 | // Write the update balance logic here 107 | // YOUR CODE HERE 108 | 109 | return node; 110 | } 111 | 112 | 113 | 114 | 115 | // update the balance factor the node 116 | void updateBalance(NodePtr node) { 117 | if (node->bf < -1 || node->bf > 1) { 118 | rebalance(node); 119 | return; 120 | } 121 | 122 | if (node->parent != nullptr) { 123 | if (node == node->parent->left) { 124 | node->parent->bf -= 1; 125 | } 126 | 127 | if (node == node->parent->right) { 128 | node->parent->bf += 1; 129 | } 130 | 131 | if (node->parent->bf != 0) { 132 | updateBalance(node->parent); 133 | } 134 | } 135 | } 136 | 137 | // rebalance the tree 138 | void rebalance(NodePtr node) { 139 | if (node->bf > 0) { 140 | if (node->right->bf < 0) { 141 | rightRotate(node->right); 142 | leftRotate(node); 143 | } else { 144 | leftRotate(node); 145 | } 146 | } else if (node->bf < 0) { 147 | if (node->left->bf > 0) { 148 | leftRotate(node->left); 149 | rightRotate(node); 150 | } else { 151 | rightRotate(node); 152 | } 153 | } 154 | } 155 | 156 | void printHelper(NodePtr root, string indent, bool last) { 157 | // print the tree structure on the screen 158 | if (root != nullptr) { 159 | cout<data<<"( BF = "<bf<<")"<left, indent, false); 171 | printHelper(root->right, indent, true); 172 | } 173 | } 174 | 175 | public: 176 | AVLTree() { 177 | root = nullptr; 178 | } 179 | 180 | // Pre-Order traversal 181 | // Node->Left Subtree->Right Subtree 182 | void preorder() { 183 | preOrderHelper(this->root); 184 | } 185 | 186 | // In-Order traversal 187 | // Left Subtree -> Node -> Right Subtree 188 | void inorder() { 189 | inOrderHelper(this->root); 190 | } 191 | 192 | // Post-Order traversal 193 | // Left Subtree -> Right Subtree -> Node 194 | void postorder() { 195 | postOrderHelper(this->root); 196 | } 197 | 198 | // search the tree for the key k 199 | // and return the corresponding node 200 | NodePtr searchTree(int k) { 201 | return searchTreeHelper(this->root, k); 202 | } 203 | 204 | // find the node with the minimum key 205 | NodePtr minimum(NodePtr node) { 206 | while (node->left != nullptr) { 207 | node = node->left; 208 | } 209 | return node; 210 | } 211 | 212 | // find the node with the maximum key 213 | NodePtr maximum(NodePtr node) { 214 | while (node->right != nullptr) { 215 | node = node->right; 216 | } 217 | return node; 218 | } 219 | 220 | // find the successor of a given node 221 | NodePtr successor(NodePtr x) { 222 | // if the right subtree is not null, 223 | // the successor is the leftmost node in the 224 | // right subtree 225 | if (x->right != nullptr) { 226 | return minimum(x->right); 227 | } 228 | 229 | // else it is the lowest ancestor of x whose 230 | // left child is also an ancestor of x. 231 | NodePtr y = x->parent; 232 | while (y != nullptr && x == y->right) { 233 | x = y; 234 | y = y->parent; 235 | } 236 | return y; 237 | } 238 | 239 | // find the predecessor of a given node 240 | NodePtr predecessor(NodePtr x) { 241 | // if the left subtree is not null, 242 | // the predecessor is the rightmost node in the 243 | // left subtree 244 | if (x->left != nullptr) { 245 | return maximum(x->left); 246 | } 247 | 248 | NodePtr y = x->parent; 249 | while (y != nullptr && x == y->left) { 250 | x = y; 251 | y = y->parent; 252 | } 253 | 254 | return y; 255 | } 256 | 257 | // rotate left at node x 258 | void leftRotate(NodePtr x) { 259 | NodePtr y = x->right; 260 | x->right = y->left; 261 | if (y->left != nullptr) { 262 | y->left->parent = x; 263 | } 264 | y->parent = x->parent; 265 | if (x->parent == nullptr) { 266 | this->root = y; 267 | } else if (x == x->parent->left) { 268 | x->parent->left = y; 269 | } else { 270 | x->parent->right = y; 271 | } 272 | y->left = x; 273 | x->parent = y; 274 | 275 | // update the balance factor 276 | x->bf = x->bf - 1 - max(0, y->bf); 277 | y->bf = y->bf - 1 + min(0, x->bf); 278 | } 279 | 280 | // rotate right at node x 281 | void rightRotate(NodePtr x) { 282 | NodePtr y = x->left; 283 | x->left = y->right; 284 | if (y->right != nullptr) { 285 | y->right->parent = x; 286 | } 287 | y->parent = x->parent; 288 | if (x->parent == nullptr) { 289 | this->root = y; 290 | } else if (x == x->parent->right) { 291 | x->parent->right = y; 292 | } else { 293 | x->parent->left = y; 294 | } 295 | y->right = x; 296 | x->parent = y; 297 | 298 | // update the balance factor 299 | x->bf = x->bf + 1 - min(0, y->bf); 300 | y->bf = y->bf + 1 + max(0, x->bf); 301 | } 302 | 303 | // insert the key to the tree in its appropriate position 304 | void insert(int key) { 305 | // PART 1: Ordinary BST insert 306 | NodePtr node = new Node; 307 | node->parent = nullptr; 308 | node->left = nullptr; 309 | node->right = nullptr; 310 | node->data = key; 311 | node->bf = 0; 312 | NodePtr y = nullptr; 313 | NodePtr x = this->root; 314 | 315 | while (x != nullptr) { 316 | y = x; 317 | if (node->data < x->data) { 318 | x = x->left; 319 | } else { 320 | x = x->right; 321 | } 322 | } 323 | 324 | // y is parent of x 325 | node->parent = y; 326 | if (y == nullptr) { 327 | root = node; 328 | } else if (node->data < y->data) { 329 | y->left = node; 330 | } else { 331 | y->right = node; 332 | } 333 | 334 | // PART 2: re-balance the node if necessary 335 | updateBalance(node); 336 | 337 | } 338 | 339 | NodePtr getRoot(){ 340 | return this->root; 341 | } 342 | 343 | // delete the node from the tree 344 | NodePtr deleteNode(int data) { 345 | NodePtr deletedNode = deleteNodeHelper(this->root, data); 346 | return deletedNode; 347 | } 348 | 349 | // print the tree structure on the screen 350 | void prettyPrint() { 351 | printHelper(this->root, "", true); 352 | } 353 | 354 | }; 355 | 356 | int main() { 357 | AVLTree bst; 358 | // bst.createSampleTree1(); 359 | bst.insert(50); 360 | bst.insert(30); 361 | bst.insert(70); 362 | bst.insert(23); 363 | bst.prettyPrint(); 364 | return 0; 365 | } -------------------------------------------------------------------------------- /data-structures/avl-trees/AVLTree.java: -------------------------------------------------------------------------------- 1 | // AVL Binary search tree implementation in Java 2 | // Author: AlgorithmTutor 3 | 4 | // data structure that represents a node in the tree 5 | class Node { 6 | int data; // holds the key 7 | Node parent; // pointer to the parent 8 | Node left; // pointer to left child 9 | Node right; // pointer to right child 10 | int bf; // balance factor of the node 11 | 12 | public Node(int data) { 13 | this.data = data; 14 | this.parent = null; 15 | this.left = null; 16 | this.right = null; 17 | this.bf = 0; 18 | } 19 | } 20 | 21 | public class AVLTree { 22 | private Node root; 23 | 24 | public AVLTree() { 25 | root = null; 26 | } 27 | 28 | private void printHelper(Node currPtr, String indent, boolean last) { 29 | // print the tree structure on the screen 30 | if (currPtr != null) { 31 | System.out.print(indent); 32 | if (last) { 33 | System.out.print("R----"); 34 | indent += " "; 35 | } else { 36 | System.out.print("L----"); 37 | indent += "| "; 38 | } 39 | 40 | System.out.println(currPtr.data + "(BF = " + currPtr.bf + ")"); 41 | 42 | printHelper(currPtr.left, indent, false); 43 | printHelper(currPtr.right, indent, true); 44 | } 45 | } 46 | 47 | private Node searchTreeHelper(Node node, int key) { 48 | if (node == null || key == node.data) { 49 | return node; 50 | } 51 | 52 | if (key < node.data) { 53 | return searchTreeHelper(node.left, key); 54 | } 55 | return searchTreeHelper(node.right, key); 56 | } 57 | 58 | private Node deleteNodeHelper(Node node, int key) { 59 | // search the key 60 | if (node == null) return node; 61 | else if (key < node.data) node.left = deleteNodeHelper(node.left, key); 62 | else if (key > node.data) node.right = deleteNodeHelper(node.right, key); 63 | else { 64 | // the key has been found, now delete it 65 | 66 | // case 1: node is a leaf node 67 | if (node.left == null && node.right == null) { 68 | node = null; 69 | } 70 | 71 | // case 2: node has only one child 72 | else if (node.left == null) { 73 | Node temp = node; 74 | node = node.right; 75 | } 76 | 77 | else if (node.right == null) { 78 | Node temp = node; 79 | node = node.left; 80 | } 81 | 82 | // case 3: has both children 83 | else { 84 | Node temp = minimum(node.right); 85 | node.data = temp.data; 86 | node.right = deleteNodeHelper(node.right, temp.data); 87 | } 88 | 89 | } 90 | 91 | // Write the update balance logic here 92 | // YOUR CODE HERE 93 | 94 | return node; 95 | } 96 | 97 | // update the balance factor the node 98 | private void updateBalance(Node node) { 99 | if (node.bf < -1 || node.bf > 1) { 100 | rebalance(node); 101 | return; 102 | } 103 | 104 | if (node.parent != null) { 105 | if (node == node.parent.left) { 106 | node.parent.bf -= 1; 107 | } 108 | 109 | if (node == node.parent.right) { 110 | node.parent.bf += 1; 111 | } 112 | 113 | if (node.parent.bf != 0) { 114 | updateBalance(node.parent); 115 | } 116 | } 117 | } 118 | 119 | // rebalance the tree 120 | void rebalance(Node node) { 121 | if (node.bf > 0) { 122 | if (node.right.bf < 0) { 123 | rightRotate(node.right); 124 | leftRotate(node); 125 | } else { 126 | leftRotate(node); 127 | } 128 | } else if (node.bf < 0) { 129 | if (node.left.bf > 0) { 130 | leftRotate(node.left); 131 | rightRotate(node); 132 | } else { 133 | rightRotate(node); 134 | } 135 | } 136 | } 137 | 138 | 139 | private void preOrderHelper(Node node) { 140 | if (node != null) { 141 | System.out.print(node.data + " "); 142 | preOrderHelper(node.left); 143 | preOrderHelper(node.right); 144 | } 145 | } 146 | 147 | private void inOrderHelper(Node node) { 148 | if (node != null) { 149 | inOrderHelper(node.left); 150 | System.out.print(node.data + " "); 151 | inOrderHelper(node.right); 152 | } 153 | } 154 | 155 | private void postOrderHelper(Node node) { 156 | if (node != null) { 157 | postOrderHelper(node.left); 158 | postOrderHelper(node.right); 159 | System.out.print(node.data + " "); 160 | } 161 | } 162 | 163 | // Pre-Order traversal 164 | // Node.Left Subtree.Right Subtree 165 | public void preorder() { 166 | preOrderHelper(this.root); 167 | } 168 | 169 | // In-Order traversal 170 | // Left Subtree . Node . Right Subtree 171 | public void inorder() { 172 | inOrderHelper(this.root); 173 | } 174 | 175 | // Post-Order traversal 176 | // Left Subtree . Right Subtree . Node 177 | public void postorder() { 178 | postOrderHelper(this.root); 179 | } 180 | 181 | // search the tree for the key k 182 | // and return the corresponding node 183 | public Node searchTree(int k) { 184 | return searchTreeHelper(this.root, k); 185 | } 186 | 187 | // find the node with the minimum key 188 | public Node minimum(Node node) { 189 | while (node.left != null) { 190 | node = node.left; 191 | } 192 | return node; 193 | } 194 | 195 | // find the node with the maximum key 196 | public Node maximum(Node node) { 197 | while (node.right != null) { 198 | node = node.right; 199 | } 200 | return node; 201 | } 202 | 203 | // find the successor of a given node 204 | public Node successor(Node x) { 205 | // if the right subtree is not null, 206 | // the successor is the leftmost node in the 207 | // right subtree 208 | if (x.right != null) { 209 | return minimum(x.right); 210 | } 211 | 212 | // else it is the lowest ancestor of x whose 213 | // left child is also an ancestor of x. 214 | Node y = x.parent; 215 | while (y != null && x == y.right) { 216 | x = y; 217 | y = y.parent; 218 | } 219 | return y; 220 | } 221 | 222 | // find the predecessor of a given node 223 | public Node predecessor(Node x) { 224 | // if the left subtree is not null, 225 | // the predecessor is the rightmost node in the 226 | // left subtree 227 | if (x.left != null) { 228 | return maximum(x.left); 229 | } 230 | 231 | Node y = x.parent; 232 | while (y != null && x == y.left) { 233 | x = y; 234 | y = y.parent; 235 | } 236 | 237 | return y; 238 | } 239 | 240 | // rotate left at node x 241 | void leftRotate(Node x) { 242 | Node y = x.right; 243 | x.right = y.left; 244 | if (y.left != null) { 245 | y.left.parent = x; 246 | } 247 | y.parent = x.parent; 248 | if (x.parent == null) { 249 | this.root = y; 250 | } else if (x == x.parent.left) { 251 | x.parent.left = y; 252 | } else { 253 | x.parent.right = y; 254 | } 255 | y.left = x; 256 | x.parent = y; 257 | 258 | // update the balance factor 259 | x.bf = x.bf - 1 - Math.max(0, y.bf); 260 | y.bf = y.bf - 1 + Math.min(0, x.bf); 261 | } 262 | 263 | // rotate right at node x 264 | void rightRotate(Node x) { 265 | Node y = x.left; 266 | x.left = y.right; 267 | if (y.right != null) { 268 | y.right.parent = x; 269 | } 270 | y.parent = x.parent; 271 | if (x.parent == null) { 272 | this.root = y; 273 | } else if (x == x.parent.right) { 274 | x.parent.right = y; 275 | } else { 276 | x.parent.left = y; 277 | } 278 | y.right = x; 279 | x.parent = y; 280 | 281 | // update the balance factor 282 | x.bf = x.bf + 1 - Math.min(0, y.bf); 283 | y.bf = y.bf + 1 + Math.max(0, x.bf); 284 | } 285 | 286 | 287 | // insert the key to the tree in its appropriate position 288 | public void insert(int key) { 289 | // PART 1: Ordinary BST insert 290 | Node node = new Node(key); 291 | Node y = null; 292 | Node x = this.root; 293 | 294 | while (x != null) { 295 | y = x; 296 | if (node.data < x.data) { 297 | x = x.left; 298 | } else { 299 | x = x.right; 300 | } 301 | } 302 | 303 | // y is parent of x 304 | node.parent = y; 305 | if (y == null) { 306 | root = node; 307 | } else if (node.data < y.data) { 308 | y.left = node; 309 | } else { 310 | y.right = node; 311 | } 312 | 313 | // PART 2: re-balance the node if necessary 314 | updateBalance(node); 315 | } 316 | 317 | // delete the node from the tree 318 | Node deleteNode(int data) { 319 | return deleteNodeHelper(this.root, data); 320 | } 321 | 322 | // print the tree structure on the screen 323 | public void prettyPrint() { 324 | printHelper(this.root, "", true); 325 | } 326 | 327 | public static void main(String [] args) { 328 | AVLTree bst = new AVLTree(); 329 | bst.insert(1); 330 | bst.insert(2); 331 | bst.insert(3); 332 | bst.insert(4); 333 | bst.insert(5); 334 | bst.insert(6); 335 | bst.insert(7); 336 | bst.insert(8); 337 | bst.prettyPrint(); 338 | } 339 | } -------------------------------------------------------------------------------- /data-structures/avl-trees/avl_tree.py: -------------------------------------------------------------------------------- 1 | # AVL Binary search tree implementation in Python 2 | # Author: AlgorithmTutor 3 | 4 | # data structure that represents a node in the tree 5 | 6 | import sys 7 | 8 | class Node: 9 | def __init__(self, data): 10 | self.data = data 11 | self.parent = None 12 | self.left = None 13 | self.right = None 14 | self.bf = 0 15 | 16 | class AVLTree: 17 | 18 | def __init__(self): 19 | self.root = None 20 | 21 | def __printHelper(self, currPtr, indent, last): 22 | # print the tree structure on the screen 23 | if currPtr != None: 24 | sys.stdout.write(indent) 25 | if last: 26 | sys.stdout.write("R----") 27 | indent += " " 28 | else: 29 | sys.stdout.write("L----") 30 | indent += "| " 31 | 32 | print currPtr.data 33 | 34 | self.__printHelper(currPtr.left, indent, False) 35 | self.__printHelper(currPtr.right, indent, True) 36 | 37 | def __searchTreeHelper(self, node, key): 38 | if node == None or key == node.data: 39 | return node 40 | 41 | if key < node.data: 42 | return self.__searchTreeHelper(node.left, key) 43 | return self.__searchTreeHelper(node.right, key) 44 | 45 | def __deleteNodeHelper(self, node, key): 46 | # search the key 47 | if node == None: 48 | return node 49 | elif key < node.data: 50 | node.left = self.__deleteNodeHelper(node.left, key) 51 | elif key > node.data: 52 | node.right = self.__deleteNodeHelper(node.right, key) 53 | else: 54 | # the key has been found, now delete it 55 | 56 | # case 1: node is a leaf node 57 | if node.left == None and node.right == None: 58 | node = None 59 | 60 | # case 2: node has only one child 61 | elif node.left == None: 62 | temp = node 63 | node = node.right 64 | 65 | elif node.right == None: 66 | temp = node 67 | node = node.left 68 | 69 | # case 3: has both children 70 | else: 71 | temp = minimum(node.right) 72 | node.data = temp.data 73 | node.right = self.__deleteNodeHelper(node.right, temp.data) 74 | 75 | # Write the update balance logic here 76 | # YOUR CODE HERE 77 | return node 78 | 79 | # update the balance factor the node 80 | def __updateBalance(self, node): 81 | if node.bf < -1 or node.bf > 1: 82 | self.__rebalance(node) 83 | return; 84 | 85 | if node.parent != None: 86 | if node == node.parent.left: 87 | node.parent.bf -= 1 88 | 89 | if node == node.parent.right: 90 | node.parent.bf += 1 91 | 92 | if node.parent.bf != 0: 93 | self.__updateBalance(node.parent) 94 | 95 | # rebalance the tree 96 | def __rebalance(self, node): 97 | if node.bf > 0: 98 | if node.right.bf < 0: 99 | self.rightRotate(node.right) 100 | self.leftRotate(node) 101 | else: 102 | self.leftRotate(node) 103 | elif node.bf < 0: 104 | if node.left.bf > 0: 105 | self.leftRotate(node.left) 106 | self.rightRotate(node) 107 | else: 108 | rightRotate(node) 109 | 110 | def __preOrderHelper(self, node): 111 | if node != None: 112 | sys.stdout.write(node.data + " ") 113 | self.__preOrderHelper(node.left) 114 | self.__preOrderHelper(node.right) 115 | 116 | def __inOrderHelper(self, node): 117 | if node != None: 118 | self.__inOrderHelper(node.left) 119 | sys.stdout.write(node.data + " ") 120 | self.__inOrderHelper(node.right) 121 | 122 | def __postOrderHelper(self, node): 123 | if node != None: 124 | self.__postOrderHelper(node.left) 125 | self.__postOrderHelper(node.right) 126 | std.out.write(node.data + " ") 127 | 128 | # Pre-Order traversal 129 | # Node->Left Subtree->Right Subtree 130 | def preorder(self): 131 | self.__preOrderHelper(self.root) 132 | 133 | # In-Order traversal 134 | # Left Subtree -> Node -> Right Subtree 135 | def __inorder(self): 136 | self.__inOrderHelper(self.root) 137 | 138 | # Post-Order traversal 139 | # Left Subtree -> Right Subtree -> Node 140 | def __postorder(self): 141 | self.__postOrderHelper(self.root) 142 | 143 | # search the tree for the key k 144 | # and return the corresponding node 145 | def searchTree(self, k): 146 | return self.__searchTreeHelper(self.root, k) 147 | 148 | # find the node with the minimum key 149 | def minimum(self, node): 150 | while node.left != None: 151 | node = node.left 152 | return node 153 | 154 | # find the node with the maximum key 155 | def maximum(self, node): 156 | while node.right != None: 157 | node = node.right 158 | return node 159 | 160 | # find the successor of a given node 161 | def successor(self, x): 162 | # if the right subtree is not null, 163 | # the successor is the leftmost node in the 164 | # right subtree 165 | if x.right != None: 166 | return self.minimum(x.right) 167 | 168 | # else it is the lowest ancestor of x whose 169 | # left child is also an ancestor of x. 170 | y = x.parent 171 | while y != None and x == y.right: 172 | x = y 173 | y = y.parent 174 | return y 175 | 176 | # find the predecessor of a given node 177 | def predecessor(self, x): 178 | # if the left subtree is not null, 179 | # the predecessor is the rightmost node in the 180 | # left subtree 181 | if x.left != None: 182 | return self.maximum(x.left) 183 | 184 | y = x.parent 185 | while y != None and x == y.left: 186 | x = y 187 | y = y.parent 188 | return y 189 | 190 | # rotate left at node x 191 | def leftRotate(self, x): 192 | y = x.right 193 | x.right = y.left 194 | if y.left != None: 195 | y.left.parent = x 196 | 197 | y.parent = x.parent; 198 | if x.parent == None: 199 | self.root = y 200 | elif x == x.parent.left: 201 | x.parent.left = y 202 | else: 203 | x.parent.right = y 204 | y.left = x 205 | x.parent = y 206 | 207 | # update the balance factor 208 | x.bf = x.bf - 1 - max(0, y.bf) 209 | y.bf = y.bf - 1 + min(0, x.bf) 210 | 211 | # rotate right at node x 212 | def rightRotate(self, x): 213 | y = x.left 214 | x.left = y.right; 215 | if y.right != None: 216 | y.right.parent = x 217 | 218 | y.parent = x.parent; 219 | if x.parent == None: 220 | self.root = y 221 | elif x == x.parent.right: 222 | x.parent.right = y 223 | else: 224 | x.parent.left = y 225 | 226 | y.right = x 227 | x.parent = y 228 | 229 | # update the balance factor 230 | x.bf = x.bf + 1 - min(0, y.bf) 231 | y.bf = y.bf + 1 + max(0, x.bf) 232 | 233 | # insert the key to the tree in its appropriate position 234 | def insert(self, key): 235 | # PART 1: Ordinary BST insert 236 | node = Node(key) 237 | y = None 238 | x = self.root 239 | 240 | while x != None: 241 | y = x 242 | if node.data < x.data: 243 | x = x.left 244 | else: 245 | x = x.right 246 | 247 | # y is parent of x 248 | node.parent = y 249 | if y == None: 250 | self.root = node 251 | elif node.data < y.data: 252 | y.left = node 253 | else: 254 | y.right = node 255 | 256 | # PART 2: re-balance the node if necessary 257 | self.__updateBalance(node) 258 | 259 | 260 | # delete the node from the tree 261 | def deleteNode(self, data): 262 | return self.__deleteNodeHelper(self.root, data) 263 | 264 | # print the tree structure on the screen 265 | def prettyPrint(self): 266 | self.__printHelper(self.root, "", True) 267 | 268 | if __name__ == '__main__': 269 | bst = AVLTree() 270 | bst.insert(1) 271 | bst.insert(2) 272 | bst.insert(3) 273 | bst.insert(4) 274 | bst.insert(5) 275 | bst.insert(6) 276 | bst.insert(7) 277 | bst.insert(8) 278 | bst.prettyPrint() -------------------------------------------------------------------------------- /data-structures/binary-heaps/BinaryHeap.cpp: -------------------------------------------------------------------------------- 1 | // C++ implementation of a binary heap 2 | 3 | #include 4 | using namespace std; 5 | 6 | class BinaryHeap { 7 | private: 8 | const static int MAX_SIZE = 15; 9 | int heap[MAX_SIZE]; 10 | int size; 11 | 12 | public: 13 | BinaryHeap() { 14 | size = 0; 15 | } 16 | 17 | // returns the index of the parent node 18 | static int parent(int i) { 19 | return (i - 1) / 2; 20 | } 21 | 22 | // return the index of the left child 23 | static int leftChild(int i) { 24 | return 2*i + 1; 25 | } 26 | 27 | // return the index of the right child 28 | static int rightChild(int i) { 29 | return 2*i + 2; 30 | } 31 | 32 | 33 | static void swap(int *x, int *y) { 34 | int temp = *x; 35 | *x = *y; 36 | *y = temp; 37 | } 38 | 39 | // insert the item at the appropriate position 40 | void insert(int data) { 41 | if (size >= MAX_SIZE) { 42 | cout<<"The heap is full. Cannot insert"< heap[largest]) { 74 | largest = left; 75 | } 76 | 77 | // check if the right node is larger than the current node 78 | // and left node 79 | if (right <= size && heap[right] > heap[largest]) { 80 | largest = right; 81 | } 82 | 83 | // swap the largest node with the current node 84 | // and repeat this process until the current node is larger than 85 | // the right and the left node 86 | if (largest != i) { 87 | int temp = heap[i]; 88 | heap[i] = heap[largest]; 89 | heap[largest] = temp; 90 | maxHeapify(largest); 91 | } 92 | 93 | } 94 | 95 | // returns the maximum item of the heap 96 | int getMax() { 97 | return heap[0]; 98 | } 99 | 100 | // deletes the max item and return 101 | int extractMax() { 102 | int maxItem = heap[0]; 103 | 104 | // replace the first item with the last item 105 | heap[0] = heap[size - 1]; 106 | size = size - 1; 107 | 108 | // maintain the heap property by heapifying the 109 | // first item 110 | maxHeapify(0); 111 | return maxItem; 112 | } 113 | 114 | // prints the heap 115 | void printHeap() { 116 | for (int i = 0; i < size; i++) { 117 | cout<= MAX_SIZE) { 31 | System.out.println("The heap is full. Cannot insert"); 32 | return; 33 | } 34 | 35 | // first insert the time at the last position of the array 36 | // and move it up 37 | heap[size] = data; 38 | size = size + 1; 39 | 40 | 41 | // move up until the heap property satisfies 42 | int i = size - 1; 43 | while (i != 0 && heap[BinaryHeap.parent(i)] < heap[i]) { 44 | int temp = heap[i]; 45 | heap[i] = heap[parent(i)]; 46 | heap[parent(i)] = temp; 47 | i = BinaryHeap.parent(i); 48 | } 49 | } 50 | 51 | // moves the item at position i of array a 52 | // into its appropriate position 53 | public void maxHeapify(int i){ 54 | // find left child node 55 | int left = BinaryHeap.leftChild(i); 56 | 57 | // find right child node 58 | int right = BinaryHeap.rightChild(i); 59 | 60 | // find the largest among 3 nodes 61 | int largest = i; 62 | 63 | // check if the left node is larger than the current node 64 | if (left <= size && heap[left] > heap[largest]) { 65 | largest = left; 66 | } 67 | 68 | // check if the right node is larger than the current node 69 | // and left node 70 | if (right <= size && heap[right] > heap[largest]) { 71 | largest = right; 72 | } 73 | 74 | // swap the largest node with the current node 75 | // and repeat this process until the current node is larger than 76 | // the right and the left node 77 | if (largest != i) { 78 | int temp = heap[i]; 79 | heap[i] = heap[largest]; 80 | heap[largest] = temp; 81 | maxHeapify(largest); 82 | } 83 | 84 | } 85 | 86 | // returns the maximum item of the heap 87 | public int getMax() { 88 | return heap[0]; 89 | } 90 | 91 | // deletes the max item and return 92 | public int extractMax() { 93 | int maxItem = heap[0]; 94 | 95 | // replace the first item with the last item 96 | heap[0] = heap[size - 1]; 97 | size = size - 1; 98 | 99 | // maintain the heap property by heapifying the 100 | // first item 101 | maxHeapify(0); 102 | return maxItem; 103 | } 104 | 105 | // prints the heap 106 | public void printHeap() { 107 | for (int i = 0; i < size; i++) { 108 | System.out.print(heap[i] + " "); 109 | } 110 | System.out.println(); 111 | } 112 | 113 | public static void main(String [] args) { 114 | BinaryHeap heap = new BinaryHeap(); 115 | } 116 | } -------------------------------------------------------------------------------- /data-structures/binary-heaps/binary_heap.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #define MAX_SIZE 15 4 | 5 | // returns the index of the parent node 6 | int parent(int i) { 7 | return (i - 1) / 2; 8 | } 9 | 10 | // return the index of the left child 11 | int left_child(int i) { 12 | return 2*i + 1; 13 | } 14 | 15 | // return the index of the right child 16 | int right_child(int i) { 17 | return 2*i + 2; 18 | } 19 | 20 | void swap(int *x, int *y) { 21 | int temp = *x; 22 | *x = *y; 23 | *y = temp; 24 | } 25 | 26 | // insert the item at the appropriate position 27 | void insert(int a[], int data, int *n) { 28 | if (*n >= MAX_SIZE) { 29 | printf("%s\n", "The heap is full. Cannot insert"); 30 | return; 31 | } 32 | // first insert the time at the last position of the array 33 | // and move it up 34 | a[*n] = data; 35 | *n = *n + 1; 36 | 37 | 38 | // move up until the heap property satisfies 39 | int i = *n - 1; 40 | while (i != 0 && a[parent(i)] < a[i]) { 41 | swap(&a[parent(i)], &a[i]); 42 | i = parent(i); 43 | } 44 | } 45 | 46 | // moves the item at position i of array a 47 | // into its appropriate position 48 | void max_heapify(int a[], int i, int n){ 49 | // find left child node 50 | int left = left_child(i); 51 | 52 | // find right child node 53 | int right = right_child(i); 54 | 55 | // find the largest among 3 nodes 56 | int largest = i; 57 | 58 | // check if the left node is larger than the current node 59 | if (left <= n && a[left] > a[largest]) { 60 | largest = left; 61 | } 62 | 63 | // check if the right node is larger than the current node 64 | if (right <= n && a[right] > a[largest]) { 65 | largest = right; 66 | } 67 | 68 | // swap the largest node with the current node 69 | // and repeat this process until the current node is larger than 70 | // the right and the left node 71 | if (largest != i) { 72 | int temp = a[i]; 73 | a[i] = a[largest]; 74 | a[largest] = temp; 75 | max_heapify(a, largest, n); 76 | } 77 | 78 | } 79 | 80 | // converts an array into a heap 81 | void build_max_heap(int a[], int n) { 82 | int i; 83 | for (i = n/2; i >= 0; i--) { 84 | max_heapify(a, i, n); 85 | } 86 | } 87 | 88 | // returns the maximum item of the heap 89 | int get_max(int a[]) { 90 | return a[0]; 91 | } 92 | 93 | // deletes the max item and return 94 | int extract_max(int a[], int *n) { 95 | int max_item = a[0]; 96 | 97 | // replace the first item with the last item 98 | a[0] = a[*n - 1]; 99 | *n = *n - 1; 100 | 101 | // maintain the heap property by heapifying the 102 | // first item 103 | max_heapify(a, 0, *n); 104 | return max_item; 105 | } 106 | 107 | // prints the heap 108 | void print_heap(int a[], int n) { 109 | int i; 110 | for (i = 0; i < n; i++) { 111 | printf("%d\n", a[i]); 112 | } 113 | printf("\n"); 114 | } 115 | 116 | 117 | int main() { 118 | int n = 10; 119 | int a[MAX_SIZE]; 120 | a[1] = 10; a[2] = 12; a[3] = 9; a[4] = 78; a[5] = 33; a[6] = 21; a[7] = 35; a[8] = 29; a[9] = 5; a[10] = 66; 121 | build_max_heap(a, n); 122 | insert(a, 55, &n); 123 | insert(a, 56, &n); 124 | insert(a, 57, &n); 125 | insert(a, 58, &n); 126 | insert(a, 100, &n); 127 | print_heap(a, n); 128 | return 0; 129 | } -------------------------------------------------------------------------------- /data-structures/binary-search-trees/BST.cpp: -------------------------------------------------------------------------------- 1 | // Binary search tree implementation in C++ 2 | // Author: Algorithm Tutor 3 | 4 | #include 5 | 6 | using namespace std; 7 | 8 | // data structure that represents a node in the tree 9 | struct Node { 10 | int data; // holds the key 11 | Node *parent; // pointer to the parent 12 | Node *left; // pointer to left child 13 | Node *right; // pointer to right child 14 | }; 15 | 16 | typedef Node *NodePtr; 17 | 18 | // class BST implements the operations in BST 19 | class BST { 20 | private: 21 | NodePtr root; 22 | 23 | // initializes the nodes with appropirate values 24 | // all the pointers are set to point to the null pointer 25 | void initializeNode(NodePtr node, int key) { 26 | node->data = key; 27 | node->parent = nullptr; 28 | node->left = nullptr; 29 | node->right = nullptr; 30 | } 31 | 32 | void preOrderHelper(NodePtr node) { 33 | if (node != nullptr) { 34 | cout<data<<" "; 35 | preOrderHelper(node->left); 36 | preOrderHelper(node->right); 37 | } 38 | } 39 | 40 | void inOrderHelper(NodePtr node) { 41 | if (node != nullptr) { 42 | inOrderHelper(node->left); 43 | cout<data<<" "; 44 | inOrderHelper(node->right); 45 | } 46 | } 47 | 48 | void postOrderHelper(NodePtr node) { 49 | if (node != nullptr) { 50 | postOrderHelper(node->left); 51 | postOrderHelper(node->right); 52 | cout<data<<" "; 53 | } 54 | } 55 | 56 | NodePtr searchTreeHelper(NodePtr node, int key) { 57 | if (node == nullptr || key == node->data) { 58 | return node; 59 | } 60 | 61 | if (key < node->data) { 62 | return searchTreeHelper(node->left, key); 63 | } 64 | return searchTreeHelper(node->right, key); 65 | } 66 | 67 | NodePtr deleteNodeHelper(NodePtr node, int key) { 68 | // search the key 69 | if (node == nullptr) return node; 70 | else if (key < node->data) node->left = deleteNodeHelper(node->left, key); 71 | else if (key > node->data) node->right = deleteNodeHelper(node->right, key); 72 | else { 73 | // the key has been found, now delete it 74 | 75 | // case 1: node is a leaf node 76 | if (node->left == nullptr && node->right == nullptr) { 77 | delete node; 78 | node = nullptr; 79 | } 80 | 81 | // case 2: node has only one child 82 | else if (node->left == nullptr) { 83 | NodePtr temp = node; 84 | node = node->right; 85 | delete temp; 86 | } 87 | 88 | else if (node->right == nullptr) { 89 | NodePtr temp = node; 90 | node = node->left; 91 | delete temp; 92 | } 93 | 94 | // case 3: has both children 95 | else { 96 | NodePtr temp = minimum(node->right); 97 | node->data = temp->data; 98 | node->right = deleteNodeHelper(node->right, temp->data); 99 | } 100 | 101 | } 102 | return node; 103 | } 104 | 105 | void printHelper(NodePtr root, string indent, bool last) { 106 | // print the tree structure on the screen 107 | if (root != nullptr) { 108 | cout<data<left, indent, false); 120 | printHelper(root->right, indent, true); 121 | } 122 | } 123 | 124 | public: 125 | BST() { 126 | root = nullptr; 127 | } 128 | 129 | void createSampleTree1() { 130 | NodePtr node50 = new Node; 131 | initializeNode(node50, 50); 132 | NodePtr node30 = new Node; 133 | initializeNode(node30, 30); 134 | NodePtr node70 = new Node; 135 | initializeNode(node70, 70); 136 | 137 | node30->parent = node50; 138 | node70->parent = node50; 139 | node50->left = node30; 140 | node50->right = node70; 141 | 142 | NodePtr node23 = new Node; 143 | initializeNode(node23, 23); 144 | NodePtr node35 = new Node; 145 | initializeNode(node35, 35); 146 | 147 | node23->parent = node30; 148 | node35->parent = node30; 149 | node30->left = node23; 150 | node30->right = node35; 151 | 152 | NodePtr node11 = new Node; 153 | initializeNode(node11, 11); 154 | NodePtr node25 = new Node; 155 | initializeNode(node25, 25); 156 | 157 | node11->parent = node23; 158 | node25->parent = node23; 159 | node23->left = node11; 160 | node23->right = node25; 161 | 162 | NodePtr node31 = new Node; 163 | initializeNode(node31, 31); 164 | NodePtr node42 = new Node; 165 | initializeNode(node42, 42); 166 | 167 | node31->parent = node35; 168 | node42->parent = node35; 169 | node35->left = node31; 170 | node35->right = node42; 171 | 172 | NodePtr node80 = new Node; 173 | initializeNode(node80, 80); 174 | 175 | node80->parent = node70; 176 | node70->right = node80; 177 | 178 | NodePtr node73 = new Node; 179 | initializeNode(node73, 73); 180 | NodePtr node85 = new Node; 181 | initializeNode(node85, 85); 182 | 183 | node73->parent = node80; 184 | node85->parent = node80; 185 | node80->left = node73; 186 | node80->right = node85; 187 | 188 | this->root = node50; 189 | } 190 | 191 | // Pre-Order traversal 192 | // Node->Left Subtree->Right Subtree 193 | void preorder() { 194 | preOrderHelper(this->root); 195 | } 196 | 197 | // In-Order traversal 198 | // Left Subtree -> Node -> Right Subtree 199 | void inorder() { 200 | inOrderHelper(this->root); 201 | } 202 | 203 | // Post-Order traversal 204 | // Left Subtree -> Right Subtree -> Node 205 | void postorder() { 206 | postOrderHelper(this->root); 207 | } 208 | 209 | // search the tree for the key k 210 | // and return the corresponding node 211 | NodePtr searchTree(int k) { 212 | return searchTreeHelper(this->root, k); 213 | } 214 | 215 | // find the node with the minimum key 216 | NodePtr minimum(NodePtr node) { 217 | while (node->left != nullptr) { 218 | node = node->left; 219 | } 220 | return node; 221 | } 222 | 223 | // find the node with the maximum key 224 | NodePtr maximum(NodePtr node) { 225 | while (node->right != nullptr) { 226 | node = node->right; 227 | } 228 | return node; 229 | } 230 | 231 | // find the successor of a given node 232 | NodePtr successor(NodePtr x) { 233 | // if the right subtree is not null, 234 | // the successor is the leftmost node in the 235 | // right subtree 236 | if (x->right != nullptr) { 237 | return minimum(x->right); 238 | } 239 | 240 | // else it is the lowest ancestor of x whose 241 | // left child is also an ancestor of x. 242 | NodePtr y = x->parent; 243 | while (y != nullptr && x == y->right) { 244 | x = y; 245 | y = y->parent; 246 | } 247 | return y; 248 | } 249 | 250 | // find the predecessor of a given node 251 | NodePtr predecessor(NodePtr x) { 252 | // if the left subtree is not null, 253 | // the predecessor is the rightmost node in the 254 | // left subtree 255 | if (x->left != nullptr) { 256 | return maximum(x->left); 257 | } 258 | 259 | NodePtr y = x->parent; 260 | while (y != nullptr && x == y->left) { 261 | x = y; 262 | y = y->parent; 263 | } 264 | 265 | return y; 266 | } 267 | 268 | // insert the key to the tree in its appropriate position 269 | void insert(int key) { 270 | NodePtr node = new Node; 271 | node->parent = nullptr; 272 | node->left = nullptr; 273 | node->right = nullptr; 274 | node->data = key; 275 | NodePtr y = nullptr; 276 | NodePtr x = this->root; 277 | 278 | while (x != nullptr) { 279 | y = x; 280 | if (node->data < x->data) { 281 | x = x->left; 282 | } else { 283 | x = x->right; 284 | } 285 | } 286 | 287 | // y is parent of x 288 | node->parent = y; 289 | if (y == nullptr) { 290 | root = node; 291 | } else if (node->data < y->data) { 292 | y->left = node; 293 | } else { 294 | y->right = node; 295 | } 296 | } 297 | 298 | NodePtr getRoot(){ 299 | return this->root; 300 | } 301 | 302 | // delete the node from the tree 303 | NodePtr deleteNode(int data) { 304 | return deleteNodeHelper(this->root, data); 305 | } 306 | 307 | // print the tree structure on the screen 308 | void prettyPrint() { 309 | printHelper(this->root, "", true); 310 | } 311 | 312 | }; 313 | 314 | int main() { 315 | BST bst; 316 | bst.createSampleTree1(); 317 | bst.prettyPrint(); 318 | return 0; 319 | } 320 | 321 | // // replace the subtree rooted at node u with the subtree 322 | // // rooted at node v. 323 | // void transplant(NodePtr u, NodePtr v){ 324 | // if (u->parent == nullptr) { 325 | // root = v; 326 | // } else if (u == u->parent->left) { 327 | // u->parent->left = v; 328 | // } else{ 329 | // u->parent->right = v; 330 | // } 331 | 332 | // if (v != nullptr) { 333 | // v->parent = u->parent; 334 | // } 335 | // } 336 | 337 | // // delete node x 338 | // void deleteNodeHelper(NodePtr x, int key) { 339 | // if (x->left == nullptr) { 340 | // transplant(x, x->right); 341 | // } else if (x->right == nullptr) { 342 | // transplant(x, x->left); 343 | // } else { 344 | // y = minimum(x->right); 345 | // if (y->parent != x) { 346 | // transplant(y, y->right); 347 | // y->right = x->right; 348 | // y->right->parent = y; 349 | // } 350 | // transplant(x, y); 351 | // y->left = x->left; 352 | // y->left->parent = y; 353 | // } 354 | 355 | // // fix the tree after the deletion 356 | // } -------------------------------------------------------------------------------- /data-structures/binary-search-trees/BST.java: -------------------------------------------------------------------------------- 1 | // Binary search tree implementation in Java 2 | // Author: AlgorithmTutor 3 | 4 | // data structure that represents a node in the tree 5 | class Node { 6 | int data; // holds the key 7 | Node parent; // pointer to the parent 8 | Node left; // pointer to left child 9 | Node right; // pointer to right child 10 | 11 | public Node(int data) { 12 | this.data = data; 13 | this.parent = null; 14 | this.left = null; 15 | this.right = null; 16 | } 17 | } 18 | 19 | public class BST { 20 | private Node root; 21 | 22 | public BST() { 23 | root = null; 24 | } 25 | 26 | public void createSampleTree1() { 27 | Node node50 = new Node(50); 28 | Node node30 = new Node(30); 29 | Node node70 = new Node(70); 30 | 31 | node30.parent = node50; 32 | node70.parent = node50; 33 | node50.left = node30; 34 | node50.right = node70; 35 | 36 | Node node23 = new Node(23); 37 | Node node35 = new Node(35); 38 | 39 | node23.parent = node30; 40 | node35.parent = node30; 41 | node30.left = node23; 42 | node30.right = node35; 43 | 44 | Node node11 = new Node(11); 45 | Node node25 = new Node(25); 46 | 47 | node11.parent = node23; 48 | node25.parent = node23; 49 | node23.left = node11; 50 | node23.right = node25; 51 | 52 | Node node31 = new Node(31); 53 | Node node42 = new Node(42); 54 | 55 | node31.parent = node35; 56 | node42.parent = node35; 57 | node35.left = node31; 58 | node35.right = node42; 59 | 60 | Node node80 = new Node(80); 61 | 62 | node80.parent = node70; 63 | node70.right = node80; 64 | 65 | Node node73 = new Node(73); 66 | Node node85 = new Node(85); 67 | 68 | node73.parent = node80; 69 | node85.parent = node80; 70 | node80.left = node73; 71 | node80.right = node85; 72 | 73 | this.root = node50; 74 | } 75 | 76 | private void printHelper(Node currPtr, String indent, boolean last) { 77 | // print the tree structure on the screen 78 | if (currPtr != null) { 79 | System.out.print(indent); 80 | if (last) { 81 | System.out.print("R----"); 82 | indent += " "; 83 | } else { 84 | System.out.print("L----"); 85 | indent += "| "; 86 | } 87 | 88 | System.out.println(currPtr.data); 89 | 90 | printHelper(currPtr.left, indent, false); 91 | printHelper(currPtr.right, indent, true); 92 | } 93 | } 94 | 95 | private Node searchTreeHelper(Node node, int key) { 96 | if (node == null || key == node.data) { 97 | return node; 98 | } 99 | 100 | if (key < node.data) { 101 | return searchTreeHelper(node.left, key); 102 | } 103 | return searchTreeHelper(node.right, key); 104 | } 105 | 106 | private Node deleteNodeHelper(Node node, int key) { 107 | // search the key 108 | if (node == null) return node; 109 | else if (key < node.data) node.left = deleteNodeHelper(node.left, key); 110 | else if (key > node.data) node.right = deleteNodeHelper(node.right, key); 111 | else { 112 | // the key has been found, now delete it 113 | 114 | // case 1: node is a leaf node 115 | if (node.left == null && node.right == null) { 116 | node = null; 117 | } 118 | 119 | // case 2: node has only one child 120 | else if (node.left == null) { 121 | Node temp = node; 122 | node = node.right; 123 | } 124 | 125 | else if (node.right == null) { 126 | Node temp = node; 127 | node = node.left; 128 | } 129 | 130 | // case 3: has both children 131 | else { 132 | Node temp = minimum(node.right); 133 | node.data = temp.data; 134 | node.right = deleteNodeHelper(node.right, temp.data); 135 | } 136 | 137 | } 138 | return node; 139 | } 140 | 141 | private void preOrderHelper(Node node) { 142 | if (node != null) { 143 | System.out.print(node.data + " "); 144 | preOrderHelper(node.left); 145 | preOrderHelper(node.right); 146 | } 147 | } 148 | 149 | private void inOrderHelper(Node node) { 150 | if (node != null) { 151 | inOrderHelper(node.left); 152 | System.out.print(node.data + " "); 153 | inOrderHelper(node.right); 154 | } 155 | } 156 | 157 | private void postOrderHelper(Node node) { 158 | if (node != null) { 159 | postOrderHelper(node.left); 160 | postOrderHelper(node.right); 161 | System.out.print(node.data + " "); 162 | } 163 | } 164 | 165 | // Pre-Order traversal 166 | // Node->Left Subtree->Right Subtree 167 | public void preorder() { 168 | preOrderHelper(this.root); 169 | } 170 | 171 | // In-Order traversal 172 | // Left Subtree -> Node -> Right Subtree 173 | public void inorder() { 174 | inOrderHelper(this.root); 175 | } 176 | 177 | // Post-Order traversal 178 | // Left Subtree -> Right Subtree -> Node 179 | public void postorder() { 180 | postOrderHelper(this.root); 181 | } 182 | 183 | // search the tree for the key k 184 | // and return the corresponding node 185 | public Node searchTree(int k) { 186 | return searchTreeHelper(this.root, k); 187 | } 188 | 189 | // find the node with the minimum key 190 | public Node minimum(Node node) { 191 | while (node.left != null) { 192 | node = node.left; 193 | } 194 | return node; 195 | } 196 | 197 | // find the node with the maximum key 198 | public Node maximum(Node node) { 199 | while (node.right != null) { 200 | node = node.right; 201 | } 202 | return node; 203 | } 204 | 205 | // find the successor of a given node 206 | public Node successor(Node x) { 207 | // if the right subtree is not null, 208 | // the successor is the leftmost node in the 209 | // right subtree 210 | if (x.right != null) { 211 | return minimum(x.right); 212 | } 213 | 214 | // else it is the lowest ancestor of x whose 215 | // left child is also an ancestor of x. 216 | Node y = x.parent; 217 | while (y != null && x == y.right) { 218 | x = y; 219 | y = y.parent; 220 | } 221 | return y; 222 | } 223 | 224 | // find the predecessor of a given node 225 | public Node predecessor(Node x) { 226 | // if the left subtree is not null, 227 | // the predecessor is the rightmost node in the 228 | // left subtree 229 | if (x.left != null) { 230 | return maximum(x.left); 231 | } 232 | 233 | Node y = x.parent; 234 | while (y != null && x == y.left) { 235 | x = y; 236 | y = y.parent; 237 | } 238 | 239 | return y; 240 | } 241 | 242 | // insert the key to the tree in its appropriate position 243 | public void insert(int key) { 244 | Node node = new Node(key); 245 | Node y = null; 246 | Node x = this.root; 247 | 248 | while (x != null) { 249 | y = x; 250 | if (node.data < x.data) { 251 | x = x.left; 252 | } else { 253 | x = x.right; 254 | } 255 | } 256 | 257 | // y is parent of x 258 | node.parent = y; 259 | if (y == null) { 260 | root = node; 261 | } else if (node.data < y.data) { 262 | y.left = node; 263 | } else { 264 | y.right = node; 265 | } 266 | } 267 | 268 | // delete the node from the tree 269 | Node deleteNode(int data) { 270 | return deleteNodeHelper(this.root, data); 271 | } 272 | 273 | // print the tree structure on the screen 274 | public void prettyPrint() { 275 | printHelper(this.root, "", true); 276 | } 277 | 278 | public static void main(String [] args) { 279 | BST tree = new BST(); 280 | tree.createSampleTree1(); 281 | Node n = tree.deleteNode(35); 282 | tree.prettyPrint(); 283 | } 284 | } -------------------------------------------------------------------------------- /data-structures/binary-search-trees/BST.py: -------------------------------------------------------------------------------- 1 | # Binary search tree implementation in Java 2 | # Author: AlgorithmTutor 3 | 4 | # data structure that represents a node in the tree 5 | 6 | import sys 7 | 8 | class Node: 9 | def __init__(self, data): 10 | self.data = data 11 | self.parent = None 12 | self.left = None 13 | self.right = None 14 | 15 | class BST: 16 | 17 | def __init__(self): 18 | self.root = None 19 | 20 | def createSampleTree1(self): 21 | node50 = Node(50) 22 | node30 = Node(30) 23 | node70 = Node(70) 24 | 25 | node30.parent = node50 26 | node70.parent = node50 27 | node50.left = node30 28 | node50.right = node70 29 | 30 | node23 = Node(23) 31 | node35 = Node(35) 32 | 33 | node23.parent = node30 34 | node35.parent = node30 35 | node30.left = node23 36 | node30.right = node35 37 | 38 | node11 = Node(11) 39 | node25 = Node(25) 40 | 41 | node11.parent = node23 42 | node25.parent = node23 43 | node23.left = node11 44 | node23.right = node25 45 | 46 | node31 = Node(31) 47 | node42 = Node(42) 48 | 49 | node31.parent = node35 50 | node42.parent = node35 51 | node35.left = node31 52 | node35.right = node42 53 | 54 | node80 = Node(80) 55 | 56 | node80.parent = node70 57 | node70.right = node80 58 | 59 | node73 = Node(73) 60 | node85 = Node(85) 61 | 62 | node73.parent = node80 63 | node85.parent = node80 64 | node80.left = node73 65 | node80.right = node85 66 | 67 | self.root = node50 68 | 69 | def __printHelper(self, currPtr, indent, last): 70 | # print the tree structure on the screen 71 | if currPtr != None: 72 | sys.stdout.write(indent) 73 | if last: 74 | sys.stdout.write("R----") 75 | indent += " " 76 | else: 77 | sys.stdout.write("L----") 78 | indent += "| " 79 | 80 | print currPtr.data 81 | 82 | self.__printHelper(currPtr.left, indent, False) 83 | self.__printHelper(currPtr.right, indent, True) 84 | 85 | def __searchTreeHelper(self, node, key): 86 | if node == None or key == node.data: 87 | return node 88 | 89 | if key < node.data: 90 | return self.__searchTreeHelper(node.left, key) 91 | return self.__searchTreeHelper(node.right, key) 92 | 93 | def __deleteNodeHelper(self, node, key): 94 | # search the key 95 | if node == None: 96 | return node 97 | elif key < node.data: 98 | node.left = self.__deleteNodeHelper(node.left, key) 99 | elif key > node.data: 100 | node.right = self.__deleteNodeHelper(node.right, key) 101 | else: 102 | # the key has been found, now delete it 103 | 104 | # case 1: node is a leaf node 105 | if node.left == None and node.right == None: 106 | node = None 107 | 108 | # case 2: node has only one child 109 | elif node.left == None: 110 | temp = node 111 | node = node.right 112 | 113 | elif node.right == None: 114 | temp = node 115 | node = node.left 116 | 117 | # case 3: has both children 118 | else: 119 | temp = minimum(node.right) 120 | node.data = temp.data 121 | node.right = self.__deleteNodeHelper(node.right, temp.data) 122 | return node 123 | 124 | def __preOrderHelper(self, node): 125 | if node != None: 126 | sys.stdout.write(node.data + " ") 127 | self.__preOrderHelper(node.left) 128 | self.__preOrderHelper(node.right) 129 | 130 | def __inOrderHelper(self, node): 131 | if node != None: 132 | self.__inOrderHelper(node.left) 133 | sys.stdout.write(node.data + " ") 134 | self.__inOrderHelper(node.right) 135 | 136 | def __postOrderHelper(self, node): 137 | if node != None: 138 | self.__postOrderHelper(node.left) 139 | self.__postOrderHelper(node.right) 140 | std.out.write(node.data + " ") 141 | 142 | # Pre-Order traversal 143 | # Node->Left Subtree->Right Subtree 144 | def preorder(self): 145 | self.__preOrderHelper(self.root) 146 | 147 | # In-Order traversal 148 | # Left Subtree -> Node -> Right Subtree 149 | def __inorder(self): 150 | self.__inOrderHelper(self.root) 151 | 152 | # Post-Order traversal 153 | # Left Subtree -> Right Subtree -> Node 154 | def __postorder(self): 155 | self.__postOrderHelper(self.root) 156 | 157 | # search the tree for the key k 158 | # and return the corresponding node 159 | def searchTree(self, k): 160 | return self.__searchTreeHelper(self.root, k) 161 | 162 | # find the node with the minimum key 163 | def minimum(self, node): 164 | while node.left != None: 165 | node = node.left 166 | return node 167 | 168 | # find the node with the maximum key 169 | def maximum(self, node): 170 | while node.right != None: 171 | node = node.right 172 | return node 173 | 174 | # find the successor of a given node 175 | def successor(self, x): 176 | # if the right subtree is not null, 177 | # the successor is the leftmost node in the 178 | # right subtree 179 | if x.right != None: 180 | return self.minimum(x.right) 181 | 182 | # else it is the lowest ancestor of x whose 183 | # left child is also an ancestor of x. 184 | y = x.parent 185 | while y != None and x == y.right: 186 | x = y 187 | y = y.parent 188 | return y 189 | 190 | # find the predecessor of a given node 191 | def predecessor(self, x): 192 | # if the left subtree is not null, 193 | # the predecessor is the rightmost node in the 194 | # left subtree 195 | if x.left != None: 196 | return self.maximum(x.left) 197 | 198 | y = x.parent 199 | while y != None and x == y.left: 200 | x = y 201 | y = y.parent 202 | return y 203 | 204 | # insert the key to the tree in its appropriate position 205 | def insert(self, key): 206 | node = Node(key) 207 | y = None 208 | x = self.root 209 | 210 | while x != None: 211 | y = x 212 | if node.data < x.data: 213 | x = x.left 214 | else: 215 | x = x.right 216 | 217 | # y is parent of x 218 | node.parent = y 219 | if y == None: 220 | self.root = node 221 | elif node.data < y.data: 222 | y.left = node 223 | else: 224 | y.right = node 225 | 226 | # delete the node from the tree 227 | def deleteNode(self, data): 228 | return self.__deleteNodeHelper(self.root, data) 229 | 230 | # print the tree structure on the screen 231 | def prettyPrint(self): 232 | self.__printHelper(self.root, "", True) 233 | 234 | if __name__ == '__main__': 235 | tree = BST() 236 | tree.createSampleTree1() 237 | tree.prettyPrint() -------------------------------------------------------------------------------- /data-structures/binomial-heaps/BinomialHeaps.cpp: -------------------------------------------------------------------------------- 1 | // Implementation of a binomial heaps using C++ 2 | // author: Algorithm Tutor 3 | // Tutorial URL: https://algorithmtutor.com/Data-Structures/Tree/Binomial-Heaps/ 4 | // Limitation: Many extreme cases are not checked. Not suitable for production use. 5 | 6 | #include 7 | #include 8 | #include 9 | #include 10 | using namespace std; 11 | 12 | // node data structure 13 | struct Node { 14 | int data; // contains the key 15 | int degree; // number of children 16 | Node *p; // pointer to parent 17 | Node *child; // pointer to the leftmost child 18 | Node *sibling; // pointer to the right sibling 19 | }; 20 | 21 | typedef Node *NodePtr; 22 | 23 | 24 | // Class that represents Binomial heap data structure 25 | class BinomialHeap { 26 | private: 27 | // head points to the root of the leftmost binomial tree 28 | NodePtr head; 29 | 30 | // initializes the node with default values 31 | // all pointers are initialized to nullptr 32 | void initializeNode(NodePtr node, int data, int degree) { 33 | node->data = data; 34 | node->degree = degree; 35 | node->p = nullptr; 36 | node->child = nullptr; 37 | node->sibling = nullptr; 38 | } 39 | 40 | // merge two binomial trees of same degree 41 | static void linkBinomialTrees(NodePtr x, NodePtr y) { 42 | // x must be parent of y 43 | y->p = x; 44 | y->sibling = x->child; 45 | x->child = y; 46 | 47 | // increase the degree of x 48 | x->degree += 1; 49 | } 50 | 51 | public: 52 | BinomialHeap() { 53 | head = nullptr; 54 | } 55 | 56 | // find the node with mininum data 57 | NodePtr findMinimum() { 58 | // traverse all the roots and find compare 59 | int min = 999999; 60 | NodePtr currPtr = head; 61 | NodePtr minPtr = nullptr; 62 | 63 | while (currPtr != nullptr) { 64 | if (currPtr->data < min) { 65 | min = currPtr->data; 66 | minPtr = currPtr; 67 | } 68 | currPtr = currPtr->sibling; 69 | } 70 | 71 | return minPtr; 72 | 73 | } 74 | 75 | // create sample heap (given in figure 5) with three trees for testing 76 | void createSampleHeap1() { 77 | // B0 78 | NodePtr node1 = new Node; 79 | initializeNode(node1, 5, 0); 80 | head = node1; 81 | 82 | // B1 83 | NodePtr node2 = new Node; 84 | initializeNode(node2, 17, 1); 85 | NodePtr node3 = new Node; 86 | initializeNode(node3, 27, 0); 87 | node2->child = node3; 88 | node3->p = node2; 89 | 90 | // link B0 and B1 91 | node1->sibling = node2; 92 | 93 | // B3 94 | NodePtr node4 = new Node; 95 | initializeNode(node4, 12, 3); 96 | NodePtr node5 = new Node; 97 | initializeNode(node5, 18, 2); 98 | NodePtr node6 = new Node; 99 | initializeNode(node6, 16, 1); 100 | NodePtr node7 = new Node; 101 | initializeNode(node7, 15, 0); 102 | NodePtr node8 = new Node; 103 | initializeNode(node8, 23, 1); 104 | NodePtr node9 = new Node; 105 | initializeNode(node9, 30, 0); 106 | NodePtr node10 = new Node; 107 | initializeNode(node10, 22, 0); 108 | NodePtr node11 = new Node; 109 | initializeNode(node11, 25, 0); 110 | node4->child = node5; 111 | node5->p = node4; 112 | node6->p = node4; 113 | node7->p = node4; 114 | node5->child = node8; 115 | node5->sibling = node6; 116 | node6->child = node10; 117 | node6->sibling = node7; 118 | node8->p = node5; 119 | node9->p = node5; 120 | node10->p = node6; 121 | node8->child = node11; 122 | node8->sibling = node9; 123 | node11->p = node8; 124 | 125 | // link B1 and B3 126 | node2->sibling = node4; 127 | } 128 | 129 | // create sample heap (given in figure Fig 10 (a)) 130 | void createSampleHeap2() { 131 | // B0 132 | NodePtr node1 = new Node; 133 | initializeNode(node1, 5, 0); 134 | head = node1; 135 | 136 | // B2 137 | NodePtr node2 = new Node; 138 | initializeNode(node2, 6, 2); 139 | NodePtr node3 = new Node; 140 | initializeNode(node3, 12, 1); 141 | NodePtr node4 = new Node; 142 | initializeNode(node4, 34, 0); 143 | NodePtr node5 = new Node; 144 | initializeNode(node5, 33, 0); 145 | node2->child = node3; 146 | node3->p = node2; 147 | node4->p = node2; 148 | node3->child = node5; 149 | node3->sibling = node4; 150 | node5->p = node3; 151 | 152 | // link B0 and B1 153 | node1->sibling = node2; 154 | 155 | // B3 156 | NodePtr node6 = new Node; 157 | initializeNode(node6, 1, 3); 158 | NodePtr node7 = new Node; 159 | initializeNode(node7, 2, 2); 160 | NodePtr node8 = new Node; 161 | initializeNode(node8, 12, 1); 162 | NodePtr node9 = new Node; 163 | initializeNode(node9, 6, 0); 164 | NodePtr node10 = new Node; 165 | initializeNode(node10, 4, 1); 166 | NodePtr node11 = new Node; 167 | initializeNode(node11, 13, 0); 168 | NodePtr node12 = new Node; 169 | initializeNode(node12, 18, 0); 170 | NodePtr node13 = new Node; 171 | initializeNode(node13, 7, 0); 172 | node6->child = node7; 173 | node7->p = node6; 174 | node8->p = node6; 175 | node7->p = node6; 176 | node7->child = node10; 177 | node7->sibling = node8; 178 | node8->child = node12; 179 | node8->sibling = node9; 180 | node10->p = node7; 181 | node11->p = node7; 182 | node12->p = node8; 183 | node10->child = node13; 184 | node10->sibling = node11; 185 | node13->p = node10; 186 | 187 | // link B1 and B3 188 | node2->sibling = node6; 189 | } 190 | 191 | // crete sample heap (given in figure 10 (b)) 192 | void createSampleHeap3() { 193 | // B1 194 | NodePtr node1 = new Node; 195 | initializeNode(node1, 29, 1); 196 | NodePtr node2 = new Node; 197 | initializeNode(node2, 33, 0); 198 | node1->child = node2; 199 | node2->p = node1; 200 | head = node1; 201 | 202 | // B2 203 | NodePtr node3 = new Node; 204 | initializeNode(node3, 21, 2); 205 | NodePtr node4 = new Node; 206 | initializeNode(node4, 23, 1); 207 | NodePtr node5 = new Node; 208 | initializeNode(node5, 78, 0); 209 | NodePtr node6 = new Node; 210 | initializeNode(node6, 50, 0); 211 | node3->child = node4; 212 | node4->p = node3; 213 | node5->p = node3; 214 | node4->child = node6; 215 | node4->sibling = node5; 216 | node6->p = node4; 217 | 218 | // link B1 and B2 219 | node1->sibling = node3; 220 | 221 | } 222 | 223 | // insert a node to the heap 224 | void insert(int data) { 225 | BinomialHeap h; 226 | NodePtr node = new Node; 227 | initializeNode(node, data, 0); 228 | h.setHead(node); 229 | merge(h); 230 | } 231 | 232 | // print the binomial heap with all the trees 233 | void printHeap() { 234 | NodePtr currPtr = head; 235 | while (currPtr != nullptr) { 236 | cout<<"B"<degree<degree)<<" nodes in this tree"< q; 240 | q.push(currPtr); 241 | while (!q.empty()) { 242 | NodePtr p = q.front(); 243 | q.pop(); 244 | cout<data<<" "; 245 | 246 | if (p->child != nullptr) { 247 | NodePtr tempPtr = p->child; 248 | while (tempPtr != nullptr) { 249 | q.push(tempPtr); 250 | tempPtr = tempPtr->sibling; 251 | } 252 | } 253 | } 254 | currPtr = currPtr->sibling; 255 | cout<head = head; 267 | } 268 | 269 | // merge two binomial heaps H and H' 270 | // resulting heap will be H 271 | void merge(BinomialHeap h1) { 272 | NodePtr curr1 = getHead(); 273 | NodePtr curr2 = h1.getHead(); 274 | NodePtr curr3 = nullptr; 275 | NodePtr temp = nullptr; 276 | 277 | if (curr1->degree <= curr2->degree) { 278 | curr3 = curr1; 279 | curr1 = curr1->sibling; 280 | } else { 281 | curr3 = curr2; 282 | curr2 = curr2->sibling; 283 | } 284 | 285 | temp = curr3; 286 | 287 | // merge two heaps without taking care of trees with same degree 288 | // the roots of the tree must be in accending order of degree from 289 | // left to right 290 | while(curr1 != nullptr && curr2 != nullptr) { 291 | if (curr1->degree <= curr2->degree) { 292 | curr3->sibling = curr1; 293 | curr1 = curr1->sibling; 294 | } else { 295 | curr3->sibling = curr2; 296 | curr2 = curr2->sibling; 297 | } 298 | 299 | curr3 = curr3->sibling; 300 | } 301 | 302 | if (curr1 != nullptr) { 303 | // copy all the remaining trees of heap1 304 | while(curr1 != nullptr) { 305 | curr3->sibling = curr1; 306 | curr1 = curr1->sibling; 307 | curr3 = curr3->sibling; 308 | } 309 | } 310 | 311 | if (curr2 != nullptr) { 312 | // copy all the remaining trees of heap2 313 | while(curr2 != nullptr) { 314 | curr3->sibling = curr2; 315 | curr2 = curr2->sibling; 316 | curr3 = curr3->sibling; 317 | } 318 | } 319 | 320 | 321 | // scan the merged list and repeatidly merge binomial trees with same degree 322 | curr3 = temp; 323 | NodePtr prev = nullptr; 324 | NodePtr next = curr3->sibling; 325 | 326 | while (next != nullptr) { 327 | // if two adjacent tree roots have different degree or 3 consecutive roots have same degree 328 | // move to the next tree 329 | if ((curr3->degree != next->degree )|| (next->sibling != nullptr && curr3->degree == next->sibling->degree)) { 330 | prev = curr3; 331 | curr3 = next; 332 | } else { 333 | // otherwise repeatdly merge binomial trees with same degree 334 | if (curr3->data <= next->data) { 335 | curr3->sibling = next->sibling; 336 | BinomialHeap::linkBinomialTrees(curr3, next); 337 | } else { 338 | if (prev == nullptr) { 339 | temp = next; 340 | } else { 341 | prev->sibling = next; 342 | } 343 | 344 | BinomialHeap::linkBinomialTrees(next, curr3); 345 | curr3 = next; 346 | } 347 | } 348 | 349 | next = curr3->sibling; 350 | } 351 | 352 | setHead(temp); 353 | } 354 | 355 | // deletes the smallest node from the heap 356 | NodePtr deleteMin() { 357 | NodePtr curr = head; 358 | NodePtr prevMin = nullptr; 359 | // find the root with minimum key 360 | NodePtr minPtr = nullptr; 361 | NodePtr prevPtr = nullptr; 362 | int min = 999999; 363 | 364 | while (curr != nullptr) { 365 | if (curr->data <= min) { 366 | min = curr->data; 367 | prevMin = prevPtr; 368 | minPtr = curr; 369 | } 370 | prevPtr = curr; 371 | curr = curr->sibling; 372 | } 373 | 374 | // delete the node pointed by minPtr 375 | if (prevMin != nullptr && minPtr->sibling != nullptr) { 376 | prevMin->sibling = minPtr->sibling; 377 | } else if (prevMin != nullptr && minPtr->sibling == nullptr) { 378 | prevMin->sibling = nullptr; 379 | }else if(prevMin == nullptr and minPtr->sibling != nullptr) { 380 | head = minPtr->sibling; 381 | }else if(prevMin == nullptr and minPtr->sibling == nullptr) { 382 | head = nullptr; 383 | } 384 | 385 | // remove parent reference from all its child 386 | NodePtr childPtr = minPtr->child; 387 | while (childPtr != nullptr) { 388 | childPtr->p = nullptr; 389 | childPtr = childPtr->sibling; 390 | } 391 | 392 | // reverse the order 393 | stack s; 394 | childPtr = minPtr->child; 395 | while (childPtr != nullptr) { 396 | s.push(childPtr); 397 | childPtr = childPtr->sibling; 398 | } 399 | 400 | curr = s.top(); 401 | NodePtr temp = curr; 402 | s.pop(); 403 | 404 | while (!s.empty()) { 405 | curr->sibling = s.top(); 406 | s.pop(); 407 | curr = curr->sibling; 408 | } 409 | 410 | curr->sibling = nullptr; 411 | 412 | BinomialHeap h; 413 | h.setHead(temp); 414 | 415 | // merge 416 | merge(h); 417 | 418 | // return the min root 419 | return minPtr; 420 | } 421 | }; 422 | 423 | int main() { 424 | BinomialHeap heap1; 425 | BinomialHeap heap2; 426 | BinomialHeap heap3; 427 | heap1.createSampleHeap2(); 428 | heap2.createSampleHeap3(); 429 | heap1.merge(heap2); 430 | heap1.printHeap(); 431 | heap1.deleteMin(); 432 | heap1.printHeap(); 433 | return 0; 434 | } 435 | -------------------------------------------------------------------------------- /data-structures/doubly-linked-list/DoublyLinkedList.cpp: -------------------------------------------------------------------------------- 1 | // C++ implementation of doubly linked list 2 | #include 3 | 4 | using namespace std; 5 | 6 | // data structure for Node 7 | // data -> the actual value 8 | // next -> address of the next node 9 | struct Node { 10 | int data; 11 | Node *next; 12 | Node *prev; 13 | }; 14 | 15 | typedef Node *NodePtr; 16 | 17 | class MyLinkedList { 18 | private: 19 | NodePtr head; 20 | NodePtr tail; 21 | 22 | public: 23 | MyLinkedList() { 24 | head = nullptr; 25 | tail = nullptr; 26 | 27 | } 28 | 29 | // Insert 'value' at the front of the list 30 | void insertAtFront(int value) { 31 | NodePtr node = new Node; 32 | node->data = value; 33 | node->next = nullptr; 34 | node->prev = nullptr; 35 | 36 | if (isEmpty()) { 37 | head = node; 38 | tail = node; 39 | } else { 40 | node->next = head; 41 | head->prev = node; 42 | head = node; 43 | } 44 | } 45 | 46 | // insert value at the back of the linked list 47 | void insertAtBack(int value) { 48 | NodePtr node = new Node; 49 | node->data = value; 50 | node->next = nullptr; 51 | 52 | if (isEmpty()) { 53 | head = node; 54 | tail = node; 55 | } else { 56 | tail->next = node; 57 | node->prev = tail; 58 | tail = node; 59 | } 60 | } 61 | 62 | // inserts value after key 63 | void insertAfter(int key, int value) { 64 | NodePtr node = new Node; 65 | node->data = value; 66 | node->next = nullptr; 67 | 68 | // find the position of key 69 | NodePtr currPtr = head; 70 | while (currPtr != nullptr && currPtr->data != key) { 71 | currPtr = currPtr->next; 72 | } 73 | 74 | // if key is not there, raise error 75 | if (currPtr == nullptr) { 76 | cout<<"key not found"; 77 | } else if (currPtr->next == nullptr) { 78 | // if key is the last node, insert right after it 79 | currPtr->next = node; 80 | node->prev = currPtr; 81 | tail = node; 82 | } else { 83 | // insert between key and item next to key 84 | NodePtr nextPtr = currPtr->next; 85 | currPtr->next = node; 86 | node->prev = currPtr; 87 | node->next = nextPtr; 88 | nextPtr->prev = node; 89 | } 90 | } 91 | 92 | // returns the data at first node 93 | int topFront() { 94 | if (isEmpty()) { 95 | cout<<"List is empty"<data; 98 | } 99 | } 100 | 101 | // returns the data at last node 102 | int topBack() { 103 | if (isEmpty()) { 104 | cout<<"List is empty"<next == nullptr) { 106 | return head->data; 107 | } else { 108 | NodePtr currPtr = head; 109 | while (currPtr->next != nullptr) { 110 | currPtr = currPtr->next; 111 | } 112 | return currPtr->data; 113 | } 114 | } 115 | 116 | // removes the item at front of the linked list and return 117 | int popFront() { 118 | int item; 119 | if (isEmpty()) { 120 | cout<<"List is empty"<next; 124 | if (nextPtr->next != nullptr) { 125 | nextPtr->prev = nullptr; 126 | } 127 | item = head->data; 128 | // remove head 129 | delete head; 130 | 131 | // make nextptr head 132 | head = nextPtr; 133 | } 134 | 135 | return item; 136 | } 137 | 138 | // remove the item at the list of the linked list and return 139 | int popBack() { 140 | int item; 141 | if (isEmpty()) { 142 | cout<<"List is empty"<data; 146 | NodePtr prev = tail->prev; 147 | if (prev != nullptr) { 148 | prev->next = nullptr; 149 | } 150 | 151 | tail->prev = nullptr; 152 | delete tail; 153 | tail = prev; 154 | } 155 | 156 | return item; 157 | } 158 | 159 | // removes an item with value 'key' 160 | void remove(int key) { 161 | if (isEmpty()) { 162 | cout<<"List is empty"<data != key) { 169 | currPtr = currPtr->next; 170 | } 171 | 172 | if (currPtr == nullptr) { 173 | cout<<"Key is not found in the list"<prev == nullptr) { 178 | // this is the first item 179 | popFront(); 180 | 181 | } else if (currPtr->next == nullptr) { 182 | // this is the last item 183 | popBack(); 184 | } else { 185 | // anywhere in between first and last 186 | NodePtr nextPtr = currPtr->next; 187 | NodePtr prevPtr = currPtr->prev; 188 | nextPtr->prev = prevPtr; 189 | prevPtr->next = nextPtr; 190 | 191 | currPtr->next = nullptr; 192 | currPtr->prev = nullptr; 193 | delete currPtr; 194 | currPtr = nullptr; 195 | } 196 | } 197 | 198 | // print the linked list 199 | void print() { 200 | NodePtr currPtr = head; 201 | while (currPtr != nullptr) { 202 | cout<data<<" "; 203 | currPtr = currPtr->next; 204 | } 205 | cout<data<<" "; 212 | currPtr = currPtr->prev; 213 | } 214 | cout<data != key) { 230 | currPtr = currPtr->next; 231 | } 232 | 233 | if (currPtr == nullptr) { 234 | return false; 235 | } 236 | 237 | return true; 238 | } 239 | }; 240 | 241 | int main() { 242 | MyLinkedList list; 243 | list.insertAtFront(34); 244 | list.insertAtFront(44); 245 | list.insertAtBack(52); 246 | list.insertAtBack(22); 247 | list.printReverse(); 248 | list.insertAfter(22, 33); 249 | list.insertAfter(52, 100); 250 | list.print(); 251 | cout< 3 | #include 4 | 5 | 6 | 7 | // data structure for Node 8 | // data -> the actual value 9 | // next -> address of the next node 10 | struct Node { 11 | int data; 12 | struct Node *next; 13 | struct Node *prev; 14 | }; 15 | 16 | typedef struct Node *NodePtr; 17 | 18 | // global variables head and tail 19 | NodePtr head = NULL; 20 | NodePtr tail = NULL; 21 | 22 | // check if the list is empty 23 | int isEmpty() { 24 | return head == NULL; 25 | } 26 | 27 | // Insert 'value' at the front of the list 28 | void insertAtFront(int value) { 29 | NodePtr node = malloc(sizeof(NodePtr)); 30 | node->data = value; 31 | node->next = NULL; 32 | node->prev = NULL; 33 | 34 | if (isEmpty()) { 35 | head = node; 36 | tail = node; 37 | } else { 38 | node->next = head; 39 | head->prev = node; 40 | head = node; 41 | } 42 | 43 | } 44 | 45 | // insert value at the back of the linked list 46 | void insertAtBack(int value) { 47 | NodePtr node = malloc(sizeof(NodePtr)); 48 | node->data = value; 49 | node->next = NULL; 50 | node->prev = NULL; 51 | 52 | if (isEmpty()) { 53 | head = node; 54 | tail = node; 55 | } else { 56 | tail->next = node; 57 | node->prev = tail; 58 | tail = node; 59 | } 60 | } 61 | 62 | // inserts value after key 63 | NodePtr insertAfter(int key, int value) { 64 | NodePtr node = malloc(sizeof(NodePtr)); 65 | node->data = value; 66 | node->next = NULL; 67 | node->prev = NULL; 68 | 69 | // find the position of key 70 | NodePtr currPtr = head; 71 | while (currPtr != NULL && currPtr->data != key) { 72 | currPtr = currPtr->next; 73 | } 74 | 75 | // if key is not there, raise error 76 | if (currPtr == NULL) { 77 | printf("%s", "key not found"); 78 | } else if (currPtr->next == NULL) { 79 | // if key is the last node, insert right after it 80 | currPtr->next = node; 81 | node->prev = currPtr; 82 | tail = node; 83 | } else { 84 | // insert between key and item next to key 85 | NodePtr nextPtr = currPtr->next; 86 | currPtr->next = node; 87 | node->prev = currPtr; 88 | node->next = nextPtr; 89 | nextPtr->prev = node; 90 | } 91 | } 92 | 93 | // returns the data at first node 94 | int topFront() { 95 | if (isEmpty()) { 96 | printf("%s", "List is empty"); 97 | } else { 98 | return head->data; 99 | } 100 | } 101 | 102 | // returns the data at last node 103 | int topBack() { 104 | if (isEmpty()) { 105 | printf("%s", "List is empty"); 106 | } else if (head->next == NULL) { 107 | return head->data; 108 | } else { 109 | NodePtr currPtr = head; 110 | while (currPtr->next != NULL) { 111 | currPtr = currPtr->next; 112 | } 113 | return currPtr->data; 114 | } 115 | } 116 | 117 | // removes the item at front of the linked list and return 118 | int popFront() { 119 | int item; 120 | if (isEmpty()) { 121 | printf("%s", "List is empty"); 122 | return -99999; 123 | } else { 124 | item = head->data; 125 | if (head->next != NULL) { 126 | head->next->prev = NULL; 127 | } 128 | NodePtr next = head->next; 129 | free(head); 130 | head = next; 131 | } 132 | 133 | return item; 134 | } 135 | 136 | // remove the item at the list of the linked list and return 137 | int popBack() { 138 | int item; 139 | if (isEmpty()) { 140 | printf("%s", "List is empty"); 141 | return -99999; 142 | } else { 143 | item = tail->data; 144 | if (tail->prev != NULL) { 145 | tail->prev->next = NULL; 146 | } 147 | NodePtr prev = tail->prev; 148 | tail->prev = NULL; 149 | free(tail); 150 | tail = prev; 151 | 152 | } 153 | 154 | return item; 155 | } 156 | 157 | // removes an item with value 'key' 158 | void delete(int key) { 159 | if (isEmpty()) { 160 | printf("%s", "List is empty"); 161 | return; 162 | } 163 | 164 | // get to the position of key 165 | NodePtr currPtr = head; 166 | while(currPtr != NULL && currPtr->data != key) { 167 | currPtr = currPtr->next; 168 | } 169 | 170 | if (currPtr == NULL) { 171 | printf("%s", "Key is not found in the list"); 172 | return; 173 | } 174 | 175 | if (currPtr->prev == NULL) { 176 | // this is the first item 177 | popFront(); 178 | 179 | } else if (currPtr->next == NULL) { 180 | // this is the last item 181 | popBack(); 182 | 183 | } else { 184 | // anywhere in between first and last 185 | NodePtr nextPtr = currPtr->next; 186 | NodePtr prevPtr = currPtr->prev; 187 | nextPtr->prev = prevPtr; 188 | prevPtr->next = nextPtr; 189 | currPtr->next = NULL; 190 | currPtr->prev = NULL; 191 | free(currPtr); 192 | currPtr = NULL; 193 | 194 | } 195 | } 196 | 197 | // print the linked list 198 | void print() { 199 | NodePtr currPtr = head; 200 | while (currPtr != NULL) { 201 | printf("%d", currPtr->data); 202 | printf(" "); 203 | currPtr = currPtr->next; 204 | } 205 | printf("\n"); 206 | } 207 | 208 | // print the linked list 209 | void printReverse() { 210 | NodePtr currPtr = tail; 211 | while (currPtr != NULL) { 212 | printf("%d", currPtr->data); 213 | printf(" "); 214 | currPtr = currPtr->prev; 215 | } 216 | printf("\n"); 217 | } 218 | 219 | // check if key is in the list 220 | int find(int key) { 221 | if (isEmpty()) { 222 | return 0; 223 | } 224 | 225 | NodePtr currPtr = head; 226 | while (currPtr != NULL && currPtr->data != key) { 227 | currPtr = currPtr->next; 228 | } 229 | 230 | if (currPtr == NULL) { 231 | return 0; 232 | } 233 | 234 | return 1; 235 | } 236 | 237 | int main() { 238 | insertAtFront(23); 239 | insertAtBack(25); 240 | insertAtBack(44); 241 | insertAfter(25, 39); 242 | insertAfter(25, 233); 243 | insertAfter(44, 45); 244 | print(); 245 | int item = popFront(); 246 | printf("%d\n", item); 247 | print(); 248 | item = popBack(); 249 | printf("%d\n", item); 250 | print(); 251 | delete(233); 252 | print(); 253 | // operations 254 | return 0; 255 | } -------------------------------------------------------------------------------- /data-structures/doubly-linked-list/doubly_linked_list.py: -------------------------------------------------------------------------------- 1 | # Python implementation of Doubly linked list 2 | import sys 3 | 4 | class Node: 5 | def __init__(self, data): 6 | self.data = data 7 | self.next = None 8 | self.prev = None 9 | 10 | class MyLinkedList: 11 | def __init__(self): 12 | self.head = None 13 | self.tail = None 14 | 15 | # Insert 'value' at the front of the list 16 | def insert_at_front(self, value): 17 | node = Node(value) 18 | if self.is_empty(): 19 | self.head = node 20 | self.tail = node 21 | else: 22 | node.next = self.head 23 | self.head.prev = node 24 | self.head = node 25 | 26 | # insert value at the back of the linked list 27 | def insert_at_back(self, value): 28 | node = Node(value) 29 | if self.is_empty(): 30 | self.head = node 31 | self.tail = node 32 | else: 33 | self.tail.next = node 34 | node.prev = self.tail 35 | self.tail = node 36 | 37 | # inserts value after key 38 | def insert_after(self, key, value): 39 | node = Node(value) 40 | 41 | # find the position of key 42 | curr = self.head 43 | while curr != None and curr.data != key: 44 | curr = curr.next 45 | 46 | if curr == None: 47 | print 'Key not found' 48 | return 49 | 50 | if curr.next == None: 51 | curr.next = node 52 | node.prev = curr 53 | self.tail = node 54 | else: 55 | next_node = curr.next 56 | curr.next = node 57 | node.prev = curr 58 | node.next = next_node 59 | next_node.prev = node 60 | 61 | # returns the data at first node 62 | def top_front(self): 63 | if self.is_empty(): 64 | print 'List is empty' 65 | return 66 | 67 | return self.head.data 68 | 69 | # returns the data at last node 70 | def top_back(self): 71 | if self.is_empty(): 72 | print 'List is empty' 73 | return 74 | 75 | return self.tail.data 76 | 77 | # removes the item at front of the linked list and return 78 | def pop_front(self): 79 | if self.is_empty(): 80 | print 'List is empty' 81 | return 82 | 83 | next_node = self.head.next 84 | if (next_node != None): 85 | next_node.prev = None 86 | item = self.head.data 87 | self.head = next_node 88 | return item 89 | 90 | # remove the item at the end of the list and return 91 | def pop_back(self): 92 | if self.is_empty(): 93 | print 'List is empty' 94 | return 95 | 96 | item = self.tail.data 97 | prev = self.tail.prev 98 | 99 | if prev != None: 100 | prev.next = None 101 | 102 | self.tail.prev = None 103 | self.tail = prev 104 | 105 | return item 106 | 107 | # removes an item with value 'key' 108 | def remove(self, key): 109 | if self.is_empty(): 110 | print 'List is empty' 111 | return 112 | 113 | # find the position of the key 114 | curr = self.head 115 | 116 | while curr != None and curr.data != key: 117 | curr = curr.next 118 | 119 | if curr == None: 120 | print 'key not found' 121 | return 122 | 123 | # if curr is head, delete the head 124 | if curr.prev == None: 125 | self.pop_front() 126 | elif curr.next == None: # if curr is last item 127 | self.pop_back() 128 | else: #anywhere between first and last node 129 | next_node = curr.next 130 | prev_node = curr.prev 131 | 132 | prev_node.next = next_node 133 | next_node.prev = prev_node 134 | 135 | curr.next = None 136 | curr.prev = None 137 | curr = None 138 | 139 | # check if the key is in the list 140 | def find(self, key): 141 | if self.is_empty(): 142 | print 'List is empty' 143 | return False 144 | 145 | curr = self.head 146 | while curr != None and curr.data != key: 147 | curr = curr.next 148 | 149 | if curr == None: 150 | return False 151 | 152 | return True 153 | 154 | # check if the list is empty 155 | def is_empty(self): 156 | return self.head == None 157 | 158 | # print all the items 159 | def printlist(self): 160 | if self.is_empty(): 161 | print "Nothing to display" 162 | else: 163 | curr = self.head 164 | while (curr != None): 165 | sys.stdout.write(str(curr.data) + ' ') 166 | curr = curr.next 167 | 168 | print '' 169 | 170 | def print_reverse(self): 171 | if self.is_empty(): 172 | print "Nothing to display" 173 | else: 174 | curr = self.tail 175 | while (curr != None): 176 | sys.stdout.write(str(curr.data) + ' ') 177 | curr = curr.prev 178 | 179 | print '' 180 | 181 | if __name__ == '__main__': 182 | list = MyLinkedList() 183 | list.insert_at_front(44) 184 | list.insert_at_front(66) 185 | list.insert_at_back(21) 186 | list.insert_at_back(43) 187 | list.print_reverse() 188 | list.insert_after(43,49) 189 | list.insert_after(21,33) 190 | list.printlist() 191 | print list.pop_front() 192 | list.printlist() 193 | print list.pop_back() 194 | list.printlist() 195 | list.remove(21) 196 | list.print_reverse() 197 | -------------------------------------------------------------------------------- /data-structures/dynamic-arrays/DynamicArray.cpp: -------------------------------------------------------------------------------- 1 | // C++ implementation of Dynamic Array 2 | #include 3 | using namespace std; 4 | 5 | template 6 | class DynamicArray { 7 | private: 8 | T *list; 9 | int max_size; 10 | int length; 11 | public: 12 | DynamicArray() { 13 | // initially allocate a single memory block 14 | max_size = 1; 15 | list = new T[max_size]; 16 | length = 0; 17 | } 18 | 19 | // insert new item to the end of the list 20 | void add(T item) { 21 | if (isFull()) { 22 | // create temporary list with double size 23 | max_size = 2 * max_size; 24 | T *temp_list = new T[2* max_size]; 25 | 26 | // move all the elements to the temporary list 27 | for (int i = 0; i < length; i++) { 28 | temp_list[i] = list[i]; 29 | } 30 | 31 | // delete the old list 32 | delete [] list; 33 | 34 | // rename temp list 35 | list = temp_list; 36 | } 37 | 38 | // add the new item at the end of the list 39 | list[length] = item; 40 | length++; 41 | } 42 | 43 | void printList() { 44 | for (int i = 0; i < length; i++) { 45 | cout< list; 64 | list.add('1'); 65 | list.add('2'); 66 | list.add('3'); 67 | list.add('4'); 68 | list.add('5'); 69 | list.add('6'); 70 | list.add('7'); 71 | list.add('8'); 72 | list.add('9'); 73 | list.printList(); 74 | return 0; 75 | } -------------------------------------------------------------------------------- /data-structures/dynamic-arrays/DynamicArray.java: -------------------------------------------------------------------------------- 1 | // Java implementation of Dynamic Array 2 | class DynamicArray { 3 | private int [] list; 4 | private int max_size; 5 | private int length; 6 | 7 | public DynamicArray() { 8 | // initially allocate a single memory block 9 | max_size = 1; 10 | list = new int[max_size]; 11 | length = 0; 12 | } 13 | 14 | // insert new item to the end of the list 15 | public void add(int item) { 16 | if (isFull()) { 17 | // create temporary list with double size 18 | max_size = 2 * max_size; 19 | int [] temp_list = new int[2* max_size]; 20 | 21 | // move all the elements to the temporary list 22 | for (int i = 0; i < length; i++) { 23 | temp_list[i] = list[i]; 24 | } 25 | 26 | // rename temp list 27 | list = temp_list; 28 | } 29 | 30 | // add the new item at the end of the list 31 | list[length] = item; 32 | length++; 33 | } 34 | 35 | public void printList() { 36 | for (int i = 0; i < length; i++) { 37 | System.out.print(list[i] + " "); 38 | } 39 | System.out.println(); 40 | } 41 | 42 | // check if the list is full 43 | boolean isFull() { 44 | return length == max_size; 45 | } 46 | 47 | public static void main(String [] args) { 48 | DynamicArray list = new DynamicArray(); 49 | list.add(1); 50 | list.add(2); 51 | list.add(3); 52 | list.add(4); 53 | list.add(5); 54 | list.add(6); 55 | list.add(7); 56 | list.add(8); 57 | list.add(9); 58 | list.printList(); 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /data-structures/priority-queues/PQHeap.cpp: -------------------------------------------------------------------------------- 1 | // C++ implementation of a priority queue 2 | 3 | #include 4 | using namespace std; 5 | 6 | class PQHeap { 7 | private: 8 | const static int MAX_SIZE = 15; 9 | int heap[MAX_SIZE]; 10 | int size; 11 | 12 | public: 13 | PQHeap() { 14 | size = 0; 15 | } 16 | 17 | // returns the index of the parent node 18 | static int parent(int i) { 19 | return (i - 1) / 2; 20 | } 21 | 22 | // return the index of the left child 23 | static int leftChild(int i) { 24 | return 2*i + 1; 25 | } 26 | 27 | // return the index of the right child 28 | static int rightChild(int i) { 29 | return 2*i + 2; 30 | } 31 | 32 | 33 | static void swap(int *x, int *y) { 34 | int temp = *x; 35 | *x = *y; 36 | *y = temp; 37 | } 38 | 39 | // insert the item at the appropriate position 40 | void enqueue(int data) { 41 | if (size >= MAX_SIZE) { 42 | cout<<"The heap is full. Cannot insert"< heap[largest]) { 74 | largest = left; 75 | } 76 | 77 | // check if the right node is larger than the current node 78 | // and left node 79 | if (right <= size && heap[right] > heap[largest]) { 80 | largest = right; 81 | } 82 | 83 | // swap the largest node with the current node 84 | // and repeat this process until the current node is larger than 85 | // the right and the left node 86 | if (largest != i) { 87 | int temp = heap[i]; 88 | heap[i] = heap[largest]; 89 | heap[largest] = temp; 90 | maxHeapify(largest); 91 | } 92 | 93 | } 94 | 95 | // returns the maximum item of the heap 96 | int peek() { 97 | return heap[0]; 98 | } 99 | 100 | // deletes the max item and return 101 | int dequeue() { 102 | int maxItem = heap[0]; 103 | 104 | // replace the first item with the last item 105 | heap[0] = heap[size - 1]; 106 | size = size - 1; 107 | 108 | // maintain the heap property by heapifying the 109 | // first item 110 | maxHeapify(0); 111 | return maxItem; 112 | } 113 | 114 | // prints the heap 115 | void printQueue() { 116 | for (int i = 0; i < size; i++) { 117 | cout<= MAX_SIZE) { 31 | System.out.println("The queue is full. Cannot insert"); 32 | return; 33 | } 34 | 35 | // first insert the time at the last position of the array 36 | // and move it up 37 | heap[size] = data; 38 | size = size + 1; 39 | 40 | 41 | // move up until the heap property satisfies 42 | int i = size - 1; 43 | while (i != 0 && heap[PQHeap.parent(i)] < heap[i]) { 44 | int temp = heap[i]; 45 | heap[i] = heap[parent(i)]; 46 | heap[parent(i)] = temp; 47 | i = PQHeap.parent(i); 48 | } 49 | } 50 | 51 | // moves the item at position i of array a 52 | // into its appropriate position 53 | public void maxHeapify(int i){ 54 | // find left child node 55 | int left = PQHeap.leftChild(i); 56 | 57 | // find right child node 58 | int right = PQHeap.rightChild(i); 59 | 60 | // find the largest among 3 nodes 61 | int largest = i; 62 | 63 | // check if the left node is larger than the current node 64 | if (left <= size && heap[left] > heap[largest]) { 65 | largest = left; 66 | } 67 | 68 | // check if the right node is larger than the current node 69 | // and left node 70 | if (right <= size && heap[right] > heap[largest]) { 71 | largest = right; 72 | } 73 | 74 | // swap the largest node with the current node 75 | // and repeat this process until the current node is larger than 76 | // the right and the left node 77 | if (largest != i) { 78 | int temp = heap[i]; 79 | heap[i] = heap[largest]; 80 | heap[largest] = temp; 81 | maxHeapify(largest); 82 | } 83 | 84 | } 85 | 86 | // returns the maximum item of the heap 87 | public int peek() { 88 | return heap[0]; 89 | } 90 | 91 | // deletes the max item and return 92 | public int dequeue() { 93 | int maxItem = heap[0]; 94 | 95 | // replace the first item with the last item 96 | heap[0] = heap[size - 1]; 97 | size = size - 1; 98 | 99 | // maintain the heap property by heapifying the 100 | // first item 101 | maxHeapify(0); 102 | return maxItem; 103 | } 104 | 105 | // prints the queue 106 | public void printQueue() { 107 | for (int i = 0; i < size; i++) { 108 | System.out.print(heap[i] + " "); 109 | } 110 | System.out.println(); 111 | } 112 | 113 | public static void main(String [] args) { 114 | PQHeap queue = new PQHeap(); 115 | queue.enqueue(43); 116 | queue.enqueue(333); 117 | queue.enqueue(345); 118 | queue.enqueue(45); 119 | queue.enqueue(3); 120 | queue.enqueue(400); 121 | System.out.println(queue.dequeue()); 122 | System.out.println(queue.dequeue()); 123 | } 124 | } -------------------------------------------------------------------------------- /data-structures/priority-queues/pq_array_ordered.c: -------------------------------------------------------------------------------- 1 | // Priority queue implementation an ordered array 2 | #include 3 | #define MAX_SIZE 10 4 | 5 | int queue[MAX_SIZE]; 6 | int n = 0; 7 | 8 | // insert an item at the appropriate position of the 9 | // queue so that the queue is always ordered 10 | void enqueue(int item) { 11 | // Check if the queue is full 12 | if (n == MAX_SIZE - 1) { 13 | printf("%s\n", "ERROR: Queue is full"); 14 | return; 15 | } 16 | 17 | int i = n-1; 18 | while (i >= 0 && item < queue[i]) { 19 | queue[i+1] = queue[i]; 20 | i--; 21 | } 22 | queue[i+1] = item; 23 | n++; 24 | } 25 | 26 | // remove the last element in the queue 27 | int dequeue() { 28 | int item; 29 | // Check if the queue is empty 30 | if (n == 0) { 31 | printf("%s\n", "ERROR: Queue is empty"); 32 | return -999999; 33 | } 34 | item = queue[n - 1]; 35 | n = n - 1; 36 | return item; 37 | } 38 | 39 | int main() { 40 | enqueue(12); 41 | enqueue(33); 42 | enqueue(45); 43 | enqueue(9); 44 | enqueue(26); 45 | printf("%d\n", dequeue()); 46 | printf("%d\n", dequeue()); 47 | printf("%d\n", dequeue()); 48 | printf("%d\n", dequeue()); 49 | return 0; 50 | } -------------------------------------------------------------------------------- /data-structures/priority-queues/pq_array_unordered.c: -------------------------------------------------------------------------------- 1 | // Priority queue implementation an unordered array 2 | #include 3 | #define MAX_SIZE 10 4 | 5 | int queue[MAX_SIZE]; 6 | int n = 0; 7 | 8 | // insert an item at the rear of the queue 9 | void enqueue(int item) { 10 | // Check if the queue is full 11 | if (n == MAX_SIZE - 1) { 12 | printf("%s\n", "ERROR: Queue is full"); 13 | return; 14 | } 15 | queue[n++] = item; 16 | } 17 | 18 | // removes the item with the maximum priority 19 | // search the maximum item in the array and replace it with 20 | // the last item 21 | int dequeue() { 22 | int item; 23 | // Check if the queue is empty 24 | if (n == 0) { 25 | printf("%s\n", "ERROR: Queue is empty"); 26 | return -999999; 27 | } 28 | int i, max = 0; 29 | // find the maximum priority 30 | for (i = 1; i < n; i++) { 31 | if (queue[max] < queue[i]) { 32 | max = i; 33 | } 34 | } 35 | item = queue[max]; 36 | 37 | // replace the max with the last element 38 | queue[max] = queue[n - 1]; 39 | n = n - 1; 40 | return item; 41 | } 42 | 43 | int main() { 44 | enqueue(12); 45 | enqueue(33); 46 | enqueue(45); 47 | enqueue(9); 48 | enqueue(26); 49 | printf("%d\n", dequeue()); 50 | printf("%d\n", dequeue()); 51 | printf("%d\n", dequeue()); 52 | printf("%d\n", dequeue()); 53 | return 0; 54 | } -------------------------------------------------------------------------------- /data-structures/priority-queues/pq_heap.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #define MAX_SIZE 15 4 | 5 | // returns the index of the parent node 6 | int parent(int i) { 7 | return (i - 1) / 2; 8 | } 9 | 10 | // return the index of the left child 11 | int left_child(int i) { 12 | return 2*i + 1; 13 | } 14 | 15 | // return the index of the right child 16 | int right_child(int i) { 17 | return 2*i + 2; 18 | } 19 | 20 | void swap(int *x, int *y) { 21 | int temp = *x; 22 | *x = *y; 23 | *y = temp; 24 | } 25 | 26 | // insert the item at the appropriate position 27 | void enqueue(int a[], int data, int *n) { 28 | if (*n >= MAX_SIZE) { 29 | printf("%s\n", "The heap is full. Cannot insert"); 30 | return; 31 | } 32 | // first insert the time at the last position of the array 33 | // and move it up 34 | a[*n] = data; 35 | *n = *n + 1; 36 | 37 | 38 | // move up until the heap property satisfies 39 | int i = *n - 1; 40 | while (i != 0 && a[parent(i)] < a[i]) { 41 | swap(&a[parent(i)], &a[i]); 42 | i = parent(i); 43 | } 44 | } 45 | 46 | // moves the item at position i of array a 47 | // into its appropriate position 48 | void max_heapify(int a[], int i, int n){ 49 | // find left child node 50 | int left = left_child(i); 51 | 52 | // find right child node 53 | int right = right_child(i); 54 | 55 | // find the largest among 3 nodes 56 | int largest = i; 57 | 58 | // check if the left node is larger than the current node 59 | if (left <= n && a[left] > a[largest]) { 60 | largest = left; 61 | } 62 | 63 | // check if the right node is larger than the current node 64 | if (right <= n && a[right] > a[largest]) { 65 | largest = right; 66 | } 67 | 68 | // swap the largest node with the current node 69 | // and repeat this process until the current node is larger than 70 | // the right and the left node 71 | if (largest != i) { 72 | int temp = a[i]; 73 | a[i] = a[largest]; 74 | a[largest] = temp; 75 | max_heapify(a, largest, n); 76 | } 77 | 78 | } 79 | 80 | // returns the maximum item of the heap 81 | int get_max(int a[]) { 82 | return a[0]; 83 | } 84 | 85 | // deletes the max item and return 86 | int dequeue(int a[], int *n) { 87 | int max_item = a[0]; 88 | 89 | // replace the first item with the last item 90 | a[0] = a[*n - 1]; 91 | *n = *n - 1; 92 | 93 | // maintain the heap property by heapifying the 94 | // first item 95 | max_heapify(a, 0, *n); 96 | return max_item; 97 | } 98 | 99 | // prints the heap 100 | void print_heap(int a[], int n) { 101 | int i; 102 | for (i = 0; i < n; i++) { 103 | printf("%d\n", a[i]); 104 | } 105 | printf("\n"); 106 | } 107 | 108 | 109 | int main() { 110 | int n = 10; 111 | int a[MAX_SIZE]; 112 | insert(a, 55, &n); 113 | insert(a, 56, &n); 114 | insert(a, 57, &n); 115 | insert(a, 58, &n); 116 | insert(a, 100, &n); 117 | print_heap(a, n); 118 | return 0; 119 | } -------------------------------------------------------------------------------- /data-structures/queues/QueueArray.cpp: -------------------------------------------------------------------------------- 1 | // C++ implementation of queue using array 2 | 3 | #include 4 | using namespace std; 5 | 6 | class QueueArray { 7 | private: 8 | const static int MAX_SIZE = 10; 9 | int queue[MAX_SIZE]; 10 | int rear; 11 | int front; 12 | public: 13 | QueueArray() { 14 | rear = front = -1; 15 | } 16 | 17 | // insert an item at the rear of the queue 18 | void enqueue(int item) { 19 | // Check if the queue is full 20 | if ((rear + 1) % MAX_SIZE == front) { 21 | cout<<"ERROR: Queue is full"< 4 | using namespace std; 5 | 6 | struct Node { 7 | int data; 8 | Node *next; 9 | Node *prev; 10 | }; 11 | 12 | typedef Node *NodePtr; 13 | 14 | class QueueLinkedList { 15 | private: 16 | NodePtr front; 17 | NodePtr rear; 18 | public: 19 | QueueLinkedList() { 20 | front = nullptr; 21 | rear = nullptr; 22 | } 23 | 24 | // inserts an item at the rear of the queue 25 | void enqueue(int item) { 26 | NodePtr node = new Node; 27 | node->data = item; 28 | node->next = nullptr; 29 | node->prev = nullptr; 30 | 31 | // if the queue is empty, make this node front and rear 32 | // else insert it at the end of the queue 33 | if (rear == nullptr) { 34 | rear = node; 35 | front = node; 36 | } else { 37 | rear->next = node; 38 | node->prev = rear; 39 | rear = node; 40 | } 41 | } 42 | 43 | // remove the item at the front of the queue 44 | int dequeue() { 45 | int item; 46 | if (front == nullptr) { 47 | cout<<"ERROR: Queue is empty"<data; 53 | NodePtr next = front->next; 54 | 55 | if (next != nullptr) { 56 | next->prev = nullptr; 57 | } else { 58 | rear = nullptr; 59 | } 60 | 61 | delete front; 62 | front = next; 63 | return item; 64 | } 65 | 66 | // returns the item at the front of the queue 67 | int getFront() { 68 | if (front == nullptr) { 69 | cout<<"ERROR: Queue is empty"<data; 74 | } 75 | }; 76 | 77 | int main() { 78 | QueueLinkedList queue; 79 | queue.enqueue(34); 80 | queue.enqueue(35); 81 | queue.enqueue(41); 82 | queue.enqueue(56); 83 | cout< 4 | #define MAX_SIZE 10 5 | int front = -1; 6 | int rear = -1; 7 | 8 | int queue[MAX_SIZE]; 9 | 10 | // insert an item at the rear of the queue 11 | void enqueue(int item) { 12 | // Check if the queue is full 13 | if ((rear + 1) % MAX_SIZE == front) { 14 | printf("%s\n", "ERROR: Queue is full"); 15 | return; 16 | } 17 | 18 | // if there are no items, make front and rear 1 19 | // else increment the rear by 1 20 | if (front == -1 && rear == -1) { 21 | front = rear = 0; 22 | } else { 23 | rear = (rear + 1) % MAX_SIZE; 24 | } 25 | 26 | // insert the time at rear 27 | queue[rear] = item; 28 | } 29 | 30 | // removes the item from the front of the queue 31 | int dequeue() { 32 | int item; 33 | // Check if the queue is empty 34 | if (rear == -1 && front == -1) { 35 | printf("%s\n", "ERROR: Queue is empty"); 36 | return -999999; 37 | } 38 | item = queue[front]; 39 | 40 | if (front == rear) { 41 | front = rear = -1; 42 | } else { 43 | // increase the front 44 | front = (front + 1) % MAX_SIZE; 45 | } 46 | return item; 47 | 48 | } 49 | 50 | // returns the item from the front of the queue 51 | int getFront() { 52 | // Check if the queue is empty 53 | if (rear == -1 && front == -1) { 54 | printf("%s\n", "ERROR: Queue is empty"); 55 | return -999999; 56 | } 57 | 58 | return queue[front]; 59 | } 60 | 61 | int main() { 62 | enqueue(34); 63 | enqueue(35); 64 | enqueue(41); 65 | enqueue(56); 66 | printf("%d\n", dequeue()); 67 | printf("%d\n", dequeue()); 68 | enqueue(62); 69 | enqueue(63); 70 | enqueue(64); 71 | enqueue(65); 72 | enqueue(66); 73 | enqueue(67); 74 | enqueue(68); 75 | enqueue(69); 76 | printf("%d\n", dequeue()); 77 | enqueue(70); 78 | return 0; 79 | } -------------------------------------------------------------------------------- /data-structures/queues/queue_linked_list.c: -------------------------------------------------------------------------------- 1 | // Queue implementation in C using linked list 2 | 3 | #include 4 | #include 5 | 6 | struct Node { 7 | int data; 8 | struct Node *next; 9 | struct Node *prev; 10 | }; 11 | 12 | typedef struct Node *NodePtr; 13 | 14 | // define front and rear globally 15 | NodePtr front = NULL; 16 | NodePtr rear = NULL; 17 | 18 | // inserts an item at the rear of the queue 19 | void enqueue(int item) { 20 | NodePtr node = malloc(sizeof(NodePtr)); 21 | node->data = item; 22 | node->next = NULL; 23 | node->prev = NULL; 24 | 25 | // if the queue is empty, make this node front and rear 26 | // else insert it at the end of the queue 27 | if (rear == NULL) { 28 | rear = node; 29 | front = node; 30 | } else { 31 | rear->next = node; 32 | node->prev = rear; 33 | rear = node; 34 | } 35 | } 36 | 37 | // remove the item at the front of the queue 38 | int dequeue() { 39 | int item; 40 | if (front == NULL) { 41 | printf("%s\n", "ERROR: Queue is empty"); 42 | return -999999; 43 | } 44 | 45 | // destory the front and make the next item new front 46 | item = front->data; 47 | NodePtr next = front->next; 48 | 49 | if (next != NULL) { 50 | next->prev = NULL; 51 | } else { 52 | rear = NULL; 53 | } 54 | 55 | free(front); 56 | front = next; 57 | return item; 58 | } 59 | 60 | 61 | // returns the item at the front of the queue 62 | int getFront() { 63 | if (front == NULL) { 64 | printf("%s\n", "ERROR: Queue is empty"); 65 | return -999999; 66 | } 67 | 68 | return front->data; 69 | } 70 | 71 | int main() { 72 | enqueue(34); 73 | enqueue(35); 74 | enqueue(41); 75 | enqueue(56); 76 | printf("%d\n", dequeue()); 77 | printf("%d\n", dequeue()); 78 | printf("%d\n", dequeue()); 79 | printf("%d\n", dequeue()); 80 | enqueue(70); 81 | printf("%d\n", getFront()); 82 | return 0; 83 | } -------------------------------------------------------------------------------- /data-structures/queues/queue_linked_list.py: -------------------------------------------------------------------------------- 1 | # Python implementation of queue using linked list 2 | 3 | class Node: 4 | def __init__(self, item): 5 | self.data = item 6 | self.prev = None 7 | self.next = None 8 | 9 | class QueueLinkedList: 10 | def __init__(self): 11 | self.front = None 12 | self.rear = None 13 | 14 | # inserts an item at the rear of the queue 15 | def enqueue(self, item): 16 | node = Node(item) 17 | 18 | # if the queue is empty, make this node front and rear 19 | # else insert it at the end of the queue 20 | if self.rear == None: 21 | self.rear = node 22 | self.front = node 23 | else: 24 | self.rear.next = node 25 | node.prev = self.rear 26 | self.rear = node 27 | 28 | # remove the item at the front of the queue 29 | def dequeue(self): 30 | if self.front == None: 31 | print "ERROR: Queue is empty" 32 | return -999999 33 | 34 | # destory the front and make the next item new front 35 | item = self.front.data 36 | next_node = self.front.next 37 | 38 | if next_node != None: 39 | next_node.prev = None 40 | else: 41 | self.rear = None 42 | 43 | self.front = next_node; 44 | return item 45 | 46 | # returns the item at the front of the queue 47 | def getFront(self): 48 | if self.front == None: 49 | print "ERROR: Queue is empty" 50 | return -999999 51 | 52 | return self.front.data 53 | 54 | if __name__ == "__main__": 55 | queue = QueueLinkedList() 56 | queue.enqueue(34) 57 | queue.enqueue(35) 58 | queue.enqueue(41) 59 | queue.enqueue(56) 60 | print queue.dequeue() 61 | print queue.dequeue() 62 | print queue.dequeue() 63 | print queue.dequeue() 64 | queue.enqueue(70) 65 | print queue.getFront() -------------------------------------------------------------------------------- /data-structures/red-black-trees/RedBlackTree.cpp: -------------------------------------------------------------------------------- 1 | // Red Black Tree implementation in C++ 2 | // Author: Algorithm Tutor 3 | // Tutorial URL: https://algorithmtutor.com/Data-Structures/Tree/Red-Black-Trees/ 4 | 5 | #include 6 | 7 | using namespace std; 8 | 9 | // data structure that represents a node in the tree 10 | struct Node { 11 | int data; // holds the key 12 | Node *parent; // pointer to the parent 13 | Node *left; // pointer to left child 14 | Node *right; // pointer to right child 15 | int color; // 1 -> Red, 0 -> Black 16 | }; 17 | 18 | typedef Node *NodePtr; 19 | 20 | // class RBTree implements the operations in Red Black Tree 21 | class RBTree { 22 | private: 23 | NodePtr root; 24 | NodePtr TNULL; 25 | 26 | // initializes the nodes with appropirate values 27 | // all the pointers are set to point to the null pointer 28 | void initializeNULLNode(NodePtr node, NodePtr parent) { 29 | node->data = 0; 30 | node->parent = parent; 31 | node->left = nullptr; 32 | node->right = nullptr; 33 | node->color = 0; 34 | } 35 | 36 | void preOrderHelper(NodePtr node) { 37 | if (node != TNULL) { 38 | cout<data<<" "; 39 | preOrderHelper(node->left); 40 | preOrderHelper(node->right); 41 | } 42 | } 43 | 44 | void inOrderHelper(NodePtr node) { 45 | if (node != TNULL) { 46 | inOrderHelper(node->left); 47 | cout<data<<" "; 48 | inOrderHelper(node->right); 49 | } 50 | } 51 | 52 | void postOrderHelper(NodePtr node) { 53 | if (node != TNULL) { 54 | postOrderHelper(node->left); 55 | postOrderHelper(node->right); 56 | cout<data<<" "; 57 | } 58 | } 59 | 60 | NodePtr searchTreeHelper(NodePtr node, int key) { 61 | if (node == TNULL || key == node->data) { 62 | return node; 63 | } 64 | 65 | if (key < node->data) { 66 | return searchTreeHelper(node->left, key); 67 | } 68 | return searchTreeHelper(node->right, key); 69 | } 70 | 71 | // fix the rb tree modified by the delete operation 72 | void fixDelete(NodePtr x) { 73 | NodePtr s; 74 | while (x != root && x->color == 0) { 75 | if (x == x->parent->left) { 76 | s = x->parent->right; 77 | if (s->color == 1) { 78 | // case 3.1 79 | s->color = 0; 80 | x->parent->color = 1; 81 | leftRotate(x->parent); 82 | s = x->parent->right; 83 | } 84 | 85 | if (s->left->color == 0 && s->right->color == 0) { 86 | // case 3.2 87 | s->color = 1; 88 | x = x->parent; 89 | } else { 90 | if (s->right->color == 0) { 91 | // case 3.3 92 | s->left->color = 0; 93 | s->color = 1; 94 | rightRotate(s); 95 | s = x->parent->right; 96 | } 97 | 98 | // case 3.4 99 | s->color = x->parent->color; 100 | x->parent->color = 0; 101 | s->right->color = 0; 102 | leftRotate(x->parent); 103 | x = root; 104 | } 105 | } else { 106 | s = x->parent->left; 107 | if (s->color == 1) { 108 | // case 3.1 109 | s->color = 0; 110 | x->parent->color = 1; 111 | rightRotate(x->parent); 112 | s = x->parent->left; 113 | } 114 | 115 | if (s->right->color == 0 && s->right->color == 0) { 116 | // case 3.2 117 | s->color = 1; 118 | x = x->parent; 119 | } else { 120 | if (s->left->color == 0) { 121 | // case 3.3 122 | s->right->color = 0; 123 | s->color = 1; 124 | leftRotate(s); 125 | s = x->parent->left; 126 | } 127 | 128 | // case 3.4 129 | s->color = x->parent->color; 130 | x->parent->color = 0; 131 | s->left->color = 0; 132 | rightRotate(x->parent); 133 | x = root; 134 | } 135 | } 136 | } 137 | x->color = 0; 138 | } 139 | 140 | 141 | void rbTransplant(NodePtr u, NodePtr v){ 142 | if (u->parent == nullptr) { 143 | root = v; 144 | } else if (u == u->parent->left){ 145 | u->parent->left = v; 146 | } else { 147 | u->parent->right = v; 148 | } 149 | v->parent = u->parent; 150 | } 151 | 152 | void deleteNodeHelper(NodePtr node, int key) { 153 | // find the node containing key 154 | NodePtr z = TNULL; 155 | NodePtr x, y; 156 | while (node != TNULL){ 157 | if (node->data == key) { 158 | z = node; 159 | } 160 | 161 | if (node->data <= key) { 162 | node = node->right; 163 | } else { 164 | node = node->left; 165 | } 166 | } 167 | 168 | if (z == TNULL) { 169 | cout<<"Couldn't find key in the tree"<color; 175 | if (z->left == TNULL) { 176 | x = z->right; 177 | rbTransplant(z, z->right); 178 | } else if (z->right == TNULL) { 179 | x = z->left; 180 | rbTransplant(z, z->left); 181 | } else { 182 | y = minimum(z->right); 183 | y_original_color = y->color; 184 | x = y->right; 185 | if (y->parent == z) { 186 | x->parent = y; 187 | } else { 188 | rbTransplant(y, y->right); 189 | y->right = z->right; 190 | y->right->parent = y; 191 | } 192 | 193 | rbTransplant(z, y); 194 | y->left = z->left; 195 | y->left->parent = y; 196 | y->color = z->color; 197 | } 198 | delete z; 199 | if (y_original_color == 0){ 200 | fixDelete(x); 201 | } 202 | } 203 | 204 | // fix the red-black tree 205 | void fixInsert(NodePtr k){ 206 | NodePtr u; 207 | while (k->parent->color == 1) { 208 | if (k->parent == k->parent->parent->right) { 209 | u = k->parent->parent->left; // uncle 210 | if (u->color == 1) { 211 | // case 3.1 212 | u->color = 0; 213 | k->parent->color = 0; 214 | k->parent->parent->color = 1; 215 | k = k->parent->parent; 216 | } else { 217 | if (k == k->parent->left) { 218 | // case 3.2.2 219 | k = k->parent; 220 | rightRotate(k); 221 | } 222 | // case 3.2.1 223 | k->parent->color = 0; 224 | k->parent->parent->color = 1; 225 | leftRotate(k->parent->parent); 226 | } 227 | } else { 228 | u = k->parent->parent->right; // uncle 229 | 230 | if (u->color == 1) { 231 | // mirror case 3.1 232 | u->color = 0; 233 | k->parent->color = 0; 234 | k->parent->parent->color = 1; 235 | k = k->parent->parent; 236 | } else { 237 | if (k == k->parent->right) { 238 | // mirror case 3.2.2 239 | k = k->parent; 240 | leftRotate(k); 241 | } 242 | // mirror case 3.2.1 243 | k->parent->color = 0; 244 | k->parent->parent->color = 1; 245 | rightRotate(k->parent->parent); 246 | } 247 | } 248 | if (k == root) { 249 | break; 250 | } 251 | } 252 | root->color = 0; 253 | } 254 | 255 | void printHelper(NodePtr root, string indent, bool last) { 256 | // print the tree structure on the screen 257 | if (root != TNULL) { 258 | cout<color?"RED":"BLACK"; 268 | cout<data<<"("<left, indent, false); 270 | printHelper(root->right, indent, true); 271 | } 272 | // cout<left->data<color = 0; 279 | TNULL->left = nullptr; 280 | TNULL->right = nullptr; 281 | root = TNULL; 282 | } 283 | 284 | // Pre-Order traversal 285 | // Node->Left Subtree->Right Subtree 286 | void preorder() { 287 | preOrderHelper(this->root); 288 | } 289 | 290 | // In-Order traversal 291 | // Left Subtree -> Node -> Right Subtree 292 | void inorder() { 293 | inOrderHelper(this->root); 294 | } 295 | 296 | // Post-Order traversal 297 | // Left Subtree -> Right Subtree -> Node 298 | void postorder() { 299 | postOrderHelper(this->root); 300 | } 301 | 302 | // search the tree for the key k 303 | // and return the corresponding node 304 | NodePtr searchTree(int k) { 305 | return searchTreeHelper(this->root, k); 306 | } 307 | 308 | // find the node with the minimum key 309 | NodePtr minimum(NodePtr node) { 310 | while (node->left != TNULL) { 311 | node = node->left; 312 | } 313 | return node; 314 | } 315 | 316 | // find the node with the maximum key 317 | NodePtr maximum(NodePtr node) { 318 | while (node->right != TNULL) { 319 | node = node->right; 320 | } 321 | return node; 322 | } 323 | 324 | // find the successor of a given node 325 | NodePtr successor(NodePtr x) { 326 | // if the right subtree is not null, 327 | // the successor is the leftmost node in the 328 | // right subtree 329 | if (x->right != TNULL) { 330 | return minimum(x->right); 331 | } 332 | 333 | // else it is the lowest ancestor of x whose 334 | // left child is also an ancestor of x. 335 | NodePtr y = x->parent; 336 | while (y != TNULL && x == y->right) { 337 | x = y; 338 | y = y->parent; 339 | } 340 | return y; 341 | } 342 | 343 | // find the predecessor of a given node 344 | NodePtr predecessor(NodePtr x) { 345 | // if the left subtree is not null, 346 | // the predecessor is the rightmost node in the 347 | // left subtree 348 | if (x->left != TNULL) { 349 | return maximum(x->left); 350 | } 351 | 352 | NodePtr y = x->parent; 353 | while (y != TNULL && x == y->left) { 354 | x = y; 355 | y = y->parent; 356 | } 357 | 358 | return y; 359 | } 360 | 361 | // rotate left at node x 362 | void leftRotate(NodePtr x) { 363 | NodePtr y = x->right; 364 | x->right = y->left; 365 | if (y->left != TNULL) { 366 | y->left->parent = x; 367 | } 368 | y->parent = x->parent; 369 | if (x->parent == nullptr) { 370 | this->root = y; 371 | } else if (x == x->parent->left) { 372 | x->parent->left = y; 373 | } else { 374 | x->parent->right = y; 375 | } 376 | y->left = x; 377 | x->parent = y; 378 | } 379 | 380 | // rotate right at node x 381 | void rightRotate(NodePtr x) { 382 | NodePtr y = x->left; 383 | x->left = y->right; 384 | if (y->right != TNULL) { 385 | y->right->parent = x; 386 | } 387 | y->parent = x->parent; 388 | if (x->parent == nullptr) { 389 | this->root = y; 390 | } else if (x == x->parent->right) { 391 | x->parent->right = y; 392 | } else { 393 | x->parent->left = y; 394 | } 395 | y->right = x; 396 | x->parent = y; 397 | } 398 | 399 | // insert the key to the tree in its appropriate position 400 | // and fix the tree 401 | void insert(int key) { 402 | // Ordinary Binary Search Insertion 403 | NodePtr node = new Node; 404 | node->parent = nullptr; 405 | node->data = key; 406 | node->left = TNULL; 407 | node->right = TNULL; 408 | node->color = 1; // new node must be red 409 | 410 | NodePtr y = nullptr; 411 | NodePtr x = this->root; 412 | 413 | while (x != TNULL) { 414 | y = x; 415 | if (node->data < x->data) { 416 | x = x->left; 417 | } else { 418 | x = x->right; 419 | } 420 | } 421 | 422 | // y is parent of x 423 | node->parent = y; 424 | if (y == nullptr) { 425 | root = node; 426 | } else if (node->data < y->data) { 427 | y->left = node; 428 | } else { 429 | y->right = node; 430 | } 431 | 432 | // if new node is a root node, simply return 433 | if (node->parent == nullptr){ 434 | node->color = 0; 435 | return; 436 | } 437 | 438 | // if the grandparent is null, simply return 439 | if (node->parent->parent == nullptr) { 440 | return; 441 | } 442 | 443 | // Fix the tree 444 | fixInsert(node); 445 | } 446 | 447 | NodePtr getRoot(){ 448 | return this->root; 449 | } 450 | 451 | // delete the node from the tree 452 | void deleteNode(int data) { 453 | deleteNodeHelper(this->root, data); 454 | } 455 | 456 | // print the tree structure on the screen 457 | void prettyPrint() { 458 | if (root) { 459 | printHelper(this->root, "", true); 460 | } 461 | } 462 | 463 | }; 464 | 465 | int main() { 466 | RBTree bst; 467 | bst.insert(8); 468 | bst.insert(18); 469 | bst.insert(5); 470 | bst.insert(15); 471 | bst.insert(17); 472 | bst.insert(25); 473 | bst.insert(40); 474 | bst.insert(80); 475 | bst.deleteNode(25); 476 | bst.prettyPrint(); 477 | return 0; 478 | } -------------------------------------------------------------------------------- /data-structures/red-black-trees/RedBlackTree.java: -------------------------------------------------------------------------------- 1 | // Red Black Tree implementation in Java 2 | // Author: Algorithm Tutor 3 | // Tutorial URL: https://algorithmtutor.com/Data-Structures/Tree/Red-Black-Trees/ 4 | 5 | // data structure that represents a node in the tree 6 | class Node { 7 | int data; // holds the key 8 | Node parent; // pointer to the parent 9 | Node left; // pointer to left child 10 | Node right; // pointer to right child 11 | int color; // 1 . Red, 0 . Black 12 | } 13 | 14 | 15 | // class RedBlackTree implements the operations in Red Black Tree 16 | public class RedBlackTree { 17 | private Node root; 18 | private Node TNULL; 19 | 20 | private void preOrderHelper(Node node) { 21 | if (node != TNULL) { 22 | System.out.print(node.data + " "); 23 | preOrderHelper(node.left); 24 | preOrderHelper(node.right); 25 | } 26 | } 27 | 28 | private void inOrderHelper(Node node) { 29 | if (node != TNULL) { 30 | inOrderHelper(node.left); 31 | System.out.print(node.data + " "); 32 | inOrderHelper(node.right); 33 | } 34 | } 35 | 36 | private void postOrderHelper(Node node) { 37 | if (node != TNULL) { 38 | postOrderHelper(node.left); 39 | postOrderHelper(node.right); 40 | System.out.print(node.data + " "); 41 | } 42 | } 43 | 44 | private Node searchTreeHelper(Node node, int key) { 45 | if (node == TNULL || key == node.data) { 46 | return node; 47 | } 48 | 49 | if (key < node.data) { 50 | return searchTreeHelper(node.left, key); 51 | } 52 | return searchTreeHelper(node.right, key); 53 | } 54 | 55 | // fix the rb tree modified by the delete operation 56 | private void fixDelete(Node x) { 57 | Node s; 58 | while (x != root && x.color == 0) { 59 | if (x == x.parent.left) { 60 | s = x.parent.right; 61 | if (s.color == 1) { 62 | // case 3.1 63 | s.color = 0; 64 | x.parent.color = 1; 65 | leftRotate(x.parent); 66 | s = x.parent.right; 67 | } 68 | 69 | if (s.left.color == 0 && s.right.color == 0) { 70 | // case 3.2 71 | s.color = 1; 72 | x = x.parent; 73 | } else { 74 | if (s.right.color == 0) { 75 | // case 3.3 76 | s.left.color = 0; 77 | s.color = 1; 78 | rightRotate(s); 79 | s = x.parent.right; 80 | } 81 | 82 | // case 3.4 83 | s.color = x.parent.color; 84 | x.parent.color = 0; 85 | s.right.color = 0; 86 | leftRotate(x.parent); 87 | x = root; 88 | } 89 | } else { 90 | s = x.parent.left; 91 | if (s.color == 1) { 92 | // case 3.1 93 | s.color = 0; 94 | x.parent.color = 1; 95 | rightRotate(x.parent); 96 | s = x.parent.left; 97 | } 98 | 99 | if (s.right.color == 0 && s.right.color == 0) { 100 | // case 3.2 101 | s.color = 1; 102 | x = x.parent; 103 | } else { 104 | if (s.left.color == 0) { 105 | // case 3.3 106 | s.right.color = 0; 107 | s.color = 1; 108 | leftRotate(s); 109 | s = x.parent.left; 110 | } 111 | 112 | // case 3.4 113 | s.color = x.parent.color; 114 | x.parent.color = 0; 115 | s.left.color = 0; 116 | rightRotate(x.parent); 117 | x = root; 118 | } 119 | } 120 | } 121 | x.color = 0; 122 | } 123 | 124 | 125 | private void rbTransplant(Node u, Node v){ 126 | if (u.parent == null) { 127 | root = v; 128 | } else if (u == u.parent.left){ 129 | u.parent.left = v; 130 | } else { 131 | u.parent.right = v; 132 | } 133 | v.parent = u.parent; 134 | } 135 | 136 | private void deleteNodeHelper(Node node, int key) { 137 | // find the node containing key 138 | Node z = TNULL; 139 | Node x, y; 140 | while (node != TNULL){ 141 | if (node.data == key) { 142 | z = node; 143 | } 144 | 145 | if (node.data <= key) { 146 | node = node.right; 147 | } else { 148 | node = node.left; 149 | } 150 | } 151 | 152 | if (z == TNULL) { 153 | System.out.println("Couldn't find key in the tree"); 154 | return; 155 | } 156 | 157 | y = z; 158 | int yOriginalColor = y.color; 159 | if (z.left == TNULL) { 160 | x = z.right; 161 | rbTransplant(z, z.right); 162 | } else if (z.right == TNULL) { 163 | x = z.left; 164 | rbTransplant(z, z.left); 165 | } else { 166 | y = minimum(z.right); 167 | yOriginalColor = y.color; 168 | x = y.right; 169 | if (y.parent == z) { 170 | x.parent = y; 171 | } else { 172 | rbTransplant(y, y.right); 173 | y.right = z.right; 174 | y.right.parent = y; 175 | } 176 | 177 | rbTransplant(z, y); 178 | y.left = z.left; 179 | y.left.parent = y; 180 | y.color = z.color; 181 | } 182 | if (yOriginalColor == 0){ 183 | fixDelete(x); 184 | } 185 | } 186 | 187 | // fix the red-black tree 188 | private void fixInsert(Node k){ 189 | Node u; 190 | while (k.parent.color == 1) { 191 | if (k.parent == k.parent.parent.right) { 192 | u = k.parent.parent.left; // uncle 193 | if (u.color == 1) { 194 | // case 3.1 195 | u.color = 0; 196 | k.parent.color = 0; 197 | k.parent.parent.color = 1; 198 | k = k.parent.parent; 199 | } else { 200 | if (k == k.parent.left) { 201 | // case 3.2.2 202 | k = k.parent; 203 | rightRotate(k); 204 | } 205 | // case 3.2.1 206 | k.parent.color = 0; 207 | k.parent.parent.color = 1; 208 | leftRotate(k.parent.parent); 209 | } 210 | } else { 211 | u = k.parent.parent.right; // uncle 212 | 213 | if (u.color == 1) { 214 | // mirror case 3.1 215 | u.color = 0; 216 | k.parent.color = 0; 217 | k.parent.parent.color = 1; 218 | k = k.parent.parent; 219 | } else { 220 | if (k == k.parent.right) { 221 | // mirror case 3.2.2 222 | k = k.parent; 223 | leftRotate(k); 224 | } 225 | // mirror case 3.2.1 226 | k.parent.color = 0; 227 | k.parent.parent.color = 1; 228 | rightRotate(k.parent.parent); 229 | } 230 | } 231 | if (k == root) { 232 | break; 233 | } 234 | } 235 | root.color = 0; 236 | } 237 | 238 | private void printHelper(Node root, String indent, boolean last) { 239 | // print the tree structure on the screen 240 | if (root != TNULL) { 241 | System.out.print(indent); 242 | if (last) { 243 | System.out.print("R----"); 244 | indent += " "; 245 | } else { 246 | System.out.print("L----"); 247 | indent += "| "; 248 | } 249 | 250 | String sColor = root.color == 1?"RED":"BLACK"; 251 | System.out.println(root.data + "(" + sColor + ")"); 252 | printHelper(root.left, indent, false); 253 | printHelper(root.right, indent, true); 254 | } 255 | } 256 | 257 | public RedBlackTree() { 258 | TNULL = new Node(); 259 | TNULL.color = 0; 260 | TNULL.left = null; 261 | TNULL.right = null; 262 | root = TNULL; 263 | } 264 | 265 | // Pre-Order traversal 266 | // Node.Left Subtree.Right Subtree 267 | public void preorder() { 268 | preOrderHelper(this.root); 269 | } 270 | 271 | // In-Order traversal 272 | // Left Subtree . Node . Right Subtree 273 | public void inorder() { 274 | inOrderHelper(this.root); 275 | } 276 | 277 | // Post-Order traversal 278 | // Left Subtree . Right Subtree . Node 279 | public void postorder() { 280 | postOrderHelper(this.root); 281 | } 282 | 283 | // search the tree for the key k 284 | // and return the corresponding node 285 | public Node searchTree(int k) { 286 | return searchTreeHelper(this.root, k); 287 | } 288 | 289 | // find the node with the minimum key 290 | public Node minimum(Node node) { 291 | while (node.left != TNULL) { 292 | node = node.left; 293 | } 294 | return node; 295 | } 296 | 297 | // find the node with the maximum key 298 | public Node maximum(Node node) { 299 | while (node.right != TNULL) { 300 | node = node.right; 301 | } 302 | return node; 303 | } 304 | 305 | // find the successor of a given node 306 | public Node successor(Node x) { 307 | // if the right subtree is not null, 308 | // the successor is the leftmost node in the 309 | // right subtree 310 | if (x.right != TNULL) { 311 | return minimum(x.right); 312 | } 313 | 314 | // else it is the lowest ancestor of x whose 315 | // left child is also an ancestor of x. 316 | Node y = x.parent; 317 | while (y != TNULL && x == y.right) { 318 | x = y; 319 | y = y.parent; 320 | } 321 | return y; 322 | } 323 | 324 | // find the predecessor of a given node 325 | public Node predecessor(Node x) { 326 | // if the left subtree is not null, 327 | // the predecessor is the rightmost node in the 328 | // left subtree 329 | if (x.left != TNULL) { 330 | return maximum(x.left); 331 | } 332 | 333 | Node y = x.parent; 334 | while (y != TNULL && x == y.left) { 335 | x = y; 336 | y = y.parent; 337 | } 338 | 339 | return y; 340 | } 341 | 342 | // rotate left at node x 343 | public void leftRotate(Node x) { 344 | Node y = x.right; 345 | x.right = y.left; 346 | if (y.left != TNULL) { 347 | y.left.parent = x; 348 | } 349 | y.parent = x.parent; 350 | if (x.parent == null) { 351 | this.root = y; 352 | } else if (x == x.parent.left) { 353 | x.parent.left = y; 354 | } else { 355 | x.parent.right = y; 356 | } 357 | y.left = x; 358 | x.parent = y; 359 | } 360 | 361 | // rotate right at node x 362 | public void rightRotate(Node x) { 363 | Node y = x.left; 364 | x.left = y.right; 365 | if (y.right != TNULL) { 366 | y.right.parent = x; 367 | } 368 | y.parent = x.parent; 369 | if (x.parent == null) { 370 | this.root = y; 371 | } else if (x == x.parent.right) { 372 | x.parent.right = y; 373 | } else { 374 | x.parent.left = y; 375 | } 376 | y.right = x; 377 | x.parent = y; 378 | } 379 | 380 | // insert the key to the tree in its appropriate position 381 | // and fix the tree 382 | public void insert(int key) { 383 | // Ordinary Binary Search Insertion 384 | Node node = new Node(); 385 | node.parent = null; 386 | node.data = key; 387 | node.left = TNULL; 388 | node.right = TNULL; 389 | node.color = 1; // new node must be red 390 | 391 | Node y = null; 392 | Node x = this.root; 393 | 394 | while (x != TNULL) { 395 | y = x; 396 | if (node.data < x.data) { 397 | x = x.left; 398 | } else { 399 | x = x.right; 400 | } 401 | } 402 | 403 | // y is parent of x 404 | node.parent = y; 405 | if (y == null) { 406 | root = node; 407 | } else if (node.data < y.data) { 408 | y.left = node; 409 | } else { 410 | y.right = node; 411 | } 412 | 413 | // if new node is a root node, simply return 414 | if (node.parent == null){ 415 | node.color = 0; 416 | return; 417 | } 418 | 419 | // if the grandparent is null, simply return 420 | if (node.parent.parent == null) { 421 | return; 422 | } 423 | 424 | // Fix the tree 425 | fixInsert(node); 426 | } 427 | 428 | public Node getRoot(){ 429 | return this.root; 430 | } 431 | 432 | // delete the node from the tree 433 | public void deleteNode(int data) { 434 | deleteNodeHelper(this.root, data); 435 | } 436 | 437 | // print the tree structure on the screen 438 | public void prettyPrint() { 439 | printHelper(this.root, "", true); 440 | } 441 | 442 | public static void main(String [] args){ 443 | RedBlackTree bst = new RedBlackTree(); 444 | bst.insert(8); 445 | bst.insert(18); 446 | bst.insert(5); 447 | bst.insert(15); 448 | bst.insert(17); 449 | bst.insert(25); 450 | bst.insert(40); 451 | bst.insert(80); 452 | bst.deleteNode(25); 453 | bst.prettyPrint(); 454 | } 455 | } -------------------------------------------------------------------------------- /data-structures/singly-linked-list/MyLinkedList.cpp: -------------------------------------------------------------------------------- 1 | // C++ implementation of singly linked list 2 | #include 3 | 4 | using namespace std; 5 | 6 | // data structure for Node 7 | // data -> the actual value 8 | // next -> address of the next node 9 | struct Node { 10 | int data; 11 | Node *next; 12 | }; 13 | 14 | typedef Node *NodePtr; 15 | 16 | class MyLinkedList { 17 | private: 18 | NodePtr head; 19 | 20 | public: 21 | MyLinkedList() { 22 | head = nullptr; 23 | } 24 | 25 | // Insert 'value' at the front of the list 26 | void insertAtFront(int value) { 27 | NodePtr node = new Node; 28 | node->data = value; 29 | node->next = nullptr; 30 | 31 | if (isEmpty()) { 32 | head = node; 33 | } else { 34 | node->next = head; 35 | head = node; 36 | } 37 | } 38 | 39 | // insert value at the back of the linked list 40 | void insertAtBack(int value) { 41 | NodePtr node = new Node; 42 | node->data = value; 43 | node->next = nullptr; 44 | 45 | if (isEmpty()) { 46 | head = node; 47 | } else { 48 | // find the last node 49 | NodePtr currPtr = head; 50 | while (currPtr->next != nullptr) { 51 | currPtr = currPtr->next; 52 | } 53 | 54 | // insert it 55 | currPtr->next = node; 56 | } 57 | } 58 | 59 | // inserts value after key 60 | void insertAfter(int key, int value) { 61 | NodePtr node = new Node; 62 | node->data = value; 63 | node->next = nullptr; 64 | 65 | // find the position of key 66 | NodePtr currPtr = head; 67 | while (currPtr != nullptr && currPtr->data != key) { 68 | currPtr = currPtr->next; 69 | } 70 | 71 | // if key is not there, raise error 72 | if (currPtr == nullptr) { 73 | cout<<"key not found"; 74 | } else if (currPtr->next == nullptr) { 75 | // if key is the last node, insert right after it 76 | currPtr->next = node; 77 | } else { 78 | // insert between key and item next to key 79 | NodePtr nextPtr = currPtr->next; 80 | currPtr->next = node; 81 | node->next = nextPtr; 82 | } 83 | } 84 | 85 | // returns the data at first node 86 | int topFront() { 87 | if (isEmpty()) { 88 | cout<<"List is empty"<data; 91 | } 92 | } 93 | 94 | // returns the data at last node 95 | int topBack() { 96 | if (isEmpty()) { 97 | cout<<"List is empty"<next == nullptr) { 99 | return head->data; 100 | } else { 101 | NodePtr currPtr = head; 102 | while (currPtr->next != nullptr) { 103 | currPtr = currPtr->next; 104 | } 105 | return currPtr->data; 106 | } 107 | } 108 | 109 | // removes the item at front of the linked list and return 110 | int popFront() { 111 | int item; 112 | if (isEmpty()) { 113 | cout<<"List is empty"<next; 117 | item = head->data; 118 | // remove head 119 | delete head; 120 | 121 | // make nextptr head 122 | head = nextPtr; 123 | 124 | } 125 | 126 | return item; 127 | } 128 | 129 | // remove the item at the list of the linked list and return 130 | int popBack() { 131 | int item; 132 | if (isEmpty()) { 133 | cout<<"List if empty"<next == nullptr) { 136 | item = head->data; 137 | delete head; 138 | head = nullptr; 139 | } else { 140 | NodePtr currPtr = head; 141 | NodePtr prevPtr = nullptr; 142 | while (currPtr->next != nullptr) { 143 | prevPtr = currPtr; 144 | currPtr = currPtr->next; 145 | } 146 | item = currPtr->data; 147 | delete currPtr; 148 | currPtr = nullptr; 149 | prevPtr->next = nullptr; 150 | } 151 | 152 | return item; 153 | } 154 | 155 | // removes an item with value 'key' 156 | void remove(int key) { 157 | if (isEmpty()) { 158 | cout<<"list is empty"<data != key) { 166 | prevPtr = currPtr; 167 | currPtr = currPtr->next; 168 | } 169 | 170 | if (currPtr == nullptr) { 171 | cout<<"Key is not found in the list"<next; 178 | delete currPtr; 179 | currPtr = nullptr; 180 | return; 181 | } 182 | 183 | if (currPtr->next == nullptr) { 184 | // this is the last item 185 | prevPtr->next = nullptr; 186 | delete currPtr; 187 | currPtr = nullptr; 188 | } else { 189 | // anywhere in between first and last 190 | NodePtr nextPtr = currPtr->next; 191 | prevPtr->next = nextPtr; 192 | delete currPtr; 193 | currPtr = nullptr; 194 | } 195 | } 196 | 197 | // print the linked list 198 | void print() { 199 | NodePtr currPtr = head; 200 | while (currPtr != nullptr) { 201 | cout<data<<" "; 202 | currPtr = currPtr->next; 203 | } 204 | cout<data != key) { 220 | currPtr = currPtr->next; 221 | } 222 | 223 | if (currPtr == nullptr) { 224 | return false; 225 | } 226 | 227 | return true; 228 | } 229 | }; 230 | 231 | int main() { 232 | MyLinkedList list; 233 | // operations 234 | return 0; 235 | } -------------------------------------------------------------------------------- /data-structures/singly-linked-list/MyLinkedList.java: -------------------------------------------------------------------------------- 1 | // Java implementation of Singly linked list 2 | 3 | class Node { 4 | int data; 5 | Node next; 6 | 7 | public Node(int data) { 8 | this.data = data; 9 | this.next = null; 10 | } 11 | } 12 | 13 | public class MyLinkedList { 14 | private Node head; 15 | 16 | public MyLinkedList() { 17 | head = null; 18 | } 19 | 20 | // Insert 'value' at the front of the list 21 | public void insertAtFront(int value) { 22 | Node node = new Node(value); 23 | if(isEmpty()) { 24 | head = node; 25 | } else { 26 | node.next = head; 27 | head = node; 28 | } 29 | } 30 | 31 | // insert value at the back of the linked list 32 | public void insertAtBack(int value) { 33 | Node node = new Node(value); 34 | if (isEmpty()) { 35 | head = node; 36 | } else { 37 | Node curr = head; 38 | while(null != curr.next) { 39 | curr = curr.next; 40 | } 41 | 42 | curr.next = node; 43 | } 44 | } 45 | 46 | // inserts value after key 47 | public void insertAfter(int key, int value) { 48 | Node node = new Node(value); 49 | 50 | // find the position of key 51 | Node curr = head; 52 | while(null != curr && curr.data != key) { 53 | curr = curr.next; 54 | } 55 | 56 | if (null == curr) { 57 | System.out.println("Key not found"); 58 | return; 59 | } 60 | 61 | if(null == curr.next) { 62 | curr.next = node; 63 | } else { 64 | Node next = curr.next; 65 | curr.next = node; 66 | node.next = next; 67 | } 68 | } 69 | 70 | // returns the data at first node 71 | public int topFront() { 72 | if (isEmpty()) { 73 | System.out.println("List is empty"); 74 | return -999999; 75 | } 76 | 77 | return head.data; 78 | } 79 | 80 | // returns the data at last node 81 | public int topBack() { 82 | if(isEmpty()) { 83 | System.out.println("List is empty"); 84 | return -999999; 85 | } 86 | 87 | Node curr = head; 88 | while(curr.next != null) { 89 | curr = curr.next; 90 | } 91 | 92 | return curr.data; 93 | } 94 | 95 | // removes the item at front of the linked list and return 96 | public int popFront() { 97 | if (isEmpty()) { 98 | System.out.println("List is empty"); 99 | return -999999; 100 | } 101 | 102 | Node next = head.next; 103 | int item = head.data; 104 | head = next; 105 | return item; 106 | } 107 | 108 | // remove the item at the end of the list and return 109 | public int popBack() { 110 | if (isEmpty()) { 111 | System.out.println("List is empty"); 112 | return -999999; 113 | } 114 | 115 | // get to the last node 116 | Node curr = head; 117 | Node prev = null; 118 | while(curr.next != null) { 119 | prev = curr; 120 | curr = curr.next; 121 | } 122 | 123 | int item = curr.data; 124 | 125 | if (prev == null) { 126 | // the list has only one item 127 | head = null; 128 | } else { 129 | prev.next = null; 130 | curr = null; 131 | } 132 | 133 | return item; 134 | } 135 | 136 | // removes an item with value 'key' 137 | public void remove(int key) { 138 | if (isEmpty()) { 139 | System.out.println("List is empty"); 140 | return; 141 | } 142 | 143 | // find the position of the key 144 | Node curr = head; 145 | Node prev = null; 146 | 147 | while(curr != null && curr.data != key) { 148 | prev = curr; 149 | curr = curr.next; 150 | } 151 | 152 | if(curr == null) { 153 | System.out.print("key not found"); 154 | return; 155 | } 156 | 157 | // if curr is head, delete the head 158 | if (prev == null) { 159 | head = head.next; 160 | curr = null; 161 | } else if (curr.next == null) { // if curr is last item 162 | prev.next = null; 163 | curr = null; 164 | } else { //anywhere between first and last node 165 | Node next = curr.next; 166 | prev.next = next; 167 | curr = null; 168 | } 169 | 170 | 171 | } 172 | 173 | // check if the key is in the list 174 | public boolean find(int key) { 175 | if (isEmpty()) { 176 | System.out.println("List is empty"); 177 | return false; 178 | } 179 | 180 | Node curr = head; 181 | while(curr != null && curr.data != key) { 182 | curr = curr.next; 183 | } 184 | 185 | if (curr == null) { 186 | return false; 187 | } 188 | 189 | return true; 190 | } 191 | 192 | // check if the list is empty 193 | public boolean isEmpty() { 194 | return head == null; 195 | } 196 | 197 | // print all the items 198 | public void print() { 199 | if (isEmpty()) { 200 | System.out.println("Nothing to display"); 201 | } else { 202 | Node curr = head; 203 | while (curr != null) { 204 | System.out.print(curr.data + " "); 205 | curr = curr.next; 206 | } 207 | System.out.println(); 208 | } 209 | } 210 | 211 | public static void main(String [] args) { 212 | MyLinkedList list = new MyLinkedList(); 213 | } 214 | } -------------------------------------------------------------------------------- /data-structures/singly-linked-list/my_linked_list.c: -------------------------------------------------------------------------------- 1 | // C implementation of singly linked list 2 | #include 3 | #include 4 | 5 | 6 | 7 | // data structure for Node 8 | // data -> the actual value 9 | // next -> address of the next node 10 | struct Node { 11 | int data; 12 | struct Node *next; 13 | }; 14 | 15 | typedef struct Node *NodePtr; 16 | 17 | // global variable head. It points to the 18 | // first node of the list 19 | NodePtr head = NULL; 20 | 21 | // check if the list is empty 22 | int isEmpty() { 23 | return head == NULL; 24 | } 25 | 26 | // Insert 'value' at the front of the list 27 | void insertAtFront(int value) { 28 | NodePtr node = malloc(sizeof(NodePtr)); 29 | node->data = value; 30 | node->next = NULL; 31 | 32 | if (isEmpty()) { 33 | head = node; 34 | } else { 35 | node->next = head; 36 | head = node; 37 | } 38 | 39 | } 40 | 41 | // insert value at the back of the linked list 42 | void insertAtBack(int value) { 43 | NodePtr node = malloc(sizeof(NodePtr)); 44 | node->data = value; 45 | node->next = NULL; 46 | 47 | if (isEmpty()) { 48 | head = node; 49 | } else { 50 | // find the last node 51 | NodePtr currPtr = head; 52 | while (currPtr->next != NULL) { 53 | currPtr = currPtr->next; 54 | } 55 | 56 | // insert it 57 | currPtr->next = node; 58 | } 59 | } 60 | 61 | // inserts value after key 62 | NodePtr insertAfter(int key, int value) { 63 | NodePtr node = malloc(sizeof(NodePtr)); 64 | node->data = value; 65 | node->next = NULL; 66 | 67 | // find the position of key 68 | NodePtr currPtr = head; 69 | while (currPtr != NULL && currPtr->data != key) { 70 | currPtr = currPtr->next; 71 | } 72 | 73 | // if key is not there, raise error 74 | if (currPtr == NULL) { 75 | printf("%s", "key not found"); 76 | } else if (currPtr->next == NULL) { 77 | // if key is the last node, insert right after it 78 | currPtr->next = node; 79 | } else { 80 | // insert between key and item next to key 81 | NodePtr nextPtr = currPtr->next; 82 | currPtr->next = node; 83 | node->next = nextPtr; 84 | } 85 | } 86 | 87 | // returns the data at first node 88 | int topFront() { 89 | if (isEmpty()) { 90 | printf("%s", "List is empty"); 91 | } else { 92 | return head->data; 93 | } 94 | } 95 | 96 | // returns the data at last node 97 | int topBack() { 98 | if (isEmpty()) { 99 | printf("%s", "List is empty"); 100 | } else if (head->next == NULL) { 101 | return head->data; 102 | } else { 103 | NodePtr currPtr = head; 104 | while (currPtr->next != NULL) { 105 | currPtr = currPtr->next; 106 | } 107 | return currPtr->data; 108 | } 109 | } 110 | 111 | // removes the item at front of the linked list and return 112 | int popFront() { 113 | int item; 114 | if (isEmpty()) { 115 | printf("%s", "List is empty"); 116 | return -99999; 117 | } else { 118 | NodePtr nextPtr = head->next; 119 | item = head->data; 120 | // remove head 121 | free(head); 122 | 123 | // make nextptr head 124 | head = nextPtr; 125 | 126 | } 127 | 128 | return item; 129 | } 130 | 131 | // remove the item at the list of the linked list and return 132 | int popBack() { 133 | int item; 134 | if (isEmpty()) { 135 | printf("%s", "List is empty"); 136 | return -99999; 137 | } else if (head->next == NULL) { 138 | item = head->data; 139 | free(head); 140 | head = NULL; 141 | } else { 142 | NodePtr currPtr = head; 143 | NodePtr prevPtr = NULL; 144 | while (currPtr->next != NULL) { 145 | prevPtr = currPtr; 146 | currPtr = currPtr->next; 147 | } 148 | item = currPtr->data; 149 | free(currPtr); 150 | currPtr = NULL; 151 | prevPtr->next = NULL; 152 | } 153 | 154 | return item; 155 | } 156 | 157 | // removes an item with value 'key' 158 | void delete(int key) { 159 | if (isEmpty()) { 160 | printf("%s", "List is empty"); 161 | return; 162 | } 163 | 164 | // get to the position of key 165 | NodePtr prevPtr = NULL; 166 | NodePtr currPtr = head; 167 | while(currPtr != NULL && currPtr->data != key) { 168 | prevPtr = currPtr; 169 | currPtr = currPtr->next; 170 | } 171 | 172 | if (currPtr == NULL) { 173 | printf("%s", "Key is not found in the list"); 174 | return; 175 | } 176 | 177 | if (prevPtr == NULL) { 178 | // this is the first item 179 | head = head->next; 180 | free(currPtr); 181 | currPtr = NULL; 182 | return; 183 | } 184 | 185 | if (currPtr->next == NULL) { 186 | // this is the last item 187 | prevPtr->next = NULL; 188 | free(currPtr); 189 | currPtr = NULL; 190 | } else { 191 | // anywhere in between first and last 192 | NodePtr nextPtr = currPtr->next; 193 | prevPtr->next = nextPtr; 194 | free(currPtr); 195 | currPtr = NULL; 196 | } 197 | } 198 | 199 | // print the linked list 200 | void print() { 201 | NodePtr currPtr = head; 202 | while (currPtr != NULL) { 203 | printf("%d", currPtr->data); 204 | printf(" "); 205 | currPtr = currPtr->next; 206 | } 207 | printf("\n"); 208 | } 209 | 210 | // check if key is in the list 211 | int find(int key) { 212 | if (isEmpty()) { 213 | return 0; 214 | } 215 | 216 | NodePtr currPtr = head; 217 | while (currPtr != NULL && currPtr->data != key) { 218 | currPtr = currPtr->next; 219 | } 220 | 221 | if (currPtr == NULL) { 222 | return 0; 223 | } 224 | 225 | return 1; 226 | } 227 | 228 | int main() { 229 | insertAtFront(23); 230 | insertAtFront(24); 231 | print(); 232 | // operations 233 | return 0; 234 | } -------------------------------------------------------------------------------- /data-structures/singly-linked-list/my_linked_list.py: -------------------------------------------------------------------------------- 1 | # Python implementation of Singly linked list 2 | import sys 3 | 4 | class Node: 5 | def __init__(self, data): 6 | self.data = data 7 | self.next = None 8 | 9 | class MyLinkedList: 10 | def __init__(self): 11 | self.head = None 12 | 13 | # Insert 'value' at the front of the list 14 | def insert_at_front(self, value): 15 | node = Node(value) 16 | if self.is_empty(): 17 | self.head = node 18 | else: 19 | node.next = self.head 20 | self.head = node 21 | 22 | # insert value at the back of the linked list 23 | def insert_at_back(self, value): 24 | node = Node(value) 25 | if self.is_empty(): 26 | self.head = node 27 | else: 28 | curr = self.head 29 | while curr.next != None: 30 | curr = curr.next 31 | curr.next = node 32 | 33 | # inserts value after key 34 | def insert_after(self, key, value): 35 | node = Node(value) 36 | 37 | # find the position of key 38 | curr = self.head 39 | while curr != None and curr.data != key: 40 | curr = curr.next 41 | 42 | if curr == None: 43 | print 'Key not found' 44 | return 45 | 46 | if curr.next == None: 47 | curr.next = node 48 | else: 49 | next_node = curr.next 50 | curr.next = node 51 | node.next = next_node 52 | 53 | # returns the data at first node 54 | def top_front(self): 55 | if self.is_empty(): 56 | print 'List is empty' 57 | return 58 | 59 | return self.head.data 60 | 61 | # returns the data at last node 62 | def top_back(self): 63 | if self.is_empty(): 64 | print 'List is empty' 65 | return 66 | 67 | curr = self.head 68 | while curr.next != None: 69 | curr = curr.next 70 | 71 | return curr.data 72 | 73 | # removes the item at front of the linked list and return 74 | def pop_front(self): 75 | if self.is_empty(): 76 | print 'List is empty' 77 | return 78 | 79 | next_node = self.head.next 80 | item = self.head.data 81 | self.head = next_node 82 | return item 83 | 84 | # remove the item at the end of the list and return 85 | def pop_back(self): 86 | if self.is_empty(): 87 | print 'List is empty' 88 | return 89 | 90 | # get to the last node 91 | curr = self.head 92 | prev = None 93 | 94 | while curr.next != None: 95 | prev = curr 96 | curr = curr.next 97 | 98 | item = curr.data 99 | 100 | if prev == None: 101 | # the list has only one item 102 | self.head = None 103 | else: 104 | prev.next = None 105 | curr = None 106 | 107 | return item 108 | 109 | # removes an item with value 'key' 110 | def remove(self, key): 111 | if self.is_empty(): 112 | print 'List is empty' 113 | return 114 | 115 | # find the position of the key 116 | curr = self.head 117 | prev = None 118 | 119 | while curr != None and curr.data != key: 120 | prev = curr 121 | curr = curr.next 122 | 123 | if curr == None: 124 | print 'key not found' 125 | return 126 | 127 | # if curr is head, delete the head 128 | if prev == None: 129 | self.head = self.head.next 130 | curr = None 131 | elif curr.next == None: # if curr is last item 132 | prev.next = None 133 | curr = None 134 | else: #anywhere between first and last node 135 | next_node = curr.next 136 | prev.next = next_node 137 | curr = None 138 | 139 | # check if the key is in the list 140 | def find(self, key): 141 | if self.is_empty(): 142 | print 'List is empty' 143 | return False 144 | 145 | curr = self.head 146 | while curr != None and curr.data != key: 147 | curr = curr.next 148 | 149 | if curr == None: 150 | return False 151 | 152 | return True 153 | 154 | # check if the list is empty 155 | def is_empty(self): 156 | return self.head == None 157 | 158 | # print all the items 159 | def printlist(self): 160 | if self.is_empty(): 161 | print "Nothing to display" 162 | else: 163 | curr = self.head 164 | while (curr != None): 165 | sys.stdout.write(str(curr.data) + ' ') 166 | curr = curr.next 167 | 168 | print '' 169 | 170 | if __name__ == '__main__': 171 | list = MyLinkedList() 172 | # write code -------------------------------------------------------------------------------- /data-structures/splay-trees/SplayTree.cpp: -------------------------------------------------------------------------------- 1 | // Splay tree implementation in C++ 2 | // Author: Algorithm Tutor 3 | // Tutorial URL: http://algorithmtutor.com/Data-Structures/Tree/Splay-Trees/ 4 | 5 | #include 6 | 7 | using namespace std; 8 | 9 | // data structure that represents a node in the tree 10 | struct Node { 11 | int data; // holds the key 12 | Node *parent; // pointer to the parent 13 | Node *left; // pointer to left child 14 | Node *right; // pointer to right child 15 | }; 16 | 17 | typedef Node *NodePtr; 18 | 19 | // class SplayTree implements the operations in Splay tree 20 | class SplayTree { 21 | private: 22 | NodePtr root; 23 | 24 | void preOrderHelper(NodePtr node) { 25 | if (node != nullptr) { 26 | cout<data<<" "; 27 | preOrderHelper(node->left); 28 | preOrderHelper(node->right); 29 | } 30 | } 31 | 32 | void inOrderHelper(NodePtr node) { 33 | if (node != nullptr) { 34 | inOrderHelper(node->left); 35 | cout<data<<" "; 36 | inOrderHelper(node->right); 37 | } 38 | } 39 | 40 | void postOrderHelper(NodePtr node) { 41 | if (node != nullptr) { 42 | postOrderHelper(node->left); 43 | postOrderHelper(node->right); 44 | cout<data<<" "; 45 | } 46 | } 47 | 48 | NodePtr searchTreeHelper(NodePtr node, int key) { 49 | if (node == nullptr || key == node->data) { 50 | return node; 51 | } 52 | 53 | if (key < node->data) { 54 | return searchTreeHelper(node->left, key); 55 | } 56 | return searchTreeHelper(node->right, key); 57 | } 58 | 59 | void deleteNodeHelper(NodePtr node, int key) { 60 | NodePtr x = nullptr; 61 | NodePtr t, s; 62 | while (node != nullptr){ 63 | if (node->data == key) { 64 | x = node; 65 | } 66 | 67 | if (node->data <= key) { 68 | node = node->right; 69 | } else { 70 | node = node->left; 71 | } 72 | } 73 | 74 | if (x == nullptr) { 75 | cout<<"Couldn't find key in the tree"<left){ // remove x 80 | s->left->parent = nullptr; 81 | } 82 | root = join(s->left, t); 83 | delete(s); 84 | s = nullptr; 85 | } 86 | 87 | void printHelper(NodePtr root, string indent, bool last) { 88 | // print the tree structure on the screen 89 | if (root != nullptr) { 90 | cout<data<left, indent, false); 102 | printHelper(root->right, indent, true); 103 | } 104 | } 105 | 106 | // rotate left at node x 107 | void leftRotate(NodePtr x) { 108 | NodePtr y = x->right; 109 | x->right = y->left; 110 | if (y->left != nullptr) { 111 | y->left->parent = x; 112 | } 113 | y->parent = x->parent; 114 | if (x->parent == nullptr) { 115 | this->root = y; 116 | } else if (x == x->parent->left) { 117 | x->parent->left = y; 118 | } else { 119 | x->parent->right = y; 120 | } 121 | y->left = x; 122 | x->parent = y; 123 | } 124 | 125 | // rotate right at node x 126 | void rightRotate(NodePtr x) { 127 | NodePtr y = x->left; 128 | x->left = y->right; 129 | if (y->right != nullptr) { 130 | y->right->parent = x; 131 | } 132 | y->parent = x->parent; 133 | if (x->parent == nullptr) { 134 | this->root = y; 135 | } else if (x == x->parent->right) { 136 | x->parent->right = y; 137 | } else { 138 | x->parent->left = y; 139 | } 140 | y->right = x; 141 | x->parent = y; 142 | } 143 | 144 | // splaying 145 | void splay(NodePtr x) { 146 | while (x->parent) { 147 | if (!x->parent->parent) { 148 | if (x == x->parent->left) { 149 | // zig rotation 150 | rightRotate(x->parent); 151 | } else { 152 | // zag rotation 153 | leftRotate(x->parent); 154 | } 155 | } else if (x == x->parent->left && x->parent == x->parent->parent->left) { 156 | // zig-zig rotation 157 | rightRotate(x->parent->parent); 158 | rightRotate(x->parent); 159 | } else if (x == x->parent->right && x->parent == x->parent->parent->right) { 160 | // zag-zag rotation 161 | leftRotate(x->parent->parent); 162 | leftRotate(x->parent); 163 | } else if (x == x->parent->right && x->parent == x->parent->parent->left) { 164 | // zig-zag rotation 165 | leftRotate(x->parent); 166 | rightRotate(x->parent); 167 | } else { 168 | // zag-zig rotation 169 | rightRotate(x->parent); 170 | leftRotate(x->parent); 171 | } 172 | } 173 | } 174 | 175 | // joins two trees s and t 176 | NodePtr join(NodePtr s, NodePtr t){ 177 | if (!s) { 178 | return t; 179 | } 180 | 181 | if (!t) { 182 | return s; 183 | } 184 | NodePtr x = maximum(s); 185 | splay(x); 186 | x->right = t; 187 | t->parent = x; 188 | return x; 189 | } 190 | 191 | // splits the tree into s and t 192 | void split(NodePtr &x, NodePtr &s, NodePtr &t) { 193 | splay(x); 194 | if (x->right) { 195 | t = x->right; 196 | t->parent = nullptr; 197 | } else { 198 | t = nullptr; 199 | } 200 | s = x; 201 | s->right = nullptr; 202 | x = nullptr; 203 | } 204 | 205 | public: 206 | SplayTree() { 207 | root = nullptr; 208 | } 209 | 210 | // Pre-Order traversal 211 | // Node->Left Subtree->Right Subtree 212 | void preorder() { 213 | preOrderHelper(this->root); 214 | } 215 | 216 | // In-Order traversal 217 | // Left Subtree -> Node -> Right Subtree 218 | void inorder() { 219 | inOrderHelper(this->root); 220 | } 221 | 222 | // Post-Order traversal 223 | // Left Subtree -> Right Subtree -> Node 224 | void postorder() { 225 | postOrderHelper(this->root); 226 | } 227 | 228 | // search the tree for the key k 229 | // and return the corresponding node 230 | NodePtr searchTree(int k) { 231 | NodePtr x = searchTreeHelper(this->root, k); 232 | if (x) { 233 | splay(x); 234 | } 235 | return x; 236 | } 237 | 238 | // find the node with the minimum key 239 | NodePtr minimum(NodePtr node) { 240 | while (node->left != nullptr) { 241 | node = node->left; 242 | } 243 | return node; 244 | } 245 | 246 | // find the node with the maximum key 247 | NodePtr maximum(NodePtr node) { 248 | while (node->right != nullptr) { 249 | node = node->right; 250 | } 251 | return node; 252 | } 253 | 254 | // find the successor of a given node 255 | NodePtr successor(NodePtr x) { 256 | // if the right subtree is not null, 257 | // the successor is the leftmost node in the 258 | // right subtree 259 | if (x->right != nullptr) { 260 | return minimum(x->right); 261 | } 262 | 263 | // else it is the lowest ancestor of x whose 264 | // left child is also an ancestor of x. 265 | NodePtr y = x->parent; 266 | while (y != nullptr && x == y->right) { 267 | x = y; 268 | y = y->parent; 269 | } 270 | return y; 271 | } 272 | 273 | // find the predecessor of a given node 274 | NodePtr predecessor(NodePtr x) { 275 | // if the left subtree is not null, 276 | // the predecessor is the rightmost node in the 277 | // left subtree 278 | if (x->left != nullptr) { 279 | return maximum(x->left); 280 | } 281 | 282 | NodePtr y = x->parent; 283 | while (y != nullptr && x == y->left) { 284 | x = y; 285 | y = y->parent; 286 | } 287 | 288 | return y; 289 | } 290 | 291 | // insert the key to the tree in its appropriate position 292 | void insert(int key) { 293 | // normal BST insert 294 | NodePtr node = new Node; 295 | node->parent = nullptr; 296 | node->left = nullptr; 297 | node->right = nullptr; 298 | node->data = key; 299 | NodePtr y = nullptr; 300 | NodePtr x = this->root; 301 | 302 | while (x != nullptr) { 303 | y = x; 304 | if (node->data < x->data) { 305 | x = x->left; 306 | } else { 307 | x = x->right; 308 | } 309 | } 310 | 311 | // y is parent of x 312 | node->parent = y; 313 | if (y == nullptr) { 314 | root = node; 315 | } else if (node->data < y->data) { 316 | y->left = node; 317 | } else { 318 | y->right = node; 319 | } 320 | 321 | // splay the node 322 | splay(node); 323 | } 324 | 325 | NodePtr getRoot(){ 326 | return this->root; 327 | } 328 | 329 | // delete the node from the tree 330 | void deleteNode(int data) { 331 | deleteNodeHelper(this->root, data); 332 | } 333 | 334 | // print the tree structure on the screen 335 | void prettyPrint() { 336 | printHelper(this->root, "", true); 337 | } 338 | 339 | }; 340 | 341 | int main() { 342 | SplayTree bst; 343 | bst.insert(33); 344 | bst.insert(44); 345 | bst.insert(67); 346 | bst.insert(5); 347 | bst.insert(89); 348 | bst.insert(41); 349 | bst.insert(98); 350 | bst.insert(1); 351 | bst.prettyPrint(); 352 | bst.searchTree(33); 353 | bst.searchTree(44); 354 | bst.prettyPrint(); 355 | bst.deleteNode(89); 356 | bst.deleteNode(67); 357 | bst.deleteNode(41); 358 | bst.deleteNode(5); 359 | bst.prettyPrint(); 360 | bst.deleteNode(98); 361 | bst.deleteNode(1); 362 | bst.deleteNode(44); 363 | bst.deleteNode(33); 364 | bst.prettyPrint(); 365 | return 0; 366 | } -------------------------------------------------------------------------------- /data-structures/splay-trees/SplayTree.java: -------------------------------------------------------------------------------- 1 | // Splay tree implementation in Java 2 | // Author: AlgorithmTutor 3 | // Tutorial URL: http://algorithmtutor.com/Data-Structures/Tree/Splay-Trees/ 4 | 5 | // data structure that represents a node in the tree 6 | class Node { 7 | int data; // holds the key 8 | Node parent; // pointer to the parent 9 | Node left; // pointer to left child 10 | Node right; // pointer to right child 11 | 12 | public Node(int data) { 13 | this.data = data; 14 | this.parent = null; 15 | this.left = null; 16 | this.right = null; 17 | } 18 | } 19 | 20 | public class SplayTree { 21 | private Node root; 22 | 23 | public SplayTree() { 24 | root = null; 25 | } 26 | 27 | private void printHelper(Node currPtr, String indent, boolean last) { 28 | // print the tree structure on the screen 29 | if (currPtr != null) { 30 | System.out.print(indent); 31 | if (last) { 32 | System.out.print("R----"); 33 | indent += " "; 34 | } else { 35 | System.out.print("L----"); 36 | indent += "| "; 37 | } 38 | 39 | System.out.println(currPtr.data); 40 | 41 | printHelper(currPtr.left, indent, false); 42 | printHelper(currPtr.right, indent, true); 43 | } 44 | } 45 | 46 | private Node searchTreeHelper(Node node, int key) { 47 | if (node == null || key == node.data) { 48 | return node; 49 | } 50 | 51 | if (key < node.data) { 52 | return searchTreeHelper(node.left, key); 53 | } 54 | return searchTreeHelper(node.right, key); 55 | } 56 | 57 | private void deleteNodeHelper(Node node, int key) { 58 | Node x = null; 59 | Node t = null; 60 | Node s = null; 61 | while (node != null){ 62 | if (node.data == key) { 63 | x = node; 64 | } 65 | 66 | if (node.data <= key) { 67 | node = node.right; 68 | } else { 69 | node = node.left; 70 | } 71 | } 72 | 73 | if (x == null) { 74 | System.out.println("Couldn't find key in the tree"); 75 | return; 76 | } 77 | // split operation 78 | splay(x); 79 | if (x.right != null) { 80 | t = x.right; 81 | t.parent = null; 82 | } else { 83 | t = null; 84 | } 85 | s = x; 86 | s.right = null; 87 | x = null; 88 | 89 | // join operation 90 | if (s.left != null){ // remove x 91 | s.left.parent = null; 92 | } 93 | root = join(s.left, t); 94 | s = null; 95 | } 96 | 97 | // rotate left at node x 98 | private void leftRotate(Node x) { 99 | Node y = x.right; 100 | x.right = y.left; 101 | if (y.left != null) { 102 | y.left.parent = x; 103 | } 104 | y.parent = x.parent; 105 | if (x.parent == null) { 106 | this.root = y; 107 | } else if (x == x.parent.left) { 108 | x.parent.left = y; 109 | } else { 110 | x.parent.right = y; 111 | } 112 | y.left = x; 113 | x.parent = y; 114 | } 115 | 116 | // rotate right at node x 117 | private void rightRotate(Node x) { 118 | Node y = x.left; 119 | x.left = y.right; 120 | if (y.right != null) { 121 | y.right.parent = x; 122 | } 123 | y.parent = x.parent; 124 | if (x.parent == null) { 125 | this.root = y; 126 | } else if (x == x.parent.right) { 127 | x.parent.right = y; 128 | } else { 129 | x.parent.left = y; 130 | } 131 | y.right = x; 132 | x.parent = y; 133 | } 134 | 135 | // Splaying operation. It moves x to the root of the tree 136 | private void splay(Node x) { 137 | while (x.parent != null) { 138 | if (x.parent.parent == null) { 139 | if (x == x.parent.left) { 140 | // zig rotation 141 | rightRotate(x.parent); 142 | } else { 143 | // zag rotation 144 | leftRotate(x.parent); 145 | } 146 | } else if (x == x.parent.left && x.parent == x.parent.parent.left) { 147 | // zig-zig rotation 148 | rightRotate(x.parent.parent); 149 | rightRotate(x.parent); 150 | } else if (x == x.parent.right && x.parent == x.parent.parent.right) { 151 | // zag-zag rotation 152 | leftRotate(x.parent.parent); 153 | leftRotate(x.parent); 154 | } else if (x == x.parent.right && x.parent == x.parent.parent.left) { 155 | // zig-zag rotation 156 | leftRotate(x.parent); 157 | rightRotate(x.parent); 158 | } else { 159 | // zag-zig rotation 160 | rightRotate(x.parent); 161 | leftRotate(x.parent); 162 | } 163 | } 164 | } 165 | 166 | // joins two trees s and t 167 | private Node join(Node s, Node t){ 168 | if (s == null) { 169 | return t; 170 | } 171 | 172 | if (t == null) { 173 | return s; 174 | } 175 | Node x = maximum(s); 176 | splay(x); 177 | x.right = t; 178 | t.parent = x; 179 | return x; 180 | } 181 | 182 | 183 | private void preOrderHelper(Node node) { 184 | if (node != null) { 185 | System.out.print(node.data + " "); 186 | preOrderHelper(node.left); 187 | preOrderHelper(node.right); 188 | } 189 | } 190 | 191 | private void inOrderHelper(Node node) { 192 | if (node != null) { 193 | inOrderHelper(node.left); 194 | System.out.print(node.data + " "); 195 | inOrderHelper(node.right); 196 | } 197 | } 198 | 199 | private void postOrderHelper(Node node) { 200 | if (node != null) { 201 | postOrderHelper(node.left); 202 | postOrderHelper(node.right); 203 | System.out.print(node.data + " "); 204 | } 205 | } 206 | 207 | // Pre-Order traversal 208 | // Node->Left Subtree->Right Subtree 209 | public void preorder() { 210 | preOrderHelper(this.root); 211 | } 212 | 213 | // In-Order traversal 214 | // Left Subtree -> Node -> Right Subtree 215 | public void inorder() { 216 | inOrderHelper(this.root); 217 | } 218 | 219 | // Post-Order traversal 220 | // Left Subtree -> Right Subtree -> Node 221 | public void postorder() { 222 | postOrderHelper(this.root); 223 | } 224 | 225 | // search the tree for the key k 226 | // and return the corresponding node 227 | public Node searchTree(int k) { 228 | Node x = searchTreeHelper(root, k); 229 | if (x != null) { 230 | splay(x); 231 | } 232 | return x; 233 | } 234 | 235 | // find the node with the minimum key 236 | public Node minimum(Node node) { 237 | while (node.left != null) { 238 | node = node.left; 239 | } 240 | return node; 241 | } 242 | 243 | // find the node with the maximum key 244 | public Node maximum(Node node) { 245 | while (node.right != null) { 246 | node = node.right; 247 | } 248 | return node; 249 | } 250 | 251 | // find the successor of a given node 252 | public Node successor(Node x) { 253 | // if the right subtree is not null, 254 | // the successor is the leftmost node in the 255 | // right subtree 256 | if (x.right != null) { 257 | return minimum(x.right); 258 | } 259 | 260 | // else it is the lowest ancestor of x whose 261 | // left child is also an ancestor of x. 262 | Node y = x.parent; 263 | while (y != null && x == y.right) { 264 | x = y; 265 | y = y.parent; 266 | } 267 | return y; 268 | } 269 | 270 | // find the predecessor of a given node 271 | public Node predecessor(Node x) { 272 | // if the left subtree is not null, 273 | // the predecessor is the rightmost node in the 274 | // left subtree 275 | if (x.left != null) { 276 | return maximum(x.left); 277 | } 278 | 279 | Node y = x.parent; 280 | while (y != null && x == y.left) { 281 | x = y; 282 | y = y.parent; 283 | } 284 | 285 | return y; 286 | } 287 | 288 | // insert the key to the tree in its appropriate position 289 | public void insert(int key) { 290 | Node node = new Node(key); 291 | Node y = null; 292 | Node x = this.root; 293 | 294 | while (x != null) { 295 | y = x; 296 | if (node.data < x.data) { 297 | x = x.left; 298 | } else { 299 | x = x.right; 300 | } 301 | } 302 | 303 | // y is parent of x 304 | node.parent = y; 305 | if (y == null) { 306 | root = node; 307 | } else if (node.data < y.data) { 308 | y.left = node; 309 | } else { 310 | y.right = node; 311 | } 312 | 313 | // splay node 314 | splay(node); 315 | } 316 | 317 | // delete the node from the tree 318 | void deleteNode(int data) { 319 | deleteNodeHelper(this.root, data); 320 | } 321 | 322 | // print the tree structure on the screen 323 | public void prettyPrint() { 324 | printHelper(this.root, "", true); 325 | } 326 | 327 | public static void main(String [] args) { 328 | SplayTree tree = new SplayTree(); 329 | tree.insert(33); 330 | tree.insert(44); 331 | tree.insert(67); 332 | tree.insert(5); 333 | tree.insert(89); 334 | tree.insert(41); 335 | tree.insert(98); 336 | tree.insert(1); 337 | tree.prettyPrint(); 338 | tree.searchTree(33); 339 | tree.searchTree(44); 340 | tree.prettyPrint(); 341 | tree.deleteNode(89); 342 | tree.deleteNode(67); 343 | tree.deleteNode(41); 344 | tree.deleteNode(5); 345 | tree.prettyPrint(); 346 | tree.deleteNode(98); 347 | tree.deleteNode(1); 348 | tree.deleteNode(44); 349 | tree.deleteNode(33); 350 | tree.prettyPrint(); 351 | } 352 | } -------------------------------------------------------------------------------- /data-structures/splay-trees/splay_tree.py: -------------------------------------------------------------------------------- 1 | # Splay tree implementation in Python 2 | # Author: AlgorithmTutor 3 | # Tutorial URL: http://algorithmtutor.com/Data-Structures/Tree/Splay-Trees/ 4 | 5 | # data structure that represents a node in the tree 6 | 7 | import sys 8 | 9 | class Node: 10 | def __init__(self, data): 11 | self.data = data 12 | self.parent = None 13 | self.left = None 14 | self.right = None 15 | 16 | class SplayTree: 17 | def __init__(self): 18 | self.root = None 19 | 20 | def __print_helper(self, currPtr, indent, last): 21 | # print the tree structure on the screen 22 | if currPtr != None: 23 | sys.stdout.write(indent) 24 | if last: 25 | sys.stdout.write("R----") 26 | indent += " " 27 | else: 28 | sys.stdout.write("L----") 29 | indent += "| " 30 | 31 | print(currPtr.data) 32 | 33 | self.__print_helper(currPtr.left, indent, False) 34 | self.__print_helper(currPtr.right, indent, True) 35 | 36 | def __search_tree_helper(self, node, key): 37 | if node == None or key == node.data: 38 | return node 39 | 40 | if key < node.data: 41 | return self.__search_tree_helper(node.left, key) 42 | return self.__search_tree_helper(node.right, key) 43 | 44 | def __delete_node_helper(self, node, key): 45 | x = None 46 | t = None 47 | s = None 48 | while node != None: 49 | if node.data == key: 50 | x = node 51 | 52 | if node.data <= key: 53 | node = node.right 54 | else: 55 | node = node.left 56 | 57 | if x == None: 58 | print "Couldn't find key in the tree" 59 | return 60 | 61 | # split operation 62 | self.__splay(x) 63 | if x.right != None: 64 | t = x.right 65 | t.parent = None 66 | else: 67 | t = None 68 | 69 | s = x 70 | s.right = None 71 | x = None 72 | 73 | # join operation 74 | if s.left != None: 75 | s.left.parent = None 76 | 77 | self.root = self.__join(s.left, t) 78 | s = None 79 | 80 | # rotate left at node x 81 | def __left_rotate(self, x): 82 | y = x.right 83 | x.right = y.left 84 | if y.left != None: 85 | y.left.parent = x 86 | 87 | y.parent = x.parent 88 | if x.parent == None: 89 | self.root = y 90 | elif x == x.parent.left: 91 | x.parent.left = y 92 | else: 93 | x.parent.right = y 94 | y.left = x 95 | x.parent = y 96 | 97 | # rotate right at node x 98 | def __right_rotate(self, x): 99 | y = x.left 100 | x.left = y.right 101 | if y.right != None: 102 | y.right.parent = x 103 | 104 | y.parent = x.parent; 105 | if x.parent == None: 106 | self.root = y 107 | elif x == x.parent.right: 108 | x.parent.right = y 109 | else: 110 | x.parent.left = y 111 | 112 | y.right = x 113 | x.parent = y 114 | 115 | # Splaying operation. It moves x to the root of the tree 116 | def __splay(self, x): 117 | while x.parent != None: 118 | if x.parent.parent == None: 119 | if x == x.parent.left: 120 | # zig rotation 121 | self.__right_rotate(x.parent) 122 | else: 123 | # zag rotation 124 | self.__left_rotate(x.parent) 125 | elif x == x.parent.left and x.parent == x.parent.parent.left: 126 | # zig-zig rotation 127 | self.__right_rotate(x.parent.parent) 128 | self.__right_rotate(x.parent) 129 | elif x == x.parent.right and x.parent == x.parent.parent.right: 130 | # zag-zag rotation 131 | self.__left_rotate(x.parent.parent) 132 | self.__left_rotate(x.parent) 133 | elif x == x.parent.right and x.parent == x.parent.parent.left: 134 | # zig-zag rotation 135 | self.__left_rotate(x.parent) 136 | self.__right_rotate(x.parent) 137 | else: 138 | # zag-zig rotation 139 | self.__right_rotate(x.parent) 140 | self.__left_rotate(x.parent) 141 | 142 | # joins two trees s and t 143 | def __join(self, s, t): 144 | if s == None: 145 | return t 146 | 147 | if t == None: 148 | return s 149 | 150 | x = self.maximum(s) 151 | self.__splay(x) 152 | x.right = t 153 | t.parent = x 154 | return x 155 | 156 | def __pre_order_helper(self, node): 157 | if node != None: 158 | sys.stdout.write(node.data + " ") 159 | self.__pre_order_helper(node.left) 160 | self.__pre_order_helper(node.right) 161 | 162 | def __in_order_helper(self, node): 163 | if node != None: 164 | self.__in_order_helper(node.left) 165 | sys.stdout.write(node.data + " ") 166 | self.__in_order_helper(node.right) 167 | 168 | def __post_order_helper(self, node): 169 | if node != None: 170 | self.__post_order_helper(node.left) 171 | self.__post_order_helper(node.right) 172 | sys.std.out.write(node.data + " ") 173 | 174 | # Pre-Order traversal 175 | # Node->Left Subtree->Right Subtree 176 | def preorder(self): 177 | self.__pre_order_helper(self.root) 178 | 179 | # In-Order traversal 180 | # Left Subtree -> Node -> Right Subtree 181 | def inorder(self): 182 | self.__in_order_helper(self.root) 183 | 184 | # Post-Order traversal 185 | # Left Subtree -> Right Subtree -> Node 186 | def postorder(self): 187 | self.__post_order_helper(self.root) 188 | 189 | # search the tree for the key k 190 | # and return the corresponding node 191 | def search_tree(self, k): 192 | x = self.__search_tree_helper(self.root, k) 193 | if x != None: 194 | self.__splay(x) 195 | 196 | # find the node with the minimum key 197 | def minimum(self, node): 198 | while node.left != None: 199 | node = node.left 200 | return node 201 | 202 | # find the node with the maximum key 203 | def maximum(self, node): 204 | while node.right != None: 205 | node = node.right 206 | return node 207 | 208 | # find the successor of a given node 209 | def successor(self, x): 210 | # if the right subtree is not null, 211 | # the successor is the leftmost node in the 212 | # right subtree 213 | if x.right != None: 214 | return self.minimum(x.right) 215 | 216 | # else it is the lowest ancestor of x whose 217 | # left child is also an ancestor of x. 218 | y = x.parent 219 | while y != None and x == y.right: 220 | x = y 221 | y = y.parent 222 | return y 223 | 224 | # find the predecessor of a given node 225 | def predecessor(self, x): 226 | # if the left subtree is not null, 227 | # the predecessor is the rightmost node in the 228 | # left subtree 229 | if x.left != None: 230 | return self.maximum(x.left) 231 | 232 | y = x.parent 233 | while y != None and x == y.left: 234 | x = y 235 | y = y.parent 236 | return y 237 | 238 | # insert the key to the tree in its appropriate position 239 | def insert(self, key): 240 | node = Node(key) 241 | y = None 242 | x = self.root 243 | 244 | while x != None: 245 | y = x 246 | if node.data < x.data: 247 | x = x.left 248 | else: 249 | x = x.right 250 | 251 | # y is parent of x 252 | node.parent = y 253 | if y == None: 254 | self.root = node 255 | elif node.data < y.data: 256 | y.left = node 257 | else: 258 | y.right = node 259 | # splay the node 260 | self.__splay(node) 261 | 262 | # delete the node from the tree 263 | def delete_node(self, data): 264 | self.__delete_node_helper(self.root, data) 265 | 266 | # print the tree structure on the screen 267 | def pretty_print(self): 268 | self.__print_helper(self.root, "", True) 269 | 270 | if __name__ == '__main__': 271 | tree = SplayTree() 272 | tree.insert(33) 273 | tree.insert(44) 274 | tree.insert(67) 275 | tree.insert(5) 276 | tree.insert(89) 277 | tree.insert(41) 278 | tree.insert(98) 279 | tree.insert(1) 280 | tree.pretty_print() 281 | tree.search_tree(33) 282 | tree.search_tree(44) 283 | tree.pretty_print() 284 | tree.delete_node(89) 285 | tree.delete_node(67) 286 | tree.delete_node(41) 287 | tree.delete_node(5) 288 | tree.pretty_print() 289 | tree.delete_node(98) 290 | tree.delete_node(1) 291 | tree.delete_node(44) 292 | tree.delete_node(33) 293 | tree.pretty_print() 294 | -------------------------------------------------------------------------------- /data-structures/stacks/MyStack.cpp: -------------------------------------------------------------------------------- 1 | // C++ implementation of Stack using array 2 | 3 | #include 4 | 5 | using namespace std; 6 | 7 | class MyStack { 8 | private: 9 | const static int MAX_SIZE = 10; 10 | int stack[MAX_SIZE]; 11 | int top; 12 | public: 13 | MyStack() { 14 | top = -1; 15 | } 16 | 17 | // inserts item at the top of the stack 18 | void push(int item) { 19 | // check for overflow 20 | if (top >= MAX_SIZE - 1) { 21 | cout<<"Error: Can not push item. Stack Overflow"<= MAX_SIZE - 1) { 17 | System.out.println("Error: Can not push item. Stack Overflow"); 18 | return; 19 | } 20 | 21 | // insert the item and update the top 22 | stack[top + 1] = item; 23 | top = top + 1; 24 | } 25 | 26 | // removes item from the top of the stack 27 | public int pop() { 28 | // check for underflow 29 | if (top <= -1) { 30 | System.out.println("Error: Can not pop item. Stack Underflow"); 31 | return -999999; 32 | } 33 | 34 | top = top - 1; 35 | return stack[top + 1]; 36 | } 37 | 38 | // returns the item at the top 39 | public int peek() { 40 | // check for underflow 41 | if (top <= -1) { 42 | System.out.println("Error: Can not read item. Stack Underflow"); 43 | return - 999999; 44 | } 45 | 46 | return stack[top]; 47 | } 48 | 49 | public static void main(String [] args) { 50 | MyStack stack = new MyStack(); 51 | stack.push(22); 52 | stack.push(44); 53 | System.out.println(stack.peek()); 54 | System.out.println(stack.pop()); 55 | System.out.println(stack.peek()); 56 | } 57 | } -------------------------------------------------------------------------------- /data-structures/stacks/MyStackLinkedList.cpp: -------------------------------------------------------------------------------- 1 | // C++ implementation of stack using linked list 2 | #include 3 | using namespace std; 4 | 5 | struct Node { 6 | int data; 7 | Node *next; 8 | Node *prev; 9 | }; 10 | 11 | typedef Node *NodePtr; 12 | 13 | class MyStackLinkedList { 14 | private: 15 | NodePtr tail; 16 | public: 17 | MyStackLinkedList() { 18 | tail = nullptr; 19 | } 20 | 21 | // push operation 22 | void push(int item) { 23 | NodePtr node = new Node; 24 | node->data = item; 25 | node->next = nullptr; 26 | node->prev = nullptr; 27 | 28 | if (tail == nullptr) { 29 | tail = node; 30 | } else { 31 | tail->next = node; 32 | node->prev = tail; 33 | tail = node; 34 | } 35 | } 36 | 37 | // pop operation 38 | int pop() { 39 | if (tail == nullptr) { 40 | cout<<"ERROR: stack is empty"<data; 45 | NodePtr prev = tail->prev; 46 | if (prev != nullptr) { 47 | prev->next = nullptr; 48 | } 49 | tail->prev = nullptr; 50 | delete tail; 51 | tail = prev; 52 | return item; 53 | } 54 | 55 | 56 | // peek (top) operation 57 | int peek() { 58 | if (tail == nullptr) { 59 | cout<<"ERROR: stack is empty"<data; 64 | } 65 | 66 | }; 67 | 68 | int main() { 69 | MyStackLinkedList stack; 70 | stack.push(44); 71 | stack.push(33); 72 | cout< 4 | #define MAX_SIZE 10 5 | 6 | // global variables 7 | int stack[MAX_SIZE]; 8 | int top = -1; 9 | 10 | // inserts item at the top of the stack 11 | void push(int item) { 12 | // check for overflow 13 | if (top >= MAX_SIZE - 1) { 14 | printf("%s\n", "Error: Can not push item. Stack Overflow"); 15 | return; 16 | } 17 | 18 | // insert the item and update the top 19 | stack[top + 1] = item; 20 | top = top + 1; 21 | } 22 | 23 | 24 | // removes item from the top of the stack 25 | int pop() { 26 | // check for underflow 27 | if (top <= -1) { 28 | printf("%s\n", "Error: Can not pop item. Stack Underflow"); 29 | return -999999; 30 | } 31 | 32 | top = top - 1; 33 | return stack[top + 1]; 34 | } 35 | 36 | // returns the item at the top 37 | int peek() { 38 | // check for underflow 39 | if (top <= -1) { 40 | printf("%s\n", "Error: Can not read item. Stack Underflow"); 41 | return - 999999; 42 | } 43 | 44 | return stack[top]; 45 | } 46 | 47 | int main() { 48 | push(12); 49 | push(45); 50 | push(33); 51 | push(35); 52 | push(39); 53 | push(53); 54 | push(30); 55 | push(98); 56 | push(34); 57 | push(78); 58 | push(3100); 59 | printf("%d\n", pop()); 60 | printf("%d\n", pop()); 61 | printf("%d\n", pop()); 62 | printf("%d\n", pop()); 63 | printf("%d\n", pop()); 64 | printf("%d\n", peek()); 65 | printf("%d\n", peek()); 66 | return 0; 67 | } 68 | -------------------------------------------------------------------------------- /data-structures/stacks/my_stack.py: -------------------------------------------------------------------------------- 1 | # Python implementation of stack using linked list 2 | 3 | class Node: 4 | def __init__(self, item): 5 | self.data = item 6 | self.prev = None 7 | self.next = None 8 | 9 | class MyStack: 10 | def __init__(self): 11 | self.tail = None 12 | 13 | def push(self, item): 14 | node = Node(item) 15 | 16 | if self.tail == None: 17 | self.tail = node 18 | else: 19 | node.prev = self.tail 20 | self.tail.next = node 21 | self.tail = node 22 | 23 | def pop(self): 24 | if self.tail == None: 25 | print "ERROR: Stack is empty" 26 | return 27 | 28 | item = self.tail.data 29 | prev = self.tail.prev 30 | if prev != None: 31 | prev.next = None 32 | self.tail.prev = None 33 | self.tail = prev 34 | return item 35 | 36 | def peek(self): 37 | if self.tail == None: 38 | print "ERROR: Stack is empty" 39 | return 40 | return self.tail.data 41 | 42 | if __name__ == '__main__': 43 | stack = MyStack() 44 | stack.push(44) 45 | stack.push(34) 46 | stack.push(22) 47 | print stack.pop() 48 | print stack.pop() 49 | print stack.peek() -------------------------------------------------------------------------------- /data-structures/stacks/my_stack_linked_list.c: -------------------------------------------------------------------------------- 1 | // C implementation of stack using linked list 2 | 3 | #include 4 | #include 5 | 6 | struct Node { 7 | int data; 8 | struct Node *next; 9 | struct Node *prev; 10 | }; 11 | 12 | typedef struct Node *NodePtr; 13 | 14 | // globally define tail 15 | NodePtr tail = NULL; 16 | 17 | // Push operation 18 | void push(int item) { 19 | NodePtr node = malloc(sizeof(NodePtr)); 20 | node->data = item; 21 | node->next = NULL; 22 | node->prev = NULL; 23 | 24 | if (tail == NULL) { 25 | tail = node; 26 | } else { 27 | tail->next = node; 28 | node->prev = tail; 29 | tail = node; 30 | } 31 | } 32 | 33 | // pop operation 34 | int pop() { 35 | int item; 36 | if (tail == NULL){ 37 | printf("%s\n", "ERROR: Stack is empty"); 38 | return -999999; 39 | } 40 | 41 | item = tail->data; 42 | NodePtr prev = tail->prev; 43 | if (prev != NULL) { 44 | prev->next = NULL; 45 | } 46 | tail->prev = NULL; 47 | free(tail); 48 | tail = prev; 49 | return item; 50 | 51 | } 52 | 53 | // top (peek) operation 54 | int peek() { 55 | if (tail == NULL){ 56 | printf("%s\n", "ERROR: Stack is empty"); 57 | return -999999; 58 | } 59 | 60 | return tail->data; 61 | } 62 | 63 | int main() { 64 | push(33); 65 | push(22); 66 | push(44); 67 | printf("%d\n", pop()); 68 | printf("%d\n", peek()); 69 | return 0; 70 | } -------------------------------------------------------------------------------- /data-structures/treaps/Treap.cpp: -------------------------------------------------------------------------------- 1 | // Treap data structure implementation in C++ 2 | // Author: Algorithm Tutor 3 | 4 | #include 5 | 6 | using namespace std; 7 | 8 | // data structure that represents a node in the tree 9 | struct Node { 10 | int data; // holds the key 11 | float priority; // priority of the node 12 | Node *parent; // pointer to the parent 13 | Node *left; // pointer to left child 14 | Node *right; // pointer to right child 15 | }; 16 | 17 | typedef Node *NodePtr; 18 | 19 | // class Treap implements the operations in Treap Data Structure 20 | class Treap { 21 | private: 22 | NodePtr root; 23 | 24 | void preOrderHelper(NodePtr node) { 25 | if (node != nullptr) { 26 | cout<data<<" "; 27 | preOrderHelper(node->left); 28 | preOrderHelper(node->right); 29 | } 30 | } 31 | 32 | void inOrderHelper(NodePtr node) { 33 | if (node != nullptr) { 34 | inOrderHelper(node->left); 35 | cout<data<<" "; 36 | inOrderHelper(node->right); 37 | } 38 | } 39 | 40 | void postOrderHelper(NodePtr node) { 41 | if (node != nullptr) { 42 | postOrderHelper(node->left); 43 | postOrderHelper(node->right); 44 | cout<data<<" "; 45 | } 46 | } 47 | 48 | NodePtr searchTreeHelper(NodePtr node, int key) { 49 | if (node == nullptr || key == node->data) { 50 | return node; 51 | } 52 | 53 | if (key < node->data) { 54 | return searchTreeHelper(node->left, key); 55 | } 56 | return searchTreeHelper(node->right, key); 57 | } 58 | 59 | 60 | 61 | void printHelper(NodePtr root, string indent, bool last) { 62 | // print the tree structure on the screen 63 | if (root != nullptr) { 64 | cout<data<<"("<priority<<")"<left, indent, false); 76 | printHelper(root->right, indent, true); 77 | } 78 | } 79 | 80 | // rotate left at node x 81 | void leftRotate(NodePtr x) { 82 | NodePtr y = x->right; 83 | x->right = y->left; 84 | if (y->left != nullptr) { 85 | y->left->parent = x; 86 | } 87 | y->parent = x->parent; 88 | if (x->parent == nullptr) { 89 | this->root = y; 90 | } else if (x == x->parent->left) { 91 | x->parent->left = y; 92 | } else { 93 | x->parent->right = y; 94 | } 95 | y->left = x; 96 | x->parent = y; 97 | } 98 | 99 | // rotate right at node x 100 | void rightRotate(NodePtr x) { 101 | NodePtr y = x->left; 102 | x->left = y->right; 103 | if (y->right != nullptr) { 104 | y->right->parent = x; 105 | } 106 | y->parent = x->parent; 107 | if (x->parent == nullptr) { 108 | this->root = y; 109 | } else if (x == x->parent->right) { 110 | x->parent->right = y; 111 | } else { 112 | x->parent->left = y; 113 | } 114 | y->right = x; 115 | x->parent = y; 116 | } 117 | 118 | // we move the node up until its priority is greater than 119 | // or equal the parent's priority 120 | void moveUp(NodePtr x) { 121 | if (x->parent == nullptr) { 122 | return; 123 | } 124 | if (x->parent != nullptr && x->priority >= x->parent->priority) { 125 | return; 126 | } 127 | 128 | if (x == x->parent->left) { 129 | rightRotate(x->parent); 130 | } else { 131 | leftRotate(x->parent); 132 | } 133 | 134 | // recursively move the x up 135 | moveUp(x); 136 | } 137 | 138 | // delete key k 139 | void deleteNodeHelper(NodePtr node, int k) { 140 | // find k 141 | NodePtr x = nullptr; 142 | while (node != nullptr) { 143 | if (node->data == k) { 144 | x = node; 145 | break; 146 | } 147 | 148 | if (node->data <= k) { 149 | node = node->right; 150 | } else { 151 | node = node->left; 152 | } 153 | } 154 | 155 | if (x == nullptr) { 156 | cout<<"couldn't find the "<parent->left) { 166 | x->parent->left = nullptr; 167 | } else { 168 | x->parent->right = nullptr; 169 | } 170 | delete x; 171 | x = nullptr; 172 | } 173 | 174 | // move down x to the leaf of the tree 175 | void moveDown(NodePtr x) { 176 | if (x->left == nullptr && x->right == nullptr) { 177 | return; 178 | } 179 | 180 | if (x->left != nullptr && x->right != nullptr) { 181 | if (x->left->priority < x->right->priority) { 182 | rightRotate(x); 183 | } else { 184 | leftRotate(x); 185 | } 186 | } else if (x->left != nullptr) { 187 | rightRotate(x); 188 | } else { 189 | leftRotate(x); 190 | } 191 | 192 | moveDown(x); 193 | } 194 | 195 | public: 196 | Treap() { 197 | root = nullptr; 198 | } 199 | 200 | // Pre-Order traversal 201 | // Node->Left Subtree->Right Subtree 202 | void preorder() { 203 | preOrderHelper(this->root); 204 | } 205 | 206 | // In-Order traversal 207 | // Left Subtree -> Node -> Right Subtree 208 | void inorder() { 209 | inOrderHelper(this->root); 210 | } 211 | 212 | // Post-Order traversal 213 | // Left Subtree -> Right Subtree -> Node 214 | void postorder() { 215 | postOrderHelper(this->root); 216 | } 217 | 218 | // search the tree for the key k 219 | // and return the corresponding node 220 | NodePtr searchTree(int k) { 221 | return searchTreeHelper(this->root, k); 222 | } 223 | 224 | // find the node with the minimum key 225 | NodePtr minimum(NodePtr node) { 226 | while (node->left != nullptr) { 227 | node = node->left; 228 | } 229 | return node; 230 | } 231 | 232 | // find the node with the maximum key 233 | NodePtr maximum(NodePtr node) { 234 | while (node->right != nullptr) { 235 | node = node->right; 236 | } 237 | return node; 238 | } 239 | 240 | // find the successor of a given node 241 | NodePtr successor(NodePtr x) { 242 | // if the right subtree is not null, 243 | // the successor is the leftmost node in the 244 | // right subtree 245 | if (x->right != nullptr) { 246 | return minimum(x->right); 247 | } 248 | 249 | // else it is the lowest ancestor of x whose 250 | // left child is also an ancestor of x. 251 | NodePtr y = x->parent; 252 | while (y != nullptr && x == y->right) { 253 | x = y; 254 | y = y->parent; 255 | } 256 | return y; 257 | } 258 | 259 | // find the predecessor of a given node 260 | NodePtr predecessor(NodePtr x) { 261 | // if the left subtree is not null, 262 | // the predecessor is the rightmost node in the 263 | // left subtree 264 | if (x->left != nullptr) { 265 | return maximum(x->left); 266 | } 267 | 268 | NodePtr y = x->parent; 269 | while (y != nullptr && x == y->left) { 270 | x = y; 271 | y = y->parent; 272 | } 273 | 274 | return y; 275 | } 276 | 277 | // insert the key to the tree in its appropriate position 278 | void insert(int key, float priority) { 279 | NodePtr node = new Node; 280 | node->parent = nullptr; 281 | node->left = nullptr; 282 | node->right = nullptr; 283 | node->data = key; 284 | node->priority = priority; 285 | NodePtr y = nullptr; 286 | NodePtr x = this->root; 287 | 288 | while (x != nullptr) { 289 | y = x; 290 | if (node->data < x->data) { 291 | x = x->left; 292 | } else { 293 | x = x->right; 294 | } 295 | } 296 | 297 | // y is parent of x 298 | node->parent = y; 299 | if (y == nullptr) { 300 | root = node; 301 | } else if (node->data < y->data) { 302 | y->left = node; 303 | } else { 304 | y->right = node; 305 | } 306 | 307 | // rotate the tree to fix the priorities. 308 | if (node->parent != nullptr) { 309 | moveUp(node); 310 | } 311 | } 312 | 313 | // split the tree into two trees 314 | void split(int x, Treap* t1, Treap* t2) { 315 | // insert a dummy node with lowest priority 316 | this->insert(x, -99); 317 | 318 | // this node is in the root node 319 | t1->root = this->root->left; 320 | t2->root = this->root->right; 321 | 322 | this->root->left = nullptr; 323 | this->root->right = nullptr; 324 | delete this->root; 325 | this->root = nullptr; 326 | } 327 | 328 | // merge trees t1 and t2 329 | void merge(Treap t1, Treap t2) { 330 | // find the largest node in t1 331 | NodePtr largest = t1.maximum(t1.root); 332 | // find the smallest node in t2 333 | NodePtr smallest = t2.minimum(t2.root); 334 | 335 | // create a dummy node 336 | NodePtr newRoot = new Node(); 337 | newRoot->data = (largest->data + smallest->data) / 2; 338 | newRoot->left = t1.root; 339 | newRoot->right = t2.root; 340 | newRoot->parent = nullptr; 341 | newRoot->priority = 99; 342 | 343 | // move down the dummy node to the leaf node 344 | moveDown(newRoot); 345 | 346 | NodePtr currPtr = newRoot; 347 | while(currPtr->parent != nullptr) { 348 | currPtr = currPtr->parent; 349 | } 350 | 351 | this->root = currPtr; 352 | 353 | if (newRoot == newRoot->parent->left) { 354 | newRoot->parent->left = nullptr; 355 | } else { 356 | newRoot->parent->right = nullptr; 357 | } 358 | 359 | // delete the dummy node 360 | delete(newRoot); 361 | newRoot = nullptr; 362 | 363 | } 364 | 365 | NodePtr getRoot(){ 366 | return this->root; 367 | } 368 | 369 | // delete the node from the tree 370 | void deleteNode(int data) { 371 | deleteNodeHelper(this->root, data); 372 | } 373 | 374 | // print the tree structure on the screen 375 | void prettyPrint() { 376 | printHelper(this->root, "", true); 377 | } 378 | 379 | }; 380 | 381 | int main() { 382 | Treap bst; 383 | // test insert 384 | bst.insert(5, 0.30143); 385 | bst.insert(7, 0.47493); 386 | bst.insert(19, 0.54531); 387 | bst.insert(23, 0.46047); 388 | bst.insert(30, 0.73010); 389 | bst.insert(31, 0.28807); 390 | bst.insert(45, 0.99760); 391 | bst.insert(48, 0.51079); 392 | bst.insert(51, 0.98976); 393 | bst.insert(25, 0.22342); 394 | bst.prettyPrint(); 395 | cout<