├── .gitignore ├── AVL ├── Avl.cpp └── rotation.c ├── Advanced ├── Trie.cpp └── binaryIndexTree.cpp ├── Arrays ├── DynamicMemory │ ├── array_heap.c │ └── malloc.c ├── OperationsOnArrays │ ├── array_Menu.c │ ├── array_append.c │ ├── array_delete.c │ ├── array_difference.c │ ├── array_display.c │ ├── array_insert.c │ ├── array_insertSort.c │ └── array_operation.c ├── RecursiveArrays │ ├── array_headRecursion.c │ ├── array_usingRecursion.c │ └── recursive_array.c ├── SearchingInArrays │ ├── array_linearSearch.c │ ├── array_linearSearchImproved.c │ ├── array_linearSearschTransposition.c │ ├── array_multiple_missing.c │ ├── array_using_recursion.c │ ├── arrays_returnMissing.c │ ├── binarySearch_iterative.c │ └── binarySearch_recursive.c └── SetOperation │ ├── array_intersection.c │ ├── array_rearrange.c │ ├── array_reverse.c │ ├── array_shift.c │ ├── array_sorted.c │ ├── array_unsorted_union.c │ ├── arrays_merge.c │ └── arrays_union.c ├── BST ├── C │ ├── Queue.h │ ├── createBST.c │ ├── main.c │ ├── recursive.c │ └── stack.h └── CPP │ ├── BstClass.cpp │ └── bstGeneration.cpp ├── Graph ├── kruskal's.cpp ├── main.cpp └── spanningTreeClass.cpp ├── HashTable ├── chaining.cpp ├── doubleHashing.cpp ├── linearProbing.cpp └── quadraticProbing.cpp ├── Heap ├── C │ ├── MaxHeap │ │ └── createHeap.c │ ├── MinHeap │ │ └── createHeap.c │ └── heapify.c └── CPP │ ├── heapify.cpp │ └── maxHeap.cpp ├── LinkedList ├── DoublyLinkedList │ └── doublyLinkList.c ├── IterativeLinkedList │ ├── addition_on_linkedList_iterative.c │ ├── count_of_nodes.iterative.c │ ├── createListByinsert.c │ ├── displaying_linkedList_iterative.c │ ├── insertInSortedList.c │ ├── insert_iterative.c │ └── linearSearch_iterative.c ├── RecursiveLinkedList │ ├── addition_on_linkedList_recursive.c │ ├── countNodes.c.c │ ├── displaying_linkedList_recursive.c │ ├── linearSearch_recursive.c │ └── reversingLinksrecursively.c ├── circularLinkedList │ ├── CircularLinkListRecursive.c │ ├── circularDoublyLinkList.c │ └── circularLinkListIterative.c ├── operationsOnLinkedList │ ├── checkSort.c │ ├── concatLinkLists.c │ ├── linkedList_delete.c │ ├── loopDetection.c │ ├── mergeTwoLinks.c │ ├── removingDuplicates.c │ ├── reversingElements.c │ └── reversingLinks.c └── studentChallenge │ ├── findMidInSinglyLL.c │ ├── middleElement.c │ ├── polynomial.c │ └── sparseMatrix.c ├── Makefile ├── Matrices ├── Lower-triangular-matrix │ ├── column_major_method.c │ ├── lower_triangular_matrix.c │ └── row_major_method.c ├── TriDiagonal_matrix.c ├── Upper-triangular-matrix │ ├── column_major_mapping.c │ └── row_major_mapping.c ├── diagonal_matrix.c ├── matrixClass.cpp ├── polynomial_addition.c ├── sparse_matrix.cpp ├── symmetric_matrix.c └── toeplitz_matrix.c ├── Queue ├── DEQueue.c ├── QueueArray.c ├── QueueLL.c ├── QueueStack.c ├── circularQueueArray.c └── recursiveQueue.c ├── README.md ├── Stack ├── StackArray.c ├── StackLL.c └── application.c ├── Strings └── permutation.cpp └── binarytree ├── C ├── Queue.h ├── create_tree.c ├── iterativeOrder.c ├── levelorder.c ├── nodes.c ├── postorder.c ├── stack.h └── tree.h └── CPP ├── binaryTree.cpp ├── generateTree.cpp └── traversals.cpp /.gitignore: -------------------------------------------------------------------------------- 1 | *.app 2 | -------------------------------------------------------------------------------- /AVL/rotation.c: -------------------------------------------------------------------------------- 1 | /* 2 | Author : Fakhra Najm 3 | Email : fnajm09@gmail.com 4 | Topic : Rotation 5 | 6 | Operations: 7 | * createNode 8 | * insert 9 | * Inorder 10 | * LL_Rotation 11 | * LR_Rotation 12 | * RR_Rotation 13 | * RL_Rotation 14 | * Balance_factor 15 | * Node_height 16 | * Rotate 17 | 18 | */ 19 | 20 | #include 21 | #include 22 | 23 | 24 | struct Node{ 25 | int data; 26 | 27 | struct Node *left; 28 | struct Node *right; 29 | 30 | int height; 31 | 32 | }*root = NULL; 33 | 34 | int node_height(struct Node *node){ 35 | 36 | int left, right; 37 | 38 | left = node && node->left ? node->left->height : 0; 39 | right = node && node->right ? node->right->height : 0; 40 | 41 | return left > right ? left+1 : right+1; 42 | } 43 | 44 | 45 | struct Node * LR_Rotation(struct Node *node){ 46 | struct Node *node_left = node->left; 47 | struct Node *left_right = node_left->right; 48 | 49 | node_left->right = left_right->left; 50 | node->left = left_right->right; 51 | 52 | left_right->left = node->left; 53 | left_right->right = node; 54 | 55 | node->height = node_height(node); 56 | node_left->height = node_height(node_left); 57 | left_right->height = node_height(left_right); 58 | 59 | if(root == node) 60 | root = left_right; 61 | 62 | return left_right; 63 | } 64 | 65 | 66 | struct Node *RL_Rotation(struct Node *node){ 67 | struct Node * right_node = node->right; 68 | struct Node * right_left = right_node->left; 69 | 70 | 71 | right_left->left = node; 72 | right_left->right = right_node; 73 | 74 | if(root == node) 75 | root = right_left; 76 | 77 | node->height = node_height(node); 78 | right_node->height = node_height(right_node); 79 | right_left->height = node_height(right_left); 80 | 81 | return right_left; 82 | } 83 | 84 | 85 | struct Node * RR_Rotation(struct Node *node){ 86 | 87 | struct Node * right_node = node->right; 88 | struct Node * right_left = right_node->left; 89 | 90 | node->right = right_left; 91 | right_node->left = node; 92 | 93 | node->height = node_height(node); 94 | right_node->height = node_height(right_node); 95 | 96 | if(root == node) 97 | root = right_node; 98 | 99 | return right_node; 100 | 101 | } 102 | 103 | struct Node *LL_Rotation(struct Node *node){ 104 | 105 | struct Node *left_node = node->left; 106 | struct Node * left_right = left_node->right; 107 | 108 | left_node->right = node; 109 | node->left = left_right; 110 | 111 | node->height = node_height(node); 112 | left_node->height = node_height(left_node); 113 | 114 | if(root == node) 115 | root = left_node; 116 | 117 | return left_node; 118 | } 119 | 120 | 121 | struct Node * createNode(struct Node *node, int value){ 122 | 123 | node = (struct Node *)malloc(sizeof(struct Node)); 124 | 125 | node->data = value; 126 | node->height = 1; 127 | 128 | node->left = node->right = NULL; 129 | 130 | return node; 131 | } 132 | 133 | 134 | void Inorder(struct Node *root){ 135 | 136 | if(root){ 137 | 138 | Inorder(root->left); 139 | 140 | printf("%d ",root->data); 141 | 142 | Inorder(root->right); 143 | } 144 | 145 | } 146 | 147 | int Balance_factor(struct Node *node){ 148 | 149 | int left, right; 150 | 151 | left = node && node->left ? node->left->height : 0; 152 | right = node && node->right ? node->right->height : 0; 153 | 154 | return left - right; 155 | } 156 | 157 | 158 | struct Node *Rotate(struct Node *node, int BALANCE_FACTOR){ 159 | int bf; 160 | if(BALANCE_FACTOR == 2){ 161 | 162 | bf = Balance_factor(node->left); 163 | 164 | if(bf == 1) 165 | node = LL_Rotation(node); 166 | 167 | else if(bf == -1) 168 | node = LR_Rotation(node); 169 | } 170 | 171 | else if(BALANCE_FACTOR == -2){ 172 | 173 | bf = Balance_factor(node->right); 174 | 175 | if(bf == 1) 176 | node = RL_Rotation(node); 177 | 178 | else if(bf == -1) 179 | node = RR_Rotation(node); 180 | } 181 | 182 | return node; 183 | } 184 | 185 | 186 | struct Node * insert(struct Node *node, int value){ 187 | 188 | struct Node *temp = NULL; 189 | int BALANCE_FACTOR; 190 | 191 | if(node == NULL){ 192 | return createNode(temp, value); 193 | } 194 | 195 | if(node->data > value) 196 | node->left = insert(node->left, value); 197 | 198 | else if(node->data < value) 199 | node->right = insert(node->right, value); 200 | 201 | node->height = node_height(node); 202 | 203 | BALANCE_FACTOR = Balance_factor(node); 204 | Rotate(node, BALANCE_FACTOR); 205 | return node; 206 | } 207 | 208 | 209 | int main(){ 210 | root = insert(root, 30); 211 | insert(root, 20); 212 | insert(root, 40); 213 | insert(root, 50); 214 | insert(root, 10); 215 | insert(root, 25); 216 | insert(root, 5); 217 | insert(root, 15); 218 | insert(root, 28); 219 | insert(root, 4); 220 | Inorder(root); 221 | printf("\n%d", Balance_factor(root)); 222 | return 0; 223 | } 224 | -------------------------------------------------------------------------------- /Advanced/Trie.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Author : Fakhra Najm 3 | * Topic : Implementation of Trie Datastructure 4 | * A Trie is a special data structure used to store strings that can be visualized like a graph. 5 | * They are used to represent the “Retrieval” of data and thus the name Trie. 6 | * Application - String Processing 7 | - Search Engine 8 | - Gnome analysis 9 | - Data Analytics 10 | */ 11 | 12 | #include 13 | using namespace std; 14 | 15 | class Trie{ 16 | map next = {}; 17 | bool isWord = false; 18 | 19 | public: 20 | 21 | void update(string word){ 22 | Trie *node = this; 23 | for(auto letter : word){ 24 | if(!node -> next[letter]) node -> next[letter] = new Trie(); 25 | node = node -> next[letter]; 26 | } 27 | node -> isWord = true; 28 | } 29 | 30 | bool read(string word){ 31 | Trie *node = this; 32 | 33 | for(auto letter : word){ 34 | if(!node -> next[letter]) return false; 35 | node = node -> next[letter]; 36 | } 37 | return node -> isWord; 38 | } 39 | 40 | bool isPrefix(string prefix){ 41 | Trie *node = this; 42 | for(auto letter : prefix){ 43 | if(!node -> next[letter]) return false; 44 | node = node -> next[letter]; 45 | } 46 | return true; 47 | } 48 | }; 49 | 50 | int main(){ 51 | Trie trie; 52 | string word, prefix, search; 53 | cout << "Enter String : " << endl; 54 | cin >> word; 55 | trie.update(word); 56 | cout << "Enter Prefix : " << endl; 57 | cin >> prefix; 58 | if(trie.isPrefix(prefix)) cout << "Prefix found" << endl; 59 | else cout << "Prefix Not Found " << endl; 60 | cout << "Enter word to search : " << endl; 61 | cin >> search; 62 | if(trie.read(search)) cout << "Word found" << endl; 63 | else cout << "Word Not Found " << endl; 64 | 65 | return 0; 66 | } -------------------------------------------------------------------------------- /Advanced/binaryIndexTree.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | Buid binary indexed tree using Array 3 | 4 | Use case: Range queries 5 | - finding sum from index i to j of an array. 6 | operations: 7 | - update -> log(n) 8 | - read -> log(n) 9 | 10 | Reference: https://www.topcoder.com/community/competitive-programming/tutorials/range-minimum-query-and-lowest-common-ancestor/ 11 | */ 12 | #include 13 | #include 14 | using namespace std; 15 | 16 | class BinaryIndexTree { 17 | vector values; 18 | vector binaryIndexTree; 19 | int maxIdx; 20 | 21 | // build tree using updates 22 | void build() { 23 | for(int i = 0; i < values.size(); i++) { 24 | update(values[i], i); 25 | } 26 | } 27 | public: 28 | BinaryIndexTree(vector values) { 29 | this -> values = values; 30 | this -> binaryIndexTree.resize(values.size() + 1); 31 | this -> maxIdx = binaryIndexTree.size(); 32 | build(); 33 | } 34 | // update binaryIndexTree after update in original array at index idx 35 | void update(int val, int idx) { 36 | values[idx] = val; 37 | idx++; 38 | while(idx <= maxIdx) { 39 | binaryIndexTree[idx] += val; 40 | idx += (idx & -idx); // toggle last set bit 41 | } 42 | } 43 | 44 | // returns sum from index 0 to idx 45 | int read(int idx) { 46 | int sum = 0; 47 | while(idx > 0) { 48 | sum += binaryIndexTree[idx]; 49 | idx -= (idx & -idx); // mark last set bit to zero 50 | } 51 | return sum; 52 | } 53 | 54 | // print tree stored in array 55 | void show() { 56 | for(int i : binaryIndexTree) cout<{1,0,2,1,1,3,0,4,2,5,2,2,3,1,0,2}); 63 | cout<<"Sum of values from index 0 to index 13: "<< tree.read(13)< 2 | #include 3 | 4 | int main() 5 | { 6 | int **p; 7 | int i,j; 8 | p=(int **)malloc(3*sizeof(int)); 9 | p[0]=(int **)malloc(4*sizeof(int)); 10 | p[1]=(int **)malloc(4*sizeof(int)); 11 | p[2]=(int **)malloc(4*sizeof(int)); 12 | 13 | for (i = 0; i < 3; ++i){ 14 | for (j = 0; j < 4; ++j){ 15 | printf("%d\n",p[i][j] ); 16 | } 17 | } 18 | } -------------------------------------------------------------------------------- /Arrays/DynamicMemory/malloc.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main() 5 | { 6 | int *p,*q; 7 | int i; 8 | p=(int *)malloc(5*sizeof(int)); 9 | p[0]=1; 10 | p[1]=3; 11 | p[2]=5; 12 | p[3]=7; 13 | p[4]=9; 14 | 15 | q=(int *)malloc(10*sizeof(int)); 16 | 17 | for (i=0; i<5; ++i) 18 | { 19 | q[i]=p[i]; 20 | } 21 | for ( i = 0; i < 5; ++i) 22 | { 23 | printf("%d\n",q[i] ); 24 | } 25 | 26 | free(p); 27 | p=q; 28 | q=NULL; 29 | for(i=0 ; i<5 ; ++i) 30 | printf("%d\n ",p[i] ); 31 | return 0; 32 | } 33 | -------------------------------------------------------------------------------- /Arrays/OperationsOnArrays/array_Menu.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | struct Array{ 5 | int *A; 6 | int size; 7 | int length; 8 | }; 9 | 10 | int Display(struct Array arr){ 11 | 12 | int i; 13 | 14 | printf("\nElements are:\n"); 15 | 16 | for(i=0; i=0 && index<=arr->length){ 24 | for ( i = arr->length ; i >index; i--) 25 | { 26 | arr->A[i]=arr->A[i-1]; 27 | } 28 | 29 | arr->A[index]=x; 30 | } 31 | arr->length++; 32 | } 33 | 34 | int Delete(struct Array *arr, int index){ 35 | int x=0; 36 | int i; 37 | if(index>=0 && indexlength){ 38 | x=arr->A[index]; 39 | for(i=index ; ilength-1 ; i++){ 40 | arr->A[i]=arr->A[i+1]; 41 | } 42 | arr->length--; 43 | return x; 44 | } 45 | return 0; 46 | } 47 | 48 | int LinearSearch(struct Array *arr , int key){ 49 | int i; 50 | for(i=0; ilength ; i++){ 51 | if(key==arr->A[i]) 52 | return i; 53 | } 54 | return -1; 55 | } 56 | 57 | int Sum(struct Array arr){ 58 | int s=0; 59 | int i; 60 | for(i=0; i 2 | #include 3 | 4 | struct Array{ 5 | int A[20]; 6 | int size; 7 | int length; 8 | }; 9 | 10 | 11 | int display_array(struct Array arr){ 12 | int i; 13 | for(i=0 ; ilength < arr->size){ 20 | arr->A[arr->length]=x; 21 | arr->length++; 22 | } 23 | } 24 | 25 | int main(){ 26 | struct Array arr={{2,3,4,5,6},20,5}; 27 | append_array(&arr , 10); 28 | display_array(arr); 29 | return 0; 30 | } -------------------------------------------------------------------------------- /Arrays/OperationsOnArrays/array_delete.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | struct Array{ 5 | int A[20]; 6 | int size; 7 | int length; 8 | }; 9 | 10 | void Display(struct Array arr){ 11 | int i; 12 | for(i=0 ; i < arr.length ; i++){ 13 | printf("%d\n",arr.A[i]); 14 | } 15 | } 16 | 17 | int Delete(struct Array *arr, int index){ 18 | int x=0; 19 | int i; 20 | if(index>=0 && indexlength){ 21 | x=arr->A[index]; 22 | for(i=index ; ilength-1 ; i++){ 23 | arr->A[i]=arr->A[i+1]; 24 | } 25 | arr->length--; 26 | return x; 27 | } 28 | return 0; 29 | } 30 | 31 | int main(){ 32 | struct Array arr = {{2,4,6,8,10,12,14,16,18,20},20,10}; 33 | Delete(&arr,5); 34 | Display(arr); 35 | return 0; 36 | } -------------------------------------------------------------------------------- /Arrays/OperationsOnArrays/array_difference.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | struct Array{ 5 | int A[20]; 6 | int size; 7 | int length; 8 | }; 9 | 10 | void Display(struct Array arr){ 11 | int i; 12 | for(i=0;ilength && jlength){ 22 | if(arr->A[i]A[j]) 23 | arr3->A[k++]=arr->A[i++]; 24 | else if(arr->A[i]>arr2->A[j]) 25 | j++; 26 | else if(arr->A[i]==arr2->A[j]){ 27 | i++; 28 | j++; 29 | } 30 | } 31 | for(;ilength;i++) 32 | arr3->A[k++]=arr->A[i]; 33 | arr3->length=k; 34 | arr3->size=arr->length+arr2->length; 35 | return arr3; 36 | } 37 | 38 | 39 | int main(){ 40 | struct Array x = {{2,3,4,5,6},20,5}; 41 | struct Array y = {{1,3,5,7,9},20,5}; 42 | struct Array *z; 43 | z=Difference_of_Arrays(&x,&y); 44 | Display(*z); 45 | } -------------------------------------------------------------------------------- /Arrays/OperationsOnArrays/array_display.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | struct Array{ 5 | int *A; 6 | int size; 7 | int length; 8 | }; 9 | 10 | int Display_array(struct Array arr){ 11 | 12 | int i; 13 | 14 | for(i=0; i 2 | #include 3 | 4 | struct Array{ 5 | int A[20]; 6 | int size; 7 | int length; 8 | }; 9 | 10 | void Display(struct Array arr){ 11 | int i; 12 | for(i=0 ; i < arr.length ; i++){ 13 | printf("%d\n",arr.A[i]); 14 | } 15 | } 16 | 17 | void Insert_array(struct Array *arr ,int index ,int x ){ 18 | int i; 19 | if(index>=0 && index<=arr->length){ 20 | for ( i = arr->length ; i >index; i--) 21 | { 22 | arr->A[i]=arr->A[i-1]; 23 | } 24 | 25 | arr->A[index]=x; 26 | } 27 | } 28 | 29 | int main(){ 30 | struct Array arr = {{2,4,6,8,10,12,14,16,18,20},20,5}; 31 | Insert_array(&arr,3,7); 32 | Display(arr); 33 | } -------------------------------------------------------------------------------- /Arrays/OperationsOnArrays/array_insertSort.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | struct Array{ 5 | int A[20]; 6 | int size; 7 | int length; 8 | }; 9 | 10 | void Display(struct Array arr){ 11 | int i; 12 | for(i=0; ilength-1; 19 | while(arr->A[i]>x){ 20 | arr->A[i+1]=arr->A[i]; 21 | i--; 22 | } 23 | arr->A[i+1]=x; 24 | arr->length++; 25 | 26 | } 27 | 28 | int main(){ 29 | struct Array arr={{5,10,15,20,25,30,35,40},20,7}; 30 | InsertSort(&arr,26); 31 | Display(arr); 32 | } -------------------------------------------------------------------------------- /Arrays/OperationsOnArrays/array_operation.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | struct Array{ 5 | int A[20]; 6 | int size; 7 | int length; 8 | }; 9 | 10 | 11 | int display_array(struct Array arr){ 12 | int i; 13 | 14 | for(i=0 ; i=0 && index=0 && indexlength) 27 | arr->A[index]=x; 28 | } 29 | 30 | int sum(struct Array arr){ 31 | int s=0; 32 | int i; 33 | for(i=0; iarr.A[i]) 57 | min=arr.A[i]; 58 | } 59 | return min; 60 | } 61 | 62 | int main(){ 63 | struct Array arr={{2,3,4,5,6},20,5}; 64 | printf("Get Result:%d\n",Get(arr,0) ); 65 | printf("maximum of the element is%d\nminimum of the element is%d\n",max(arr),min(arr) ); 66 | printf("Sum of all element:%d\n", sum(arr)); 67 | printf("Average of all element is:%f\n",Avg(arr) ); 68 | set(&arr,0,1); 69 | display_array(arr); 70 | return 0; 71 | } -------------------------------------------------------------------------------- /Arrays/RecursiveArrays/array_headRecursion.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void print_recursive(int a[],int n,int i) 4 | { 5 | if(i 2 | 3 | void print_recursive(int a[],int n,int i) 4 | { 5 | if(i 2 | int print_recursive(int a[],int n,int i) 3 | { 4 | if(i >= n) return 0; 5 | return 5*(a[i]*a[i])+ 1 + print_recursive(a, n, i + 1); 6 | } 7 | 8 | int main() 9 | { 10 | int a[]={1,2,3,4,5,6,7,8,9,10}; 11 | printf("%d", print_recursive(a,10,0)); 12 | return 0; 13 | } 14 | -------------------------------------------------------------------------------- /Arrays/SearchingInArrays/array_linearSearch.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | struct Array{ 5 | int A[20]; 6 | int size; 7 | int length; 8 | }; 9 | 10 | void Display(struct Array arr){ 11 | int i; 12 | for(i=0 ; i < arr.length ; i++){ 13 | printf("%d\n",arr.A[i]); 14 | } 15 | } 16 | 17 | int linearSearch(struct Array arr , int key){ 18 | int i; 19 | for(i=0; i 2 | #include 3 | 4 | struct Array{ 5 | int A[20]; 6 | int size; 7 | int length; 8 | }; 9 | 10 | void Display(struct Array arr){ 11 | int i; 12 | for(i=0 ; i < arr.length ; i++){ 13 | printf("%d\n",arr.A[i]); 14 | } 15 | } 16 | void swap(int *x ,int *y){ 17 | int temp; 18 | temp=*x; 19 | *x=*y; 20 | *y=temp; 21 | } 22 | 23 | int linearSearch_transposition(struct Array *arr ,int key){ 24 | int i; 25 | for(i=0; ilength ; i++){ 26 | if(key==arr->A[i]){ 27 | swap(&arr->A[i],&arr->A[0]); 28 | return i; 29 | } 30 | } 31 | return -1; 32 | } 33 | int main(){ 34 | struct Array arr = {{10,15,20,25,30,35,40,45,50,55,60,65},20,12}; 35 | printf("The index for 45 is:%d\n",linearSearch_transposition(&arr,45)); 36 | Display(arr); 37 | printf("The index for 45 is:%d\n",linearSearch_transposition(&arr,45)); 38 | return 0; 39 | } -------------------------------------------------------------------------------- /Arrays/SearchingInArrays/array_linearSearschTransposition.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | struct Array{ 5 | int A[20]; 6 | int size; 7 | int length; 8 | }; 9 | 10 | void Display(struct Array arr){ 11 | int i; 12 | for(i=0 ; i < arr.length ; i++){ 13 | printf("%d\n",arr.A[i]); 14 | } 15 | } 16 | void swap(int *x ,int *y){ 17 | int temp; 18 | temp=*x; 19 | *x=*y; 20 | *y=temp; 21 | } 22 | 23 | int linearSearch_transposition(struct Array *arr ,int key){ 24 | int i; 25 | for(i=0; ilength ; i++){ 26 | if(key==arr->A[i]){ 27 | swap(&arr->A[i],&arr->A[i-1]); 28 | return i; 29 | } 30 | } 31 | return -1; 32 | } 33 | int main(){ 34 | struct Array arr = {{10,15,20,25,30,35,40,45,50,55,60,65},20,12}; 35 | printf("%d\n",linearSearch_transposition(&arr,45)); 36 | Display(arr); 37 | return 0; 38 | } -------------------------------------------------------------------------------- /Arrays/SearchingInArrays/array_multiple_missing.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | struct Array{ 5 | int *A; 6 | int size; 7 | int length; 8 | }; 9 | 10 | int Display(struct Array arr){ 11 | 12 | int i; 13 | 14 | printf("\nElements are:\n"); 15 | 16 | for(i=0; i=0 && index<=arr->length){ 24 | for ( i = arr->length ; i >index; i--) 25 | { 26 | arr->A[i]=arr->A[i-1]; 27 | } 28 | 29 | arr->A[index]=x; 30 | } 31 | arr->length++; 32 | } 33 | 34 | int Delete(struct Array *arr, int index){ 35 | int x=0; 36 | int i; 37 | if(index>=0 && indexlength){ 38 | x=arr->A[index]; 39 | for(i=index ; ilength-1 ; i++){ 40 | arr->A[i]=arr->A[i+1]; 41 | } 42 | arr->length--; 43 | return x; 44 | } 45 | return 0; 46 | } 47 | 48 | int missing(struct Array * arr,int first){ 49 | int i, difference; 50 | difference=first-0; 51 | for(i=0;ilength;i++){ 52 | if(arr->A[i]-i!=difference){ 53 | printf("Missing element is %d\n",i+difference ); 54 | break; 55 | } 56 | } 57 | } 58 | 59 | int main() 60 | { 61 | int choice,index,x,f; 62 | struct Array arr; 63 | printf("Enter size of the array:"); 64 | scanf("%d",&arr.size); 65 | 66 | arr.A = (int*)malloc(arr.size*sizeof(int)); 67 | arr.length=0; 68 | 69 | do{ 70 | printf("\nMenu\n"); 71 | printf("1 . Insert\n"); 72 | printf("2 . Delete\n"); 73 | printf("3 . Display\n"); 74 | printf("4 . Missing\n"); 75 | printf("5 . Exit\n"); 76 | printf("Enter your choice:",choice); 77 | scanf("%d",&choice); 78 | switch(choice){ 79 | case 1:printf("Enter index:",index); 80 | scanf("%d",&index); 81 | printf("Enter Element:",x); 82 | scanf("%d",&x); 83 | Insert(&arr,index,x); 84 | break; 85 | case 2:printf("Enter index:",index); 86 | scanf("%d",&index); 87 | x=Delete(&arr,index); 88 | printf("Deleted element is %d",x); 89 | break; 90 | case 3:Display(arr); 91 | break; 92 | case 4:printf("Enter first element of the array:\n",f); 93 | scanf("%d",&f); 94 | missing(&arr,f); 95 | break; 96 | 97 | } 98 | }while(choice<5); 99 | return 0; 100 | } -------------------------------------------------------------------------------- /Arrays/SearchingInArrays/array_using_recursion.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void print_recursive(int a[],int n,int i) 4 | { 5 | if(i 2 | #include 3 | 4 | struct Array{ 5 | int *A; 6 | int size; 7 | int length; 8 | }; 9 | 10 | int Display(struct Array arr){ 11 | 12 | int i; 13 | 14 | printf("\nElements are:\n"); 15 | 16 | for(i=0; i=0 && index<=arr->length){ 24 | for ( i = arr->length ; i >index; i--) 25 | { 26 | arr->A[i]=arr->A[i-1]; 27 | } 28 | 29 | arr->A[index]=x; 30 | } 31 | arr->length++; 32 | } 33 | 34 | int Delete(struct Array *arr, int index){ 35 | int x=0; 36 | int i; 37 | if(index>=0 && indexlength){ 38 | x=arr->A[index]; 39 | for(i=index ; ilength-1 ; i++){ 40 | arr->A[i]=arr->A[i+1]; 41 | } 42 | arr->length--; 43 | return x; 44 | } 45 | return 0; 46 | } 47 | 48 | int missing(struct Array * arr,int first){ 49 | int i, difference; 50 | difference=first-0; 51 | for(i=0;ilength;i++){ 52 | if(arr->A[i]-i!=difference){ 53 | printf("Missing element is %d\n",i+difference ); 54 | break; 55 | } 56 | } 57 | } 58 | 59 | int main() 60 | { 61 | int choice,index,x,f; 62 | struct Array arr; 63 | printf("Enter size of the array:"); 64 | scanf("%d",&arr.size); 65 | 66 | arr.A = (int*)malloc(arr.size*sizeof(int)); 67 | arr.length=0; 68 | 69 | do{ 70 | printf("\nMenu\n"); 71 | printf("1 . Insert\n"); 72 | printf("2 . Delete\n"); 73 | printf("3 . Display\n"); 74 | printf("4 . Missing\n"); 75 | printf("5 . Exit\n"); 76 | printf("Enter your choice:",choice); 77 | scanf("%d",&choice); 78 | switch(choice){ 79 | case 1:printf("Enter index:",index); 80 | scanf("%d",&index); 81 | printf("Enter Element:",x); 82 | scanf("%d",&x); 83 | Insert(&arr,index,x); 84 | break; 85 | case 2:printf("Enter index:",index); 86 | scanf("%d",&index); 87 | x=Delete(&arr,index); 88 | printf("Deleted element is %d",x); 89 | break; 90 | case 3:Display(arr); 91 | break; 92 | case 4:printf("Enter first element of the array:\n",f); 93 | scanf("%d",&f); 94 | missing(&arr,f); 95 | break; 96 | 97 | } 98 | }while(choice<5); 99 | return 0; 100 | } -------------------------------------------------------------------------------- /Arrays/SearchingInArrays/binarySearch_iterative.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | struct Array{ 5 | int A[20]; 6 | int size; 7 | int length; 8 | }; 9 | 10 | 11 | int display_array(struct Array arr){ 12 | int index; 13 | while(index < arr.length){ 14 | printf("%d\n",arr.A[index++]); 15 | } 16 | } 17 | 18 | int binarySearch(struct Array arr,int key){ 19 | int front = 0; 20 | int back = arr.length - 1; 21 | while(front < back){ 22 | int mid = front + (back - front)/2; 23 | if(arr.A[mid] == key) return mid; 24 | if(arr.A[mid] < key) front = mid + 1; 25 | else back = mid - 1; 26 | } 27 | return -1; 28 | } 29 | 30 | int main(){ 31 | struct Array arr={{2,3,4,5,6},20,5}; 32 | display_array(arr); 33 | printf("search result :%d\n",binarySearch(arr,5) ); 34 | return 0; 35 | } -------------------------------------------------------------------------------- /Arrays/SearchingInArrays/binarySearch_recursive.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | struct Array{ 5 | int A[20]; 6 | int size; 7 | int length; 8 | }; 9 | 10 | 11 | int display_array(struct Array arr){ 12 | int i; 13 | 14 | for(i=0 ; i 2 | #include 3 | 4 | struct Array{ 5 | int A[20]; 6 | int size; 7 | int length; 8 | }; 9 | 10 | void Display(struct Array arr){ 11 | int i; 12 | for(i=0;ilength && jlength){ 22 | if(arr->A[i]A[j]) 23 | i++; 24 | else if(arr->A[i]>arr2->A[j]) 25 | j++; 26 | else{ 27 | arr3->A[k++]=arr->A[i++]; 28 | j++; 29 | } 30 | } 31 | arr3->length=k; 32 | arr3->size=arr->length+arr2->length; 33 | return arr3; 34 | } 35 | 36 | 37 | int main(){ 38 | struct Array x = {{2,3,4,5,6},20,5}; 39 | struct Array y = {{1,3,5,7,9},20,5}; 40 | struct Array *z; 41 | z=intersection_of_Arrays(&x,&y); 42 | Display(*z); 43 | } -------------------------------------------------------------------------------- /Arrays/SetOperation/array_rearrange.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | struct Array{ 5 | int A[20]; 6 | int size; 7 | int length; 8 | }; 9 | 10 | void Display(struct Array arr){ 11 | int i; 12 | for(i=0; ilength-1; 27 | while(iA[i]<0) i++; 30 | while(arr->A[j]>0) j--; 31 | if(iA[i],&arr->A[j]); 33 | } 34 | } 35 | 36 | int main(){ 37 | struct Array arr={{-5,10,15,-20,25,30,-35,40},20,8}; 38 | Rearrange_Integers(&arr); 39 | Display(arr); 40 | } -------------------------------------------------------------------------------- /Arrays/SetOperation/array_reverse.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | struct Array{ 5 | int A[20]; 6 | int size; 7 | int length; 8 | }; 9 | 10 | void Display(struct Array arr){ 11 | int i; 12 | for(i=0; ilength*sizeof(int)); 29 | for(i=arr->length-1,j=0; i>=0; j++,i--){ 30 | B[j]=arr->A[i]; 31 | } 32 | for(i=0; ilength; i++){ 33 | arr->A[i]=B[i]; 34 | } 35 | } 36 | 37 | void reverse_swap(struct Array *arr){ 38 | int i,j; 39 | for(i=0,j=arr->length-1 ; iA[i],&arr->A[j]); 41 | } 42 | } 43 | 44 | int main(){ 45 | struct Array arr ={{2,6,9,8,12,17,19,10},20,5}; 46 | reverse_swap(&arr); 47 | Display(arr); 48 | reverse_array(&arr); 49 | Display(arr); 50 | } -------------------------------------------------------------------------------- /Arrays/SetOperation/array_shift.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | struct Array{ 5 | int A[20]; 6 | int size; 7 | int length; 8 | }; 9 | 10 | 11 | int display_array(struct Array arr){ 12 | int i; 13 | 14 | for(i=0 ; iA[0]; 23 | for(i=0; ilength; i++){ 24 | arr->A[i]=arr->A[i+1]; 25 | } 26 | arr->A[arr->length-1]=x; 27 | 28 | } 29 | 30 | int main(){ 31 | struct Array arr={{2,3,4,5,6},20,5}; 32 | shift_array(&arr); 33 | display_array(arr); 34 | 35 | 36 | return 0; 37 | } 38 | -------------------------------------------------------------------------------- /Arrays/SetOperation/array_sorted.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | struct Array{ 5 | int A[20]; 6 | int size; 7 | int length; 8 | }; 9 | 10 | void Display(struct Array arr){ 11 | int i; 12 | for(i=0; iA[i]>arr->A[i+1]){ 20 | return 0; 21 | } 22 | return 1; 23 | } 24 | int main(){ 25 | struct Array arr={{5,10,15,20,25,30,35,40},20,7}; 26 | Display(arr); 27 | printf("%d\n",is_Sorted(&arr) ); 28 | } -------------------------------------------------------------------------------- /Arrays/SetOperation/array_unsorted_union.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | struct Array{ 5 | int A[20]; 6 | int size; 7 | int length; 8 | }; 9 | 10 | void Display(struct Array arr){ 11 | int i; 12 | for(i=0;ilength){ 20 | if(key!=arr3->A[i]) 21 | return i++; 22 | else 23 | break; 24 | } 25 | if(i>=arr2->length){ 26 | arr3->A[index]=key; 27 | arr3->length++; 28 | } 29 | else return arr3; 30 | 31 | return arr3; 32 | } 33 | 34 | struct Array * union_unsorted(struct Array *arr1,struct Array *arr2){ 35 | int i, j, k; 36 | i=j=k=0; 37 | 38 | struct Array *arr3 = (struct Array *)malloc(sizeof(struct Array)); 39 | arr3->length=0; 40 | 41 | for(i=0;ilength;i++){ 42 | arr3->A[k++]=arr1->A[i]; 43 | arr3->length++; 44 | } 45 | 46 | for(i=0;ilength;i++){ 47 | search_Insert(&arr2,&arr3,arr2->A[i],k); 48 | k++; 49 | } 50 | return arr3; 51 | } 52 | 53 | int main(){ 54 | struct Array arr1 = {{11,23,43,54,67},20,5}; 55 | struct Array arr2 = {{23,67,20,56,76},20,5}; 56 | struct Array *arr3; 57 | arr3=union_unsorted(&arr1,&arr2); 58 | Display(*arr3); 59 | } -------------------------------------------------------------------------------- /Arrays/SetOperation/arrays_merge.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | struct Array{ 5 | int A[20]; 6 | int size; 7 | int length; 8 | }; 9 | 10 | void Display(struct Array arr){ 11 | int i; 12 | for(i=0; ilength && jlength){ 25 | 26 | if(arr->A[i]A[j]) 27 | arr3->A[k++]=arr->A[i++]; 28 | else 29 | arr3->A[k++]=arr2->A[j++]; 30 | } 31 | 32 | for(;ilength;i++) 33 | arr3->A[k++]=arr->A[i]; 34 | for(;jlength;j++) 35 | arr3->A[k++]=arr2->A[j]; 36 | 37 | arr3->length = arr->length + arr2->length; 38 | arr3->size = 10; 39 | 40 | return arr3; 41 | } 42 | 43 | 44 | int main(){ 45 | struct Array arr={{5,10,15,20,25},20,5}; 46 | struct Array arr2={{2,4,6,8,10},20,5}; 47 | struct Array *arr3; 48 | arr3 = merge_arrays(&arr,&arr2); 49 | Display(*arr3); 50 | return 0; 51 | } -------------------------------------------------------------------------------- /Arrays/SetOperation/arrays_union.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | struct Array{ 5 | int A[20]; 6 | int size; 7 | int length; 8 | }; 9 | 10 | void Display(struct Array arr){ 11 | int i; 12 | for(i=0;ilength && jlength){ 22 | if(arr->A[i]A[j]) 23 | arr3->A[k++]=arr->A[i++]; 24 | else if(arr->A[i]>arr2->A[j]) 25 | arr3->A[k++]=arr2->A[j++]; 26 | else{ 27 | arr3->A[k++]=arr->A[i++]; 28 | j++; 29 | } 30 | } 31 | for(;ilength;i++) 32 | arr3->A[k++]=arr->A[i]; 33 | for(;jlength;j++) 34 | arr3->A[k++]=arr2->A[j]; 35 | 36 | arr3->size = arr->length + arr2->length; 37 | arr3->length = k; 38 | 39 | return arr3; 40 | } 41 | 42 | 43 | int main(){ 44 | struct Array arr={{2,4,6,8,10},20,5}; 45 | struct Array arr2={{5,10,15,20,25},20,5}; 46 | struct Array *arr3; 47 | arr3 = union_of_Arrays(&arr,&arr2); 48 | Display(*arr3); 49 | return 0; 50 | } -------------------------------------------------------------------------------- /BST/C/Queue.h: -------------------------------------------------------------------------------- 1 | //header file for creating tree using queue. 2 | 3 | #ifndef Queue_h 4 | #define Queue_h 5 | 6 | struct Node 7 | { 8 | struct Node *left_child; 9 | int data; 10 | struct Node *right_child; 11 | }; 12 | 13 | struct Queue 14 | { 15 | int size; 16 | int front; 17 | int rear; 18 | struct Node **items; 19 | }; 20 | 21 | void createQ(struct Queue *q, int size){ 22 | q->size = size; 23 | q->front = q->rear = 0; 24 | q->items = ( struct Node **)malloc(q->size*sizeof( struct Node *)); 25 | } 26 | 27 | void enqueue(struct Queue *q, struct Node *value){ 28 | if((q->rear+1)%q->size == q->front) 29 | printf("Queue is full\n"); 30 | else{ 31 | q->rear = (q->rear+1)%q->size; 32 | q->items[q->rear] = value; 33 | } 34 | } 35 | 36 | struct Node * dequeue(struct Queue *q){ 37 | struct Node * value = NULL; 38 | if(q->front == q->rear) 39 | printf("Queue is empty\n"); 40 | else{ 41 | q->front = (q->front+1)%q->size; 42 | value = q->items[q->front]; 43 | } 44 | return value; 45 | } 46 | 47 | int isEmpty(struct Queue queue){ 48 | return queue.front == queue.rear; 49 | } 50 | 51 | #endif -------------------------------------------------------------------------------- /BST/C/createBST.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Author: Fakhra Najm 3 | * Email: fnajm09@gmail.com 4 | * Topic: Generating binary search tree from preorder traversal 5 | */ 6 | 7 | #include 8 | #include 9 | #include"stack.h" 10 | 11 | struct Node *root = NULL; 12 | 13 | struct Node *createNode(struct Node *node, int value){ 14 | node = (struct Node *)malloc(sizeof(struct Node)); 15 | node->data = value; 16 | node->left_child = node->right_child = NULL; 17 | return node; 18 | } 19 | 20 | void createBST(int preorder[], int nodes){ 21 | struct Node *temp, *node; 22 | int i = 0; 23 | struct stack stk; 24 | createStack(&stk, 100); 25 | root = createNode(root, preorder[i++]); 26 | temp = root; 27 | while (i < nodes){ 28 | if(preorder[i] < temp->data){ 29 | node = createNode(node, preorder[i++]); 30 | temp->left_child = node; 31 | push(&stk, temp); 32 | temp = node; 33 | } 34 | else{ 35 | if(isEmptyStack(stk)){ 36 | node = createNode(node, preorder[i++]); 37 | temp->right_child = node; 38 | push(&stk, temp); 39 | temp = node; 40 | } 41 | else if(preorder[i] < stackTop(stk)->data && temp->data < preorder[i]){ 42 | node = createNode(node, preorder[i++]); 43 | temp->right_child = node; 44 | push(&stk, temp); 45 | temp = node; 46 | } 47 | else{ 48 | node = createNode(node, preorder[i++]); 49 | pop(&stk)->right_child = node; 50 | temp = node; 51 | } 52 | } 53 | } 54 | } 55 | 56 | 57 | void bstFromPostorder(int postorder[], int nodes){ 58 | struct Node *node, *temp; 59 | struct stack stk; 60 | createStack(&stk, 100); 61 | nodes = nodes - 1; 62 | root = createNode(root, postorder[nodes--]); 63 | temp = root; 64 | while(nodes >= 0){ 65 | if(temp->data < postorder[nodes]){ 66 | node = createNode(node, postorder[nodes--]); 67 | temp->right_child = node; 68 | push(&stk, temp); 69 | temp = node; 70 | } 71 | else{ 72 | if(isEmptyStack(stk)){ 73 | node = createNode(node, postorder[nodes--]); 74 | temp->right_child = node; 75 | temp = node; 76 | push(&stk, temp); 77 | } 78 | else if(stackTop(stk)->data < postorder[nodes] && postorder[nodes] < temp->data ){ 79 | node = createNode(node, postorder[nodes--]); 80 | temp->left_child = node; 81 | push(&stk, temp); 82 | temp = node; 83 | } 84 | else{ 85 | node = createNode(node, postorder[nodes--]); 86 | pop(&stk)->left_child = node; 87 | temp = node; 88 | } 89 | } 90 | } 91 | } 92 | 93 | void inorder(struct Node *root){ 94 | if(root){ 95 | inorder(root->left_child); 96 | printf("%d ", root->data); 97 | inorder(root->right_child); 98 | } 99 | } 100 | 101 | int main(){ 102 | int preorder[7] = {50, 40, 30, 45, 60, 55, 70}; 103 | int postorder[7] = {30, 45, 40, 55, 70, 60, 50}; 104 | createBST(preorder, 7); 105 | printf("Binary search tree from preorder:"); 106 | inorder(root); 107 | printf("\n"); 108 | root = NULL; 109 | bstFromPostorder(postorder, 7); 110 | printf("Binary search tree from postorder:"); 111 | inorder(root); 112 | return 0; 113 | } -------------------------------------------------------------------------------- /BST/C/main.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Author: Fakhra Najm 3 | * Email: fnajm09@gmail.com 4 | * Topic: Implementation of binarySearchTree 5 | Operations: 6 | 1. Insert 7 | 2. Search 8 | 3. Inorder 9 | */ 10 | 11 | #include 12 | #include 13 | 14 | struct Node{ 15 | struct Node *left; 16 | struct Node *right; 17 | int data; 18 | }*root = NULL; 19 | 20 | struct Node * createNode(struct Node * node, int value){ 21 | node = (struct Node *)malloc(sizeof(struct Node)); 22 | node->data = value; 23 | node->left = node->right = NULL; 24 | return node; 25 | } 26 | 27 | void insert(int value){ 28 | struct Node *node, *tail, *present; 29 | present = root; 30 | if(! present){ 31 | present = createNode(node, value); 32 | root = present; 33 | return; 34 | } 35 | while( present){ 36 | if(present->data > value){ 37 | tail = present; 38 | present = present->left; 39 | } 40 | else if(present->data < value){ 41 | tail = present; 42 | present = present->right; 43 | } 44 | else return; 45 | } 46 | if(tail->data > value) 47 | tail->left = createNode(node, value); 48 | else 49 | tail->right = createNode(node, value); 50 | } 51 | 52 | // returns the address of passed value 53 | 54 | struct Node * search(int value){ 55 | struct Node *present = root; 56 | while(present){ 57 | if(present->data > value) 58 | present = present->left; 59 | else if(present->data < value) 60 | present = present->right; 61 | else 62 | return present; 63 | } 64 | return NULL; 65 | } 66 | 67 | // prints all the elements of binary search tree in a sorted manner. 68 | void inorder(struct Node *root){ 69 | if(root){ 70 | inorder(root->left); 71 | printf("%d ", root->data); 72 | inorder(root->right); 73 | } 74 | } 75 | 76 | int main(void){ 77 | insert(20); 78 | insert(10); 79 | insert(30); 80 | insert(5); 81 | insert(25); 82 | inorder(root); 83 | if(search(80)) 84 | printf("\nElement is found\n"); 85 | else 86 | printf("\nElement not found\n"); 87 | 88 | return 0; 89 | } -------------------------------------------------------------------------------- /BST/C/recursive.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Author: Fakhra Najm 3 | * Email: fnajm09@gmail.com 4 | * Topic: Recursive implementation code for binary search trees. 5 | Operations: 6 | 1. Insert 7 | 2. search 8 | 3. height 9 | 4. Predecessor 10 | 5. Successor 11 | 6. Delete 12 | */ 13 | 14 | #include 15 | #include 16 | 17 | struct Node { 18 | struct Node *left; 19 | struct Node *right; 20 | int data; 21 | }*root = NULL; 22 | 23 | struct Node * createNode(struct Node *node, int value){ 24 | node = (struct Node *)malloc(sizeof(struct Node)); 25 | node->data = value; 26 | node->left = node->right = NULL; 27 | return node; 28 | } 29 | 30 | struct Node * insert(struct Node *node, int value){ 31 | struct Node *temp; 32 | if(node == NULL){ 33 | return createNode(temp, value); 34 | } 35 | if(node->data > value) 36 | node->left = insert(node->left, value); 37 | else if(node->data < value) 38 | node->right = insert(node->right, value); 39 | return node; 40 | } 41 | 42 | // printing binary search tree in sorted order 43 | void inorder(struct Node *node){ 44 | if(node){ 45 | inorder(node->left); 46 | printf("%d ",node->data); 47 | inorder(node->right); 48 | } 49 | } 50 | 51 | struct Node * search(struct Node *root, int key){ 52 | if(root){ 53 | if(root->data > key) 54 | return search(root->left, key); 55 | else if(root->data < key) 56 | return search(root->right, key); 57 | else 58 | return root; 59 | } 60 | return NULL; 61 | } 62 | 63 | int height(struct Node *root){ 64 | int x, y; 65 | if(!root) 66 | return 0; 67 | x = height(root->left); 68 | y = height(root->right); 69 | return x > y ? x+1 : y+1; 70 | } 71 | 72 | struct Node* Predecessor(struct Node *root){ 73 | while(root != NULL && root->right != NULL) 74 | root = root->right; 75 | return root; 76 | } 77 | 78 | struct Node* successor(struct Node *root){ 79 | while(root != NULL && root->left != NULL) 80 | root = root->left; 81 | return root; 82 | } 83 | 84 | struct Node *Delete(struct Node *node, int key){ 85 | struct Node *temp; 86 | if(node == NULL) 87 | return NULL; 88 | if(!node->left && ! node->right && node -> data == key){ 89 | if(node == root) 90 | root = NULL; 91 | free(node); 92 | return NULL; 93 | } 94 | if(node->data > key) 95 | node->left = Delete(node->left, key); 96 | else if(node->data < key) 97 | node->right = Delete(node->right, key); 98 | else{ 99 | int left, right; 100 | left = height(node->left); 101 | right = height(node->right); 102 | if( left > right){ 103 | temp = Predecessor(node->left); 104 | node->data = temp->data; 105 | node->left = Delete(node->left, temp->data); 106 | } 107 | else{ 108 | temp = successor(node->right); 109 | node->data = temp->data; 110 | node->right = Delete( node -> right, temp->data); 111 | } 112 | } 113 | return node; 114 | } 115 | 116 | int main(){ 117 | struct Node * result; 118 | root = insert(root, 10); 119 | insert(root, 5); 120 | insert(root, 20); 121 | insert(root, 15); 122 | Delete(root, 15); 123 | inorder(root); 124 | result = search(root, 10); 125 | if(result) 126 | printf("\nelement %d Found\n",result->data); 127 | else 128 | printf("\nelement Not found!\n"); 129 | return 0; 130 | } 131 | -------------------------------------------------------------------------------- /BST/C/stack.h: -------------------------------------------------------------------------------- 1 | #ifndef stack_h 2 | #define stack_h 3 | #include 4 | #include 5 | #include"Queue.h" 6 | 7 | struct stack{ 8 | int size; 9 | int top; 10 | struct Node **items; 11 | }; 12 | 13 | void createStack(struct stack *st, int sz){ 14 | st->items = (struct Node **)malloc(sizeof(struct Node)); 15 | st->size = sz; 16 | st->top = -1; 17 | } 18 | 19 | void push(struct stack *st, struct Node *value){ 20 | if(st->top == st->size-1) 21 | printf("stack overflow\n"); 22 | else{ 23 | st->top++; 24 | st->items[st->top] = value; 25 | } 26 | } 27 | 28 | /* 29 | * deletes the top value of the stack 30 | * @param st pointer to the top pointer of stack 31 | * @return removed value 32 | */ 33 | 34 | struct Node * pop(struct stack *st){ 35 | struct Node * removed = NULL; 36 | if(st->top == -1) 37 | printf("stack underflow\n"); 38 | else{ 39 | removed = st->items[st->top]; 40 | st->top--; 41 | } 42 | return removed; 43 | } 44 | 45 | 46 | /* 47 | * checks whether stack is full or not 48 | * @return true or false 49 | */ 50 | 51 | int isFull(struct stack st){ 52 | if(st.top == st.size-1) 53 | return 1; 54 | else 55 | return 0; 56 | } 57 | 58 | /* 59 | * checks whether stack is empty or not 60 | * @return true or false 61 | */ 62 | 63 | int isEmptyStack(struct stack st){ 64 | if(st.top == -1) 65 | return 1; 66 | else 67 | return 0; 68 | } 69 | 70 | struct Node * stackTop(struct stack st){ 71 | if (st.top == -1){ 72 | return NULL; 73 | } 74 | else{ 75 | return st.items[st.top]; 76 | } 77 | } 78 | 79 | struct Node * peek(struct stack st, int index){ 80 | struct Node *value = NULL; 81 | if(st.top-index+1 < 0) 82 | printf("invalid index\n"); 83 | else{ 84 | value = st.items[st.top-index+1]; 85 | } 86 | return value; 87 | } 88 | #endif -------------------------------------------------------------------------------- /BST/CPP/BstClass.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class BSTNode{ 6 | public: 7 | int val; 8 | BSTNode *left; 9 | BSTNode *right; 10 | BSTNode(int val){this -> val = val;} 11 | ~BSTNode(){} 12 | }; 13 | 14 | class BST{ 15 | public: 16 | BSTNode *root = NULL; 17 | BST(); 18 | 19 | int getNodeVal(BSTNode *node){return node -> val;} 20 | int height(BSTNode *root); 21 | BSTNode * getRootNode(){return this -> root;} 22 | BSTNode *inorderSuccessor(BSTNode *root); 23 | BSTNode *inorderPredecessor(BSTNode *root); 24 | 25 | void createBST(); 26 | BSTNode* insertNode(BSTNode *root, int val); 27 | 28 | BSTNode* deleteNode(BSTNode*root, int val); 29 | int searchNode(BSTNode *root, int val); 30 | void printInorderTraversal(BSTNode *root); 31 | 32 | ~BST(); 33 | }; 34 | 35 | int main(){ 36 | BST bst; 37 | cout << "Inorder : "; 38 | BSTNode *rootNode = bst.getRootNode(); 39 | bst.printInorderTraversal(rootNode); 40 | cout << endl; 41 | int val; 42 | cout << "Enter value to find : "; 43 | cin >> val; 44 | if(bst.searchNode(rootNode,val) == 0) 45 | cout << "Found" << endl; 46 | else cout << "Not Found" << endl; 47 | cout << "Enter value to delete : "; 48 | cin >> val; 49 | bst.deleteNode(rootNode, val); 50 | bst.printInorderTraversal(bst.getRootNode()); 51 | return 0; 52 | } 53 | 54 | BST :: BST (){ 55 | createBST(); 56 | } 57 | 58 | BST :: ~BST(){ 59 | delete root; 60 | } 61 | 62 | BSTNode* BST :: insertNode(BSTNode *root, int val){ 63 | if(!root){ 64 | return new BSTNode(val); 65 | } 66 | if(root -> val > val) 67 | root -> left = insertNode(root -> left, val); 68 | else if(root -> val < val) 69 | root -> right = insertNode(root -> right, val); 70 | return root; 71 | } 72 | 73 | void BST :: createBST(){ 74 | int totalNodes, val; 75 | cout << "Enter Total number of Nodes : " ; 76 | cin >> totalNodes; 77 | cout << "Enter -1 for null nodes" << endl; 78 | while(totalNodes--){ 79 | cout << "Enter Values : " << endl; 80 | cin >> val; 81 | if(val != -1){ 82 | if(!this -> root) 83 | this -> root = insertNode(root, val); 84 | else insertNode(root, val); 85 | } 86 | } 87 | } 88 | 89 | void BST :: printInorderTraversal(BSTNode *root){ 90 | if(!root) return; 91 | printInorderTraversal(root -> left); 92 | cout << root -> val << " "; 93 | printInorderTraversal(root -> right); 94 | } 95 | 96 | int BST :: searchNode(BSTNode *root, int val){ 97 | if(root){ 98 | if(root -> val == val) return 0; 99 | else if(root -> val > val) return searchNode(root -> left, val); 100 | else return searchNode(root -> right, val); 101 | } 102 | return 1; 103 | } 104 | 105 | BSTNode * BST :: deleteNode(BSTNode *root, int val){ 106 | if(!root) return root; 107 | 108 | if(!root -> left && !root -> right && root -> val == val){ 109 | if(root == this -> root) root = NULL; 110 | delete root; 111 | return NULL; 112 | } 113 | if(root -> val > val) 114 | root -> left = deleteNode(root -> left, val); 115 | else if(root -> val < val) 116 | root -> right = deleteNode(root -> right, val); 117 | else{ 118 | int leftSubHeight = height(root -> left); 119 | int rightSubHeight = height(root -> right); 120 | 121 | if(leftSubHeight > rightSubHeight){ 122 | BSTNode *predecessor = inorderPredecessor(root -> left); 123 | root -> val = predecessor -> val; 124 | root -> left = deleteNode(root -> left, predecessor -> val); 125 | } 126 | else{ 127 | BSTNode *successor = inorderSuccessor(root -> right); 128 | root -> val = successor -> val; 129 | root -> right = deleteNode(root -> right, successor -> val); 130 | } 131 | } 132 | 133 | return root; 134 | } 135 | 136 | int BST :: height(BSTNode *root){ 137 | if(!root || (!root -> left && !root -> right)) return 0; 138 | return max(height(root -> left), height(root -> right)) + 1; 139 | } 140 | 141 | BSTNode * BST :: inorderSuccessor(BSTNode *root){ 142 | while(root && root -> left) 143 | root = root -> left; 144 | return root; 145 | } 146 | 147 | BSTNode * BST :: inorderPredecessor(BSTNode *root){ 148 | while(root && root -> right) 149 | root = root -> right; 150 | return root; 151 | } -------------------------------------------------------------------------------- /BST/CPP/bstGeneration.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Topic : Generation of Binary Search Tree from 3 | * 1. Preorder 4 | * 2. Postorder 5 | */ 6 | 7 | #include 8 | #include 9 | #include 10 | using namespace std; 11 | 12 | class BSTNode{ 13 | public: 14 | int val; 15 | BSTNode *left; 16 | BSTNode *right; 17 | BSTNode(int val){this -> val = val;} 18 | ~BSTNode(){} 19 | }; 20 | 21 | class BST{ 22 | BSTNode *root = NULL; 23 | public: 24 | BST(){} 25 | void generateBstFromPreorder(vectorpreorder); 26 | void generateBstFromPostorder(vectorpostorder); 27 | BSTNode * getRootNode(){return this -> root;} 28 | void printInorderTraversal(BSTNode *root); 29 | ~BST(); 30 | }; 31 | 32 | int main(){ 33 | BST pre; 34 | BST post; 35 | pre.generateBstFromPreorder({10,5,3,4,8,7,9,15,12,18,17,22}); 36 | pre.printInorderTraversal(pre.getRootNode()); 37 | cout << endl; 38 | post.generateBstFromPostorder({4,3,7,8,9,5,12,17,22,18,15,10}); 39 | post.printInorderTraversal(post.getRootNode()); 40 | return 0; 41 | } 42 | 43 | BST :: ~BST(){ 44 | delete root; 45 | } 46 | 47 | void BST :: printInorderTraversal(BSTNode *root){ 48 | if(!root) return; 49 | printInorderTraversal(root -> left); 50 | cout << root -> val << " "; 51 | printInorderTraversal(root -> right); 52 | } 53 | 54 | void BST :: generateBstFromPreorder(vectorpreorder){ 55 | stacknodes; 56 | BSTNode *root = new BSTNode(preorder[0]); 57 | this -> root = root; 58 | int preorderItr = 1; 59 | while(preorderItr < preorder.size()){ 60 | if(preorder[preorderItr] < root -> val){ 61 | root -> left = new BSTNode(preorder[preorderItr++]); 62 | nodes.push(root); 63 | root = root -> left; 64 | } 65 | else if(root -> val < preorder[preorderItr] && 66 | (nodes.empty() || preorder[preorderItr] < nodes.top() -> val)){ 67 | root -> right = new BSTNode(preorder[preorderItr++]); 68 | root = root -> right; 69 | } 70 | else{ 71 | root = nodes.top(); 72 | nodes.pop(); 73 | } 74 | } 75 | } 76 | 77 | void BST :: generateBstFromPostorder(vectorpostorder){ 78 | stacknodes; 79 | int index = postorder.size() - 1; 80 | BSTNode *root = new BSTNode(postorder[index--]); 81 | this -> root = root; 82 | 83 | while(index >= 0){ 84 | if(root -> val < postorder[index]){ 85 | root -> right = new BSTNode(postorder[index--]); 86 | nodes.push(root); 87 | root = root -> right; 88 | } 89 | else if(postorder[index] < root -> val 90 | && (nodes.empty() || postorder[index] > nodes.top() -> val)){ 91 | root -> left = new BSTNode(postorder[index--]); 92 | root = root -> left; 93 | } 94 | else{ 95 | root = nodes.top(); 96 | nodes.pop(); 97 | } 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /Graph/kruskal's.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | #define inf INT_MAX 7 | 8 | class DisjointSet{ 9 | protected: 10 | // size : no of vertices 11 | vectorset; // detect cycle 12 | void Union(int node, int candidate); 13 | int Find(int node); 14 | public: 15 | DisjointSet(){} 16 | DisjointSet(int size); 17 | }; 18 | 19 | class Kruskalas : public DisjointSet{ 20 | private: 21 | int minCost; // Cost of edges of spanning tree 22 | int vertices; // Number of vertices in Graph 23 | // Number of edges in spanning tree = |Vertices - 1| 24 | int edges; 25 | vector>edgesCostArray; // size : no of edges 26 | // keeps track of visited edges 27 | vectorvisited; // size : no of edges 28 | vector>minCostArray; // size : no of vertices - 1 29 | public: 30 | Kruskalas(); 31 | Kruskalas(vector>edgesCostArray, int vertices); 32 | int getMinimumCost(){return minCost;} 33 | vector findMinEdge(); 34 | void generateMinCostSpanningTree(); 35 | void printSpanningTree(); 36 | }; 37 | 38 | int main(){ 39 | vector>edges = {{1,2,25},{1,6,5},{2,3,12},{2,7,10},{3,4,8},{4,5,16},{4,7,14},{5,6,20},{5,7,18}}; 40 | Kruskalas algo(edges, 7); 41 | cout << "Minimum Cost : " << algo.getMinimumCost() << endl; 42 | algo.printSpanningTree(); 43 | return 0; 44 | } 45 | 46 | DisjointSet :: DisjointSet(int size){ 47 | for(int index = 0; index <= size; ++index){ 48 | set.push_back(-1); 49 | } 50 | } 51 | 52 | void DisjointSet :: Union(int node, int candidate){ 53 | if(set[node] < set[candidate]){ 54 | set[node] = set[node] + set[candidate]; 55 | set[candidate] = node; 56 | } 57 | else{ 58 | set[candidate] = set[candidate] + set[node]; 59 | set[node] = candidate; 60 | } 61 | } 62 | 63 | int DisjointSet :: Find(int node){ 64 | int index = node; 65 | int currRoot = 0; 66 | while(set[index] > 0){ 67 | index = set[index]; 68 | } 69 | // updating the parent's value in the set 70 | while(node != index){ 71 | currRoot = set[node]; 72 | set[node] = index; 73 | node = currRoot; 74 | } 75 | return index; 76 | } 77 | 78 | Kruskalas :: Kruskalas(){ 79 | this -> edges = 0; 80 | this -> minCost = 0; 81 | } 82 | 83 | Kruskalas :: Kruskalas(vector>edgesCostArray,int vertices) 84 | :DisjointSet(vertices + 1){ 85 | this -> vertices = vertices; 86 | this -> minCost = 0; 87 | this -> edges = edgesCostArray.size() - 1; 88 | this -> edgesCostArray = edgesCostArray; 89 | for(int index = 0; index <= edges; ++index){ 90 | visited.push_back(0); 91 | } 92 | generateMinCostSpanningTree(); 93 | } 94 | 95 | vector Kruskalas :: findMinEdge(){ 96 | if(edges == 0) return {-1,-1,-1}; 97 | int minCostSoFar = inf; 98 | vector minEdgeVertex(3,0); 99 | for(int index = 0; index <= edges; ++index){ 100 | if(visited[index] != 1 && minCostSoFar > edgesCostArray[index][2]){ 101 | minEdgeVertex[0] = edgesCostArray[index][0]; 102 | minEdgeVertex[1] = edgesCostArray[index][1]; 103 | minEdgeVertex[2] = index; 104 | minCostSoFar = edgesCostArray[index][2]; 105 | } 106 | } 107 | return minEdgeVertex; 108 | } 109 | 110 | void Kruskalas :: generateMinCostSpanningTree(){ 111 | int node1, node2, parent1, parent2, minIndex; 112 | for(int index = 0; index < vertices - 1; ){ 113 | vectorminEdge = findMinEdge(); 114 | node1 = minEdge[0]; 115 | node2 = minEdge[1]; 116 | minIndex = minEdge[2]; 117 | parent1 = Find(node1); 118 | parent2 = Find(node2); 119 | if(parent1 != parent2){ 120 | minCost += edgesCostArray[minIndex][2]; 121 | minCostArray.push_back({node1,node2}); 122 | Union(parent1, parent2); 123 | index = index + 1; 124 | } 125 | visited[minIndex] = 1; 126 | } 127 | } 128 | 129 | void Kruskalas :: printSpanningTree(){ 130 | for(int index = 0; index < minCostArray.size(); ++index){ 131 | cout << "[" << minCostArray[index][0] << "]"; 132 | cout << "------> "; 133 | cout << "[" << minCostArray[index][1] << "]"; 134 | cout << endl; 135 | } 136 | } -------------------------------------------------------------------------------- /Graph/main.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Author : Fakhra Najm 3 | * Topic : Graph implementation 4 | * Operations: 5 | * BFS 6 | * DFS 7 | */ 8 | 9 | #include 10 | #include 11 | #include 12 | using namespace std; 13 | 14 | void BFS (int adjacency_matrix[][7], int vertex, int vertices){ 15 | queuequeue; 16 | vectoris_vertex_visited(vertices, false); 17 | queue.push(vertex); 18 | is_vertex_visited[vertex] = true; 19 | cout << vertex << " "; 20 | while(!queue.empty()){ 21 | int row = queue.front(); 22 | queue.pop(); 23 | for(int neighbour = 1; neighbour <= vertices; ++neighbour){ 24 | if(is_vertex_visited[neighbour] == false && adjacency_matrix[row][neighbour] == 1){ 25 | cout << neighbour << " "; 26 | queue.push(neighbour); 27 | is_vertex_visited[neighbour] = true; 28 | } 29 | } 30 | } 31 | cout << endl; 32 | } 33 | 34 | void DFS(int adjacency_matrix[][7], int vertex, int vertices){ 35 | static vectoris_vertex_visited(vertices, false); 36 | if(is_vertex_visited[vertex] == false){ 37 | cout << vertex << " "; 38 | is_vertex_visited[vertex] = true; 39 | for(int neighbour = 1; neighbour < vertices; ++neighbour){ 40 | if(adjacency_matrix[vertex][neighbour] == 1 && is_vertex_visited[neighbour] == false) 41 | DFS(adjacency_matrix, neighbour, vertices); 42 | } 43 | } 44 | } 45 | 46 | int main(){ 47 | int G[7][7] = 48 | { 49 | {0,0,0,0,0,0,0}, 50 | {0,0,1,1,0,0,0}, 51 | {0,1,0,0,1,0,0}, 52 | {0,1,0,0,1,0,0}, 53 | {0,0,1,1,0,1,1}, 54 | {0,0,0,0,1,0,0}, 55 | {0,0,0,0,1,0,0} 56 | }; 57 | int vertex; 58 | cout << "Enter vertex where to start : "; 59 | cin >> vertex; 60 | BFS(G, vertex, 7); 61 | cout << "Enter vertex where to start : "; 62 | cin >> vertex; 63 | DFS(G, vertex, 7); 64 | return 0; 65 | } -------------------------------------------------------------------------------- /Graph/spanningTreeClass.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | #define inf INT_MAX 7 | class spanningTree{ 8 | int minimumCost; 9 | // Matrix[row][col] = x is sthe cost of edge between row and col 10 | vector>adjacencyMatrix; 11 | // Represents minimum cost edge between two vertex 12 | vector>minCostArray; 13 | // Used to keep track of visited vertices and near edges of visited vertices 14 | vectornearEdges; 15 | // Size of the adjacency matrix 16 | int vertices; 17 | // First minimum cost between vertex1 and vertex2 18 | int vertex1; 19 | int vertex2; 20 | public: 21 | spanningTree(vector>adjacencyMatrix); 22 | int getMinimumCost(){return minimumCost;} 23 | // Filling initial near edges at infinity 24 | void fillNearEdges(); 25 | // Finds first minimum edge and store vertex into this -> vertex1 and this -> vertex2 26 | void findMin(); 27 | // Updates the nearEdges of vertex1 and vertex2 int nearEdges Array 28 | void updateEdgeCost(); 29 | // Finds minimum of nearEdges and store it in the minCostArray one by one 30 | // Visited vertices are marked zero in the nearEdges Array 31 | void generateMinCostSpanningTree(); 32 | // Prints the spanning tree vertices 33 | void printMinCostSpanningTree(); 34 | }; 35 | 36 | spanningTree :: spanningTree(vector>adjacencyMatrix){ 37 | this -> vertices = adjacencyMatrix.size(); 38 | this -> adjacencyMatrix = adjacencyMatrix; 39 | fillNearEdges(); 40 | findMin(); 41 | updateEdgeCost(); 42 | generateMinCostSpanningTree(); 43 | } 44 | 45 | void spanningTree :: fillNearEdges(){ 46 | for(int index = 0; index < vertices; ++index){ 47 | nearEdges.push_back(inf); 48 | } 49 | } 50 | 51 | void spanningTree :: findMin(){ 52 | // guard condition 53 | if(vertices == 0) return; 54 | // checking upper triangular matrix 55 | // upper triangular and lower triangular represent same edges 56 | int minCostEdge = inf; 57 | for(int row = 1; row < vertices; ++row){ 58 | for(int col = row; col < vertices; ++col){ 59 | if(adjacencyMatrix[row][col] < minCostEdge){ 60 | // updating minimum cost so far 61 | minCostEdge = adjacencyMatrix[row][col]; 62 | // updating vertex having minimum cost so far 63 | vertex1 = row; 64 | vertex2 = col; 65 | } 66 | } 67 | } 68 | } 69 | 70 | void spanningTree :: updateEdgeCost(){ 71 | if(vertices == 0) return; 72 | // Mark vertex1 Nand vertex2 position 0 as it is visited 73 | // No need to visit again 74 | nearEdges[vertex1] = nearEdges[vertex2] = 0; 75 | // Push first minimum cost Edge in the minCostArray 76 | minCostArray.push_back({vertex1, vertex2}); 77 | // dividing the vertex int two parts 78 | // Nearer to vertex1 is Marked as the vertex1 in nearEdges 79 | // Nearer to vertex2 is Marked as the vertex2 in nearEdges 80 | for(int row = 1; row < vertices; ++row){ 81 | if(nearEdges[row] == 0) continue; // already visited 82 | if(adjacencyMatrix[row][vertex1] < adjacencyMatrix[row][vertex2]) 83 | nearEdges[row] = vertex1; // nearEdges of row is nearer to vertex1 84 | else nearEdges[row] = vertex2; // nearEdges of row is nearer to vertex2 85 | } 86 | } 87 | 88 | void spanningTree :: generateMinCostSpanningTree(){ 89 | // guard conditions 90 | if(vertices == 0) return; 91 | // one edge is already visited int the beginning 92 | for(int vertex = 1; vertex < vertices - 1; ++vertex){ 93 | int minEdge = inf, row; 94 | for(int index = 1; index < vertices; ++index){ 95 | if(nearEdges[index] == 0) continue; 96 | if(adjacencyMatrix[index][nearEdges[index]] < minEdge){ 97 | minEdge = adjacencyMatrix[index][nearEdges[index]]; 98 | row = index; 99 | } 100 | } 101 | // Next minimum cost edge is found at adjacencyMAtrix[row][nearEdges[index]] 102 | // Update the minCostArray 103 | minCostArray.push_back({row, nearEdges[row]}); 104 | // Marking vertex as visited 105 | nearEdges[row] = 0; 106 | // Update the nearEdges 107 | for(int edges = 1; edges < vertices; ++edges){ 108 | if(nearEdges[edges] == 0) continue; 109 | if(adjacencyMatrix[edges][row] < adjacencyMatrix[edges][nearEdges[edges]]){ 110 | nearEdges[edges] = row; 111 | } 112 | } 113 | } 114 | } 115 | 116 | void spanningTree :: printMinCostSpanningTree(){ 117 | if(vertices == 0) return; 118 | int totalCost = 0; 119 | // Number of edges in spanning tree is |V - 2| 120 | for(int row = 0; row < vertices - 2; ++row){ 121 | totalCost += adjacencyMatrix[minCostArray[row][0]][minCostArray[row][1]]; 122 | cout << "[" << minCostArray[row][0] << "]"; 123 | cout << " -----> "; 124 | cout << "[" << minCostArray[row][1] << "]"; 125 | cout << "\t" << "cost : " << totalCost << endl; 126 | } 127 | // Minimum cost od edges to generate spanning tree 128 | this -> minimumCost = totalCost; 129 | } 130 | 131 | int main(){ 132 | // inf represents no edge between vertices 133 | vector>matrix = { 134 | {inf, inf, inf, inf, inf, inf, inf, inf}, 135 | {inf, inf, 25, inf, inf, inf, 5, inf}, 136 | {inf, 25, inf, 12, inf, inf, inf, 10}, 137 | {inf, inf, 12, inf, 8, inf, inf, inf}, 138 | {inf, inf, inf, 8, inf, 16, inf, 14}, 139 | {inf, inf, inf, inf, 16, inf, 20, 18}, 140 | {inf, 5, inf, inf, inf, 20, inf, inf}, 141 | {inf, inf, 10, inf, 14, 18, inf, inf}, 142 | }; 143 | spanningTree spanning(matrix); 144 | spanning.printMinCostSpanningTree(); 145 | cout << "Total Cost : " << spanning.getMinimumCost() << endl; 146 | return 0; 147 | } 148 | -------------------------------------------------------------------------------- /HashTable/chaining.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Node{ 5 | public: 6 | int data; 7 | Node* next; 8 | Node(int val, Node *next); 9 | }; 10 | 11 | Node :: Node(int val, Node *next){ 12 | this -> data = val; 13 | this -> next = next; 14 | } 15 | 16 | class HashTable{ 17 | public: 18 | Node** HashArray; 19 | HashTable(); 20 | int hash(int key); 21 | void Insert(int key); 22 | int Search(int key); 23 | ~HashTable(); 24 | }; 25 | 26 | HashTable :: HashTable() { 27 | HashArray = new Node*[10]; 28 | for (int index = 0; index < 10; index++){ 29 | HashArray[index] = nullptr; 30 | } 31 | } 32 | 33 | int HashTable::hash(int key) { 34 | return key % 10; 35 | } 36 | 37 | void HashTable::Insert(int key) { 38 | int hashKey = hash(key); 39 | Node* node = new Node(key, nullptr); 40 | // Case: No nodes in the linked list 41 | if(HashArray[hashKey] == nullptr){ 42 | HashArray[hashKey] = node; 43 | } 44 | else { 45 | Node *currNodeItr = HashArray[hashKey]; 46 | Node *lastNodeItr = HashArray[hashKey]; 47 | // Traverse to find insert position 48 | while (currNodeItr && currNodeItr -> data < key){ 49 | lastNodeItr = currNodeItr; 50 | currNodeItr = currNodeItr -> next; 51 | } 52 | // Case: insert position is first 53 | if(lastNodeItr == HashArray[hashKey]){ 54 | node -> next = HashArray[hashKey]; 55 | HashArray[hashKey] = node; 56 | } 57 | else { 58 | node -> next = lastNodeItr -> next; 59 | lastNodeItr -> next = node; 60 | } 61 | } 62 | } 63 | 64 | int HashTable::Search(int key) { 65 | int hashKey = hash(key); 66 | Node* currNodeItr = HashArray[hashKey]; 67 | while (currNodeItr){ 68 | if (currNodeItr -> data == key){ 69 | return currNodeItr -> data; 70 | } 71 | currNodeItr = currNodeItr -> next; 72 | } 73 | return -1; 74 | } 75 | 76 | HashTable::~HashTable() { 77 | for (int index = 0; index < 10; index++){ 78 | Node* currNodeItr = HashArray[index]; 79 | while (HashArray[index]){ 80 | HashArray[index] = HashArray[index] -> next; 81 | delete currNodeItr; 82 | currNodeItr = HashArray[index]; 83 | } 84 | } 85 | delete []HashArray; 86 | } 87 | 88 | int main() { 89 | int key, value; 90 | int A[] = {16, 12, 25, 39, 6, 122, 5, 68, 75}; 91 | int size = sizeof(A)/sizeof(A[0]); 92 | HashTable map; 93 | for (int index = 0; index < size; index++){ 94 | map.Insert(A[index]); 95 | } 96 | key = 6; 97 | value = map.Search(key); 98 | cout << "Key: " << key << ", Value: " << value << endl; 99 | key = 95; 100 | value = map.Search(key); 101 | cout << "Key: " << key << ", Value: " << value << endl; 102 | return 0; 103 | } -------------------------------------------------------------------------------- /HashTable/doubleHashing.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Author : Fakhra Najm 3 | * Email : fnajm09@gmail.com 4 | * Topic : Hash Table Implementation : "Double Hashing" 5 | */ 6 | 7 | #include 8 | using namespace std; 9 | 10 | class HashMap{ 11 | private: 12 | int size; 13 | int doubleKey ; // First prime number from last of the array 14 | int *Array; 15 | 16 | public: 17 | HashMap(){} 18 | void create(); 19 | void read(); 20 | void update(int val); 21 | void Delete(int val); 22 | int search(int val); 23 | int first_hash(int val); 24 | int second_hash(int val); 25 | int doubleHashing(int val); 26 | }; 27 | 28 | bool isPrime(int val){ 29 | if (val <= 1) return false; 30 | for (int factor = 2; factor < val; factor++) 31 | if (val % factor == 0) return false; 32 | return true; 33 | } 34 | 35 | void HashMap :: create(){ 36 | int size, doubleKey; 37 | cout << "Enter number of data items: "; 38 | cin >> size; 39 | this -> size = 2 * size ; 40 | cout << "size of Hash Table is " << this -> size << endl; 41 | this -> Array = new int[this -> size]; 42 | for(int key = 0; key < this -> size; ++key) 43 | Array[key] = 0; 44 | for(int key = this -> size; key >= 0; --key){ 45 | if(isPrime(key)){ 46 | this -> doubleKey = key; 47 | break; 48 | } 49 | } 50 | cout << "Enter " << size << " data elements : " ; 51 | for(int element = 0; element < size; ++element){ 52 | int val ; 53 | cin >> val; 54 | this -> update(val); 55 | } 56 | } 57 | 58 | void HashMap :: read(){ 59 | for(int key = 0; key < this -> size; ++key) 60 | cout << Array[key] << " "; 61 | cout << endl; 62 | } 63 | 64 | int HashMap :: first_hash(int val){ 65 | return val % size; 66 | } 67 | 68 | int HashMap :: second_hash(int val){ 69 | return doubleKey - (val % doubleKey); // gives random index 70 | } 71 | /* 72 | * Double hashing = h'(x) = (firstHasing + f(i)*secondHashing) % 10 73 | * f(i) = i 74 | * i = 0,1,2,3.... 75 | */ 76 | int HashMap :: doubleHashing(int val){ 77 | int first_hash_key = first_hash(val); 78 | int second_hash_key = second_hash(val); 79 | int index = first_hash_key; 80 | int i = 0; 81 | while(this -> Array[index] != 0) 82 | index = (first_hash_key + (i++) * (second_hash_key)) % size; 83 | return index; 84 | } 85 | 86 | void HashMap :: update(int val){ 87 | int hash_key = first_hash(val); 88 | if(this -> Array[hash_key] == 0) 89 | this -> Array[hash_key] = val; 90 | else{ 91 | hash_key = doubleHashing(val); 92 | this -> Array[hash_key] = val; 93 | } 94 | } 95 | 96 | int HashMap :: search(int val){ 97 | int key = first_hash(val); 98 | if(Array[key] == val) return key; 99 | else{ 100 | int second_hash_key = second_hash(val); 101 | int i = 0; 102 | while(Array[key] != val){ 103 | if(Array[key] == 0) return -1; 104 | key = (first_hash(val) + (i++) * (second_hash_key)) % size; 105 | } 106 | } 107 | return key; 108 | } 109 | 110 | int main(){ 111 | int val, find; 112 | HashMap map; 113 | map.create(); 114 | map.read(); 115 | cout << "Enter the value to be found:" << endl; 116 | cin >> val; 117 | find = map.search(val); 118 | if(find == -1) cout << val << " NOT FOUND!" << endl; 119 | else cout << val << " IS FOUNDED AT: " << find << endl; 120 | return 0; 121 | } 122 | -------------------------------------------------------------------------------- /HashTable/linearProbing.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Author : Fakhra Najm 3 | Topic : Hash Table implementation with Linear probing 4 | * Operations: 5 | * create 6 | * read 7 | * update 8 | * Delete 9 | * probe 10 | * hashkey 11 | */ 12 | 13 | #include 14 | using namespace std; 15 | 16 | class HashMap{ 17 | private: 18 | int size; 19 | int *Array; 20 | public: 21 | HashMap(int size); 22 | int hashkey(int val); 23 | int probe(int val); 24 | void create(); 25 | void read(); 26 | void update(int val); 27 | void Delete(int val); 28 | int search(int val); 29 | }; 30 | 31 | 32 | HashMap :: HashMap(int size = 0){ 33 | this -> size = 2 * size; 34 | Array = new int[this -> size]; 35 | fill(Array + 0, Array + this -> size, 0); 36 | create(); 37 | } 38 | 39 | 40 | /* 41 | * @param val to be inserted in hash table 42 | * @return hash key 43 | */ 44 | int HashMap :: hashkey(int val){ 45 | return val % size ; 46 | } 47 | 48 | // hashkey => h'(x) = (h(x) + f(i)) % size 49 | // where f(i) = i 50 | // i = 0,1,2,3,4,... 51 | // whenever there is a collision increment i 52 | /* 53 | * @param val in collision 54 | * @return index available index 55 | */ 56 | 57 | int HashMap :: probe(int val){ 58 | int i = 0; 59 | int index = hashkey(val); 60 | while(Array[index] != 0) 61 | index = (hashkey(val) + i++) % (size); 62 | return index; 63 | } 64 | 65 | void HashMap :: create(){ 66 | cout << "Enter Values:" << endl; 67 | int size = this -> size / 2; 68 | while(size--){ 69 | int input_value; 70 | cin >> input_value; 71 | update(input_value); 72 | } 73 | } 74 | 75 | void HashMap :: read(){ 76 | for(int key = 0; key < size; ++key) 77 | cout << Array[key] << " "; 78 | cout << endl; 79 | } 80 | 81 | void HashMap :: update(int val){ 82 | int key = hashkey(val); 83 | if(Array[key] == 0) 84 | Array[key] = val; 85 | else Array[probe(val)] = val; 86 | } 87 | 88 | void HashMap :: Delete(int val){ 89 | int key = hashkey(val); 90 | if(Array[key] == val) Array[key] = 0; 91 | else{ 92 | int i = 0; 93 | while(Array[key] != val){ 94 | if(Array[key] == 0) return ; 95 | key = (hashkey(val), ++i) % size; 96 | } 97 | } 98 | Array[key] = 0; 99 | return ; 100 | } 101 | 102 | int HashMap :: search(int val){ 103 | int key = hashkey(val); 104 | if(Array[key] == val) return key; 105 | else{ 106 | int i = 0; 107 | while(Array[key] != val){ 108 | if(Array[key] == 0) return -1; 109 | key = (hashkey(val) + ++i) % size; 110 | } 111 | } 112 | return key; 113 | } 114 | 115 | int main(){ 116 | int val; 117 | HashMap map(10); 118 | map.read(); 119 | cout << "Enter Value to delete : "; 120 | cin >> val; 121 | map.Delete(val); 122 | map.read(); 123 | return 0; 124 | } 125 | -------------------------------------------------------------------------------- /HashTable/quadraticProbing.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Author : Fakhra Najm 3 | Hash table implementataion : Quadratic Probing 4 | */ 5 | 6 | #include 7 | using namespace std; 8 | 9 | class HashMap{ 10 | private: 11 | int *Arr; 12 | int size; 13 | 14 | public : 15 | HashMap(){} 16 | void create(int size); 17 | void update(int val); 18 | int find(int val); 19 | int probe(int val); 20 | int hashvalue(int val); 21 | void read(); 22 | void Delete(int val); 23 | }; 24 | 25 | 26 | void HashMap :: create(int size){ 27 | this -> size = size; 28 | Arr = new int[size]; 29 | for(int i = 0; i < size; ++i) 30 | Arr[i] = 0; 31 | } 32 | 33 | void HashMap :: read(){ 34 | for(int index = 0; index < size; ++index) 35 | cout << Arr[index] << " "; 36 | cout << endl; 37 | } 38 | 39 | /* 40 | * To avoid primary clustring of the keys 41 | * probe = h'(x) = (h(x) + f(i)) % size 42 | * f(i) = i^ 43 | */ 44 | int HashMap :: probe(int val){ 45 | int i = 0, index = hashvalue(val); 46 | while(Arr[index] != 0){ 47 | index = (hashvalue(val) + i*i) % size ; 48 | i++; 49 | } 50 | return index; 51 | } 52 | 53 | int HashMap :: hashvalue(int value){ 54 | return value % size ; 55 | } 56 | 57 | void HashMap :: update(int val){ 58 | int indx = hashvalue(val); 59 | if(Arr[indx] == 0) 60 | Arr[indx] = val; 61 | else{ 62 | indx = probe(val); 63 | Arr[indx] = val; 64 | } 65 | } 66 | 67 | int HashMap :: find(int val){ 68 | int index = hashvalue(val); 69 | int i = 0; 70 | while(Arr[index] != 0 ){ 71 | if(Arr[index] == val) return index; 72 | index = (hashvalue(val) + i*i) % size ; 73 | i++; 74 | } 75 | return -1; 76 | } 77 | 78 | void HashMap :: Delete(int val){ 79 | int key = hashvalue(val); 80 | if(Arr[key] == val) Arr[key] = 0; 81 | else{ 82 | int i = 0; 83 | while(Arr[key] != val){ 84 | if(Arr[key] == 0) return; 85 | key = (hashvalue(val) + (i)*(i++)) % size; 86 | } 87 | Arr[key] = 0; 88 | } 89 | } 90 | 91 | int main(){ 92 | int size, element, remove_element; 93 | cout << "Enter size of the data elements:" << endl; 94 | cin >> size; 95 | cout << "The size of hash table is " << 2 * size << endl; 96 | HashMap map; 97 | map.create(size * 2); 98 | cout << "Enter elements:" << endl; 99 | for(int data = 0; data < size ; ++data){ 100 | int value; 101 | cin >> value; 102 | map.update(value); 103 | } 104 | cout << "Stored value : " << endl; 105 | map.read(); 106 | cout << "Enter element to be found : " << endl ; 107 | cin >> element; 108 | if( map.find(element) != -1) cout << "Founded at index " << map.find(element) << endl ; 109 | else cout << "ELEMENT NOT FOUND !!!!" << endl; 110 | cout << "Enter value to be deleted:" << endl; 111 | cin >> remove_element; 112 | map.Delete(remove_element); 113 | cout << "After deleting " << remove_element << ":" << endl; 114 | map.read(); 115 | return 0; 116 | } -------------------------------------------------------------------------------- /Heap/C/MaxHeap/createHeap.c: -------------------------------------------------------------------------------- 1 | /* 2 | Author: Fakhra Najm 3 | Email: fnajm09@gmail.com 4 | 5 | Topic: Inplace Max Heap Creation 6 | 7 | Operation: 8 | * CreateHeap 9 | * Insert 10 | * Delete 11 | * Print 12 | */ 13 | 14 | #include 15 | #include 16 | 17 | void CreateHeap(); 18 | void Insert(int index); 19 | void Print(); 20 | int Delete(int last_index); 21 | void swap(int *parent, int *child); 22 | 23 | int * heap; 24 | int size; 25 | 26 | int main() 27 | { 28 | printf("Enter size of Max heap: "); 29 | scanf("%d", &size); 30 | CreateHeap(); 31 | //Heap sort 32 | for(int i = size; i > 1; i--) Delete(i); 33 | Print(); 34 | return 0; 35 | } 36 | 37 | /* 38 | Inserts a value inside the heap from right to left 39 | @param heap array of values 40 | @param index index of the value to be inserted 41 | */ 42 | 43 | void Insert(int index) 44 | { 45 | int i = index, temp = heap[index]; 46 | 47 | while (i > 1 && temp > heap[i / 2]) 48 | { 49 | heap[i] = heap[i / 2]; 50 | i /= 2; 51 | } 52 | heap[i] = temp; 53 | } 54 | 55 | /* 56 | * Creates Heap of provided array 57 | * @param heap array of values 58 | * @param size of the array 59 | 60 | */ 61 | void CreateHeap() 62 | { 63 | heap = (int *)malloc(sizeof(int) * (size + 1)); 64 | heap[0] = 0; 65 | printf("Enter node values: "); 66 | for (int i = 1; i <= size; i++) 67 | scanf("%d", &heap[i]); 68 | for (int i = 2; i <= size; i++) 69 | Insert(i); 70 | } 71 | 72 | /* 73 | * Prints the Heap 74 | * @param heap created array of heap 75 | * @param size is the size of the Max heap 76 | */ 77 | 78 | void Print() 79 | { 80 | for (int i = 1; i <= size; i++) 81 | printf("%d ", heap[i]); 82 | printf("\n"); 83 | } 84 | 85 | /* 86 | * Deletes the root of the heap 87 | * @param heap array of heap 88 | * @param last_index index of the last element of the complete binary tree 89 | */ 90 | 91 | int Delete(int last_index) 92 | { 93 | int i = 1, j = i*2,deleted_val=heap[1]; 94 | heap[i] = heap[last_index]; 95 | heap[last_index] = deleted_val; 96 | while ( j < last_index -1) 97 | { 98 | // compare children of the parent node 99 | if (heap[j + 1] > heap[j]) 100 | j = j + 1; 101 | // swap root with child if child is greater than root 102 | if (heap[i] < heap[j]) 103 | { 104 | swap(&heap[i], &heap[j]); 105 | i = j; 106 | j = 2*i; 107 | } 108 | else 109 | break; 110 | } 111 | return deleted_val; 112 | } 113 | 114 | void swap(int *parent, int *child) 115 | { 116 | int temp; 117 | temp = *parent; 118 | *parent = *child; 119 | *child = temp; 120 | } -------------------------------------------------------------------------------- /Heap/C/MinHeap/createHeap.c: -------------------------------------------------------------------------------- 1 | /* 2 | Author: Fakhra Najm 3 | Email: fnajm09@gmail.com 4 | 5 | Topic: Inplace Min Heap Creation 6 | 7 | Operation: 8 | * CreateHeap 9 | * Insert 10 | * Delete 11 | * Print 12 | */ 13 | 14 | #include 15 | #include 16 | 17 | void CreateHeap(); 18 | void Insert(int index); 19 | void Print(); 20 | int Delete(int last_index); 21 | void swap(int *parent, int *child); 22 | 23 | int * heap; 24 | int size; 25 | 26 | int main() 27 | { 28 | printf("Enter size of Max heap: "); 29 | scanf("%d", &size); 30 | CreateHeap(); 31 | // Heap sort 32 | for(int i = size; i > 1; i--) Delete(i); 33 | Print(); 34 | return 0; 35 | } 36 | 37 | /* 38 | Inserts a value inside the heap from right to left 39 | @param heap array of values 40 | @param index index of the value to be inserted 41 | */ 42 | 43 | void Insert(int index) 44 | { 45 | int i = index, temp = heap[index]; 46 | 47 | while (i > 1 && temp < heap[i / 2]) 48 | { 49 | heap[i] = heap[i / 2]; 50 | i /= 2; 51 | } 52 | heap[i] = temp; 53 | } 54 | 55 | /* 56 | * Creates Heap of provided array 57 | * @param heap array of values 58 | * @param size of the array 59 | 60 | */ 61 | void CreateHeap() 62 | { 63 | heap = (int *)malloc(sizeof(int) * (size + 1)); 64 | heap[0] = 0; 65 | printf("Enter node values: "); 66 | for (int i = 1; i <= size; i++) 67 | scanf("%d", &heap[i]); 68 | for (int i = 2; i <= size; i++) 69 | Insert(i); 70 | } 71 | 72 | /* 73 | * Prints the Heap 74 | * @param heap created array of heap 75 | * @param size is the size of the Min heap 76 | */ 77 | 78 | void Print() 79 | { 80 | for (int i = 1; i <= size; i++) 81 | printf("%d ", heap[i]); 82 | printf("\n"); 83 | } 84 | 85 | /* 86 | * Deletes the root of the heap 87 | * @param heap array of heap 88 | * @param last_index index of the last element of the complete binary tree 89 | */ 90 | 91 | int Delete(int last_index) 92 | { 93 | int x, i = 1, j = i*2,deleted_val=heap[1]; 94 | heap[i] = heap[last_index]; 95 | heap[last_index] = deleted_val; 96 | while ( j < last_index -1) 97 | { 98 | // compare children of the parent node 99 | if (heap[j + 1] < heap[j]) 100 | j = j + 1; 101 | // swap root with child if child is smaller than root 102 | if (heap[i] > heap[j]) 103 | { 104 | swap(&heap[i], &heap[j]); 105 | i = j; 106 | j = 2*i; 107 | } 108 | else 109 | break; 110 | } 111 | return deleted_val; 112 | } 113 | 114 | void swap(int *parent, int *child) 115 | { 116 | int temp; 117 | temp = *parent; 118 | *parent = *child; 119 | *child = temp; 120 | } -------------------------------------------------------------------------------- /Heap/C/heapify.c: -------------------------------------------------------------------------------- 1 | /* 2 | Author: Fakhra Najm 3 | Email: fnajm09@gmail.com 4 | 5 | Topic: Creation of max heap by heapify 6 | */ 7 | 8 | #include 9 | #include 10 | 11 | int *__HEAP; 12 | int HEAP_SIZE; 13 | void heapify(int index); 14 | void swap(int *parent, int *child); 15 | void createHeap(); 16 | 17 | int main() 18 | { 19 | 20 | scanf("%d", &HEAP_SIZE); 21 | createHeap(); 22 | for (int i = 1; i <= HEAP_SIZE; i++) 23 | { 24 | printf("%d ", __HEAP[i]); 25 | } 26 | printf("\n"); 27 | 28 | return 0; 29 | } 30 | 31 | void createHeap() 32 | { 33 | __HEAP = (int *)malloc(sizeof(int) * (HEAP_SIZE + 1)); 34 | __HEAP[0] = 0; 35 | for (int i = 1; i <= HEAP_SIZE; i++) 36 | scanf("%d", &__HEAP[i]); 37 | for (int i = HEAP_SIZE / 2; i > 0; i--) 38 | heapify(i); 39 | } 40 | 41 | void heapify(int index) 42 | { 43 | for(int i = (index/2)-1; i >= 0; i--){ 44 | int j = index * 2 +1 ; 45 | while (j < index - 1) 46 | { 47 | if (__HEAP[j] < __HEAP[j + 1]) 48 | j = j + 1; 49 | if (__HEAP[i] < __HEAP[j]) 50 | { 51 | swap(&__HEAP[i], &__HEAP[j]); 52 | i = j; 53 | j = 2*i +1; 54 | } 55 | else 56 | break; 57 | } 58 | } 59 | } 60 | 61 | void swap(int *parent, int *child) 62 | { 63 | int temp; 64 | temp = *parent; 65 | *parent = *child; 66 | *child = temp; 67 | } -------------------------------------------------------------------------------- /Heap/CPP/heapify.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class Heap{ 7 | vectorheap; 8 | public: 9 | // using 1 indexed Heap 10 | Heap(){heap.push_back(INT_MAX);} 11 | Heap(vectorvalues); 12 | int size(){return heap.size();} 13 | void heapify(vectorvalues); 14 | void print(); 15 | }; 16 | 17 | int main(){ 18 | Heap heap({-1,30,20,15,5,10,12,6,40}); 19 | cout << "Heap using heapify: "; 20 | heap.print(); 21 | return 0; 22 | } 23 | 24 | Heap :: Heap(vectorvalues){ 25 | heap.push_back(INT_MAX); 26 | heapify(values); 27 | } 28 | 29 | void Heap :: heapify(vectorvalues){ 30 | int size = values.size() - 1; 31 | int nodePtr = size / 2; 32 | while(nodePtr > 0){ 33 | int childNodePtr = nodePtr * 2; 34 | if(values[childNodePtr] < values[childNodePtr + 1]) 35 | childNodePtr = childNodePtr + 1; 36 | if(values[childNodePtr] > values[nodePtr]) 37 | swap(values[childNodePtr], values[nodePtr]); 38 | nodePtr /= 2; 39 | } 40 | heap.swap(values); 41 | heap.front() = INT_MAX; // 0th index is useless here 42 | } 43 | 44 | void Heap :: print(){ 45 | for(int index = 1; index < size(); ++index){ 46 | cout << heap[index] << " "; 47 | } 48 | cout << endl; 49 | } -------------------------------------------------------------------------------- /Heap/CPP/maxHeap.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class Heap{ 7 | vectorheap; 8 | public: 9 | // using 1 indexed Heap 10 | Heap(){heap.push_back(INT_MAX);} 11 | Heap(vectorvalues); 12 | 13 | int size(){return heap.size();} 14 | vector getHeapArray(){return heap;} 15 | 16 | void push(int val); 17 | int pop(); 18 | void print(); 19 | vector heapSort(); 20 | }; 21 | 22 | void print(vectorarr){ 23 | for(int index = 0; index < arr.size(); ++index) 24 | cout << arr[index] << " "; 25 | cout << endl; 26 | } 27 | 28 | int main(){ 29 | Heap heap({30,20,15,5,10,12,6,40}); 30 | cout << "Heap:" << endl; 31 | heap.print(); 32 | cout << "Heap Sort:" << endl; 33 | print(heap.heapSort()); 34 | return 0; 35 | } 36 | 37 | Heap :: Heap(vectorvalues){ 38 | heap.push_back(INT_MAX); 39 | for(int index = 0; index < values.size(); ++index){ 40 | push(values[index]); 41 | } 42 | } 43 | 44 | void Heap :: push(int val){ 45 | heap.push_back(val); 46 | int index = size() - 1; 47 | int parentNodeIndex = index / 2; 48 | while(heap[parentNodeIndex] < heap[index]){ 49 | swap(heap[parentNodeIndex], heap[index]); 50 | index = parentNodeIndex; 51 | parentNodeIndex /= 2; 52 | } 53 | } 54 | 55 | int Heap :: pop(){ 56 | if(heap.size() == 1) return -1; 57 | int parentNodePtr = 1; 58 | int childNodePtr = 2 * parentNodePtr; 59 | int lastNodePtr = size() - 1; 60 | int top = heap[parentNodePtr]; 61 | swap(heap[parentNodePtr], heap[lastNodePtr]); 62 | // lastNodePtr = size() - 1; 63 | heap.pop_back(); 64 | 65 | while(childNodePtr + 1 < lastNodePtr){ 66 | if(heap[childNodePtr] < heap[childNodePtr + 1]) 67 | childNodePtr = childNodePtr + 1; 68 | if(heap[parentNodePtr] < heap[childNodePtr]){ 69 | swap(heap[parentNodePtr], heap[childNodePtr]); 70 | parentNodePtr = childNodePtr; 71 | childNodePtr = 2*parentNodePtr; 72 | } 73 | else break; 74 | } 75 | 76 | return top; 77 | } 78 | 79 | vector Heap :: heapSort(){ 80 | int heapSize = Heap :: size(); 81 | vectorsortedArray; 82 | while(heapSize > 0){ 83 | int topValue = pop(); 84 | if(topValue != -1) 85 | sortedArray.push_back(topValue); 86 | heapSize--; 87 | } 88 | return sortedArray; 89 | } 90 | 91 | void Heap :: print(){ 92 | for(int index = 1; index < size(); ++index){ 93 | cout << heap[index] << " "; 94 | } 95 | cout << endl; 96 | } -------------------------------------------------------------------------------- /LinkedList/DoublyLinkedList/doublyLinkList.c: -------------------------------------------------------------------------------- 1 | /* 2 | Author : Fakhra najm 3 | Operations on doubly LinkedList 4 | 1. Create 5 | 2. Display 6 | 3. calculateLength 7 | 4. insert 8 | 5. Delete 9 | 6. Reverse 10 | */ 11 | 12 | 13 | #include 14 | #include 15 | 16 | struct Node 17 | { 18 | struct Node * prev; 19 | int data; 20 | struct Node * next; 21 | }*Head ; 22 | 23 | struct Node * CreateNode(int value){ 24 | struct Node * node = (struct Node *)malloc(sizeof(struct Node)); 25 | node->prev = NULL; 26 | node->data = value; 27 | node->next = NULL; 28 | return node; 29 | } 30 | 31 | void CreateLinkList(int values[], int length){ 32 | Head = CreateNode(values[0]); 33 | struct Node *current, *last = Head; 34 | for (int i = 1; i < length; ++i) 35 | { 36 | current = CreateNode(values[i]); 37 | last->next = current; 38 | current->prev = last; 39 | last = current; 40 | } 41 | } 42 | 43 | int calculateLength(struct Node * Head){ 44 | int length = 0; 45 | while(Head){ 46 | length ++; 47 | Head = Head->next; 48 | } 49 | return length; 50 | } 51 | 52 | void InsertHead(struct Node * node, int value){ 53 | node = CreateNode(value); 54 | node->next = Head; 55 | Head->prev = node; 56 | Head = node; 57 | } 58 | 59 | void InsertNode(struct Node * Head, int index, int value){ 60 | struct Node * node = CreateNode(value); 61 | if(index < 0 || index > calculateLength(Head)) 62 | return; 63 | if(index == 0){ 64 | if (Head == NULL) 65 | Head = node; 66 | else 67 | InsertHead(Head, value); 68 | } 69 | else{ 70 | for (int i = 0; i < index-1; ++i) 71 | Head = Head->next; 72 | node->prev = Head; 73 | node->next = Head->next; 74 | if(Head->next) 75 | Head->next->prev = node; 76 | Head->next = node; 77 | Head = node; 78 | } 79 | } 80 | 81 | int removeHead(struct Node * current){ 82 | Head = Head->next; 83 | if(Head) 84 | Head->prev = NULL; 85 | int value = current->data; 86 | free(current); 87 | return value; 88 | } 89 | 90 | int removeValue(struct Node * Head, int index){ 91 | int value = -1; 92 | if(index < 0 || index > calculateLength(Head)) 93 | return -1; 94 | if(index == 0){ 95 | value = removeHead(Head); 96 | } 97 | 98 | else{ 99 | for (int i = 0; i < index; ++i) 100 | Head = Head->next; 101 | value = Head->data; 102 | Head->prev->next = Head->next; 103 | if(Head->next) 104 | Head->next->prev = Head->prev; 105 | free(Head); 106 | } 107 | return value; 108 | } 109 | 110 | void ReverseList(struct Node * head) 111 | { 112 | struct Node * store ; 113 | while(head){ 114 | store = head->next; 115 | head->next = head->prev; 116 | head->prev = store; 117 | head = head->prev; 118 | if( head != NULL && head->next == NULL) 119 | Head = head; 120 | } 121 | } 122 | 123 | void PrintList(struct Node * Head) 124 | { 125 | while(Head != NULL){ 126 | printf("%d ", Head->data); 127 | Head = Head->next; 128 | } 129 | printf("\n"); 130 | } 131 | 132 | void PrintReverseList(struct Node * Head){ 133 | while(Head->next != NULL) 134 | Head = Head->next; 135 | while(Head){ 136 | printf("%d ",Head->data ); 137 | Head = Head->prev; 138 | } 139 | printf("\n"); 140 | } 141 | 142 | int main(){ 143 | int values[] = {1, 2, 3, 4, 5}; 144 | CreateLinkList(values, 5); 145 | printf("Created linkedList:\n"); 146 | PrintList(Head); 147 | printf("length:%d\n", calculateLength(Head) ); 148 | InsertNode(Head, 5, 6); 149 | printf("New linkedList:\n"); 150 | PrintList(Head); 151 | printf("After deletion of value %d containing node:\n", removeValue(Head, 0)); 152 | PrintList(Head); 153 | printf("Reverse display of the linkedList\n"); 154 | ReverseList(Head); 155 | PrintList(Head); 156 | return 0; 157 | } -------------------------------------------------------------------------------- /LinkedList/IterativeLinkedList/addition_on_linkedList_iterative.c: -------------------------------------------------------------------------------- 1 | /* 2 | Author Fakhra Najm, fnajm09@gmail.com 3 | Operations on singly Linked List 4 | 1. create 5 | 2. show 6 | 3. find max 7 | 4. find sum 8 | */ 9 | #include 10 | #include 11 | 12 | struct Node 13 | { 14 | int data; 15 | struct Node *next; 16 | }*head=NULL; 17 | 18 | 19 | /** 20 | * creates a node 21 | * @param value to be inserted into node 22 | * @return node pointer to created node 23 | */ 24 | struct Node * createNode(int value) { 25 | struct Node *node = (struct Node *)malloc(sizeof(struct Node)); 26 | node->data = value; 27 | node->next = NULL; 28 | return node; 29 | } 30 | 31 | /** 32 | * Creates a linkedlist from given integer values 33 | * @param values from which linked list is to be created 34 | * @param length of given list of values 35 | */ 36 | void createLinkList(int values[],int length) 37 | { 38 | head = createNode(values[0]); 39 | struct Node *last = head, *current; 40 | 41 | // loop over given values and insert into linked list 42 | for(int i = 1; i < length; i++) { 43 | current = createNode(values[i]); 44 | last->next = current; 45 | last = current; 46 | } 47 | } 48 | 49 | /** 50 | * calculates sum of values of linked list nodes 51 | * @param head pointer to the head of linked list 52 | * @return sum calculated sum of values of Linkedlist 53 | */ 54 | int calculateSum(struct Node *head) 55 | { 56 | int sum = 0; 57 | while(head != NULL) { 58 | sum += head->data; 59 | head = head->next; 60 | } 61 | return sum; 62 | } 63 | 64 | /** 65 | * print values of a linkedlist 66 | * @param head pointer to the head of linkedlist 67 | */ 68 | void printList(struct Node *head) 69 | { 70 | while(head != NULL) { 71 | printf("%d ",head->data ); 72 | head = head->next; 73 | } 74 | } 75 | 76 | /** 77 | * finds maximum value from a linkedlist 78 | * @param head pointer to the head of linkedlist 79 | * @return max value of LinkedList 80 | */ 81 | int findMax(struct Node *head) 82 | { 83 | int max = head->data; 84 | head = head->next; 85 | // loop over ll and update max 86 | while(head) { 87 | if(max < head->data) max = head->data; 88 | head = head->next; 89 | } 90 | return max; 91 | } 92 | 93 | 94 | int main() 95 | { 96 | int values[] = { 8, 3, 7, 12, 9 }; 97 | createLinkList(values, 5); 98 | printList(head); 99 | printf("\nThe sum of all elements of linkedlist = %d ",calculateSum(head)); 100 | printf("\nThe maxima of the list: %d",findMax(head)); 101 | return 0; 102 | } -------------------------------------------------------------------------------- /LinkedList/IterativeLinkedList/count_of_nodes.iterative.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | struct Node 5 | { 6 | int Data; 7 | struct Node *next; 8 | }*first=NULL; 9 | 10 | void Create_linkedList(int a[],int elements) 11 | { 12 | struct Node *last,*current; 13 | int i; 14 | first=(struct Node *)malloc(sizeof(struct Node)); 15 | 16 | first->Data=a[0]; 17 | first->next=NULL; 18 | last=first; 19 | 20 | for(i=1;iData=a[i]; 23 | current->next=NULL; 24 | last->next=current; 25 | last=current; 26 | } 27 | } 28 | 29 | int count_of_node(struct Node *node) 30 | { 31 | int count=0; 32 | while(node!=NULL){ 33 | count++; 34 | node=node->next; 35 | } 36 | return count; 37 | } 38 | 39 | 40 | int main() 41 | { 42 | int array[]={5,10,15,20,25}; 43 | Create_linkedList(array,5); 44 | printf("lenght of the list:%d", count_of_node(first) ); 45 | return 0; 46 | } 47 | -------------------------------------------------------------------------------- /LinkedList/IterativeLinkedList/createListByinsert.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | struct Node 5 | { 6 | int data; 7 | struct Node * next; 8 | }*head=NULL,*last=NULL; 9 | 10 | struct Node * createNode(int value) 11 | { 12 | struct Node * node = (struct Node *)malloc(sizeof(struct Node)); 13 | node->data = value; 14 | node->next = NULL; 15 | return node; 16 | } 17 | 18 | void createLinkList(int value) 19 | { 20 | struct Node * node; 21 | node = createNode(value); 22 | if(head == NULL) 23 | { 24 | head = last = node ; // all the nodes are at one since there is no other node 25 | } 26 | else 27 | { 28 | last->next = node ; //current node becomes the next to the previous last node 29 | last = node; //here the current node "node" is updated as last node "last" 30 | } 31 | } 32 | 33 | void ShowList(int nodes) 34 | { 35 | for( int i = 0; i < nodes ; i++) 36 | { 37 | printf("%d ", head->data ); 38 | head = head->next; 39 | } 40 | } 41 | 42 | int main() 43 | { 44 | int value,nodes; 45 | printf("Enter number of nodes"); 46 | scanf("%d", &nodes); 47 | printf("\nEnter all elements of the link list:\n"); 48 | for(int i = 0; i < nodes; i++){ 49 | scanf("%d", &value); 50 | createLinkList(value); 51 | } 52 | ShowList(nodes); 53 | return 0; 54 | } -------------------------------------------------------------------------------- /LinkedList/IterativeLinkedList/displaying_linkedList_iterative.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | struct Node 5 | { 6 | int Data; 7 | struct Node *Next; 8 | }*first=NULL; 9 | 10 | void Create(int A[],int n) 11 | { 12 | int i; 13 | struct Node *last,*current; 14 | 15 | first =(struct Node *)malloc(sizeof(struct Node)); 16 | 17 | first->Data=A[0]; 18 | first->Next=NULL; 19 | last=first; 20 | 21 | for(i=1;iData=A[i]; 25 | current->Next=NULL; 26 | last->Next=current; 27 | last=current; 28 | } 29 | 30 | } 31 | 32 | void Display(struct Node *node) 33 | { 34 | printf("Elements in the list are:\n"); 35 | while(node!=NULL){ 36 | printf("%d ",node->Data ); 37 | node=node->Next; 38 | } 39 | } 40 | 41 | int main(){ 42 | struct Node *node; 43 | int Array[]={1,3,5,7,9}; 44 | Create(Array,5); 45 | Display(first); 46 | return 0; 47 | } 48 | -------------------------------------------------------------------------------- /LinkedList/IterativeLinkedList/insertInSortedList.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | struct Node 5 | { 6 | int data; 7 | struct Node *next; 8 | }*head=NULL,*last=NULL; 9 | 10 | struct Node * createNode(int value) 11 | { 12 | struct Node *node = (struct Node *)malloc(sizeof(struct Node)); 13 | node->data = value; 14 | node->next = NULL; 15 | return node ; 16 | } 17 | 18 | void createLinkList(int value) 19 | { 20 | struct Node *node; 21 | node = createNode(value); 22 | if( head == NULL) 23 | head = last = node ; 24 | else{ 25 | last->next = node; 26 | last = node; 27 | } 28 | } 29 | 30 | void InsertSort(int value) 31 | { 32 | struct Node * node = createNode(value); 33 | struct Node * pointer = head,*prev_node; 34 | if(head->data > value){ 35 | node->next = head; 36 | head = node; 37 | } 38 | 39 | else { 40 | while(pointer && pointer->data < value){ 41 | prev_node = pointer; 42 | pointer = pointer->next; 43 | } 44 | 45 | node->next = prev_node->next; 46 | prev_node->next = node; 47 | } 48 | 49 | } 50 | 51 | void showList(int nodes) 52 | { 53 | while(head){ 54 | printf("%d ", head->data ); 55 | head = head->next; 56 | } 57 | } 58 | 59 | int main() 60 | { 61 | int nodes,value; 62 | printf("Enter number of nodes : \n" ); 63 | scanf("%d", &nodes); 64 | printf("\nEnter all elements of the list:\n"); 65 | for( int i = 0; i < nodes; i++){ 66 | scanf("%d", &value); 67 | createLinkList(value); 68 | } 69 | 70 | InsertSort(10); 71 | printf("\n"); 72 | showList(nodes); 73 | return 0; 74 | } -------------------------------------------------------------------------------- /LinkedList/IterativeLinkedList/insert_iterative.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | struct Node 5 | { 6 | int data; 7 | struct Node * next; 8 | }*head = NULL; 9 | 10 | struct Node * createNode(int value) 11 | { 12 | struct Node *node = (struct Node *)malloc(sizeof(struct Node)); 13 | node->data = value; 14 | node->next = NULL; 15 | return node; 16 | } 17 | 18 | void CreateLinkList(int values[], int length) 19 | { 20 | head = createNode(values[0]); 21 | struct Node *current,*last=head; 22 | 23 | for(int i = 1; i < length; i++){ 24 | current = createNode(values[i]); 25 | last->next = current; 26 | last = current; 27 | } 28 | } 29 | 30 | int nodesCount(struct Node *node) 31 | { 32 | int count=0; 33 | while(node!=NULL){ 34 | count++; 35 | node=node->next; 36 | } 37 | return count; 38 | } 39 | 40 | void showList(struct Node *head) 41 | { 42 | while(head != NULL){ 43 | printf("%d ",head->data ); 44 | head = head->next; 45 | } 46 | } 47 | 48 | void insertValue(struct Node *head, int value , int position) 49 | { 50 | struct Node * new =(struct Node *)malloc(sizeof(struct Node)); 51 | new->data = value; 52 | if(position > nodesCount(head) || position < 0) 53 | return; 54 | if(position == 0){ 55 | new->next = head; 56 | head = new; 57 | } 58 | else{ 59 | for(int i = 0; i < position-1; i++) 60 | head = head->next; 61 | new->next = head->next; 62 | head->next = new; 63 | } 64 | } 65 | 66 | 67 | 68 | int main() 69 | { 70 | int values[] = {8, 5, 3, 9, 7}; 71 | CreateLinkList(values, 5); 72 | showList(head); 73 | insertValue(head , 10, 4); 74 | printf("\nshow new list formed\n"); 75 | showList(head); 76 | return 0; 77 | } 78 | 79 | -------------------------------------------------------------------------------- /LinkedList/IterativeLinkedList/linearSearch_iterative.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | struct Node 5 | { 6 | int data; 7 | struct Node *next; 8 | }*head=NULL; 9 | 10 | 11 | struct Node * CreateNode(int value) 12 | { 13 | struct Node *node = (struct Node *)malloc(sizeof(struct Node)); 14 | node->data = value; 15 | node->next = NULL; 16 | return node; 17 | } 18 | 19 | void createList(int values[],int length) 20 | { 21 | head=CreateNode(values[0]); 22 | struct Node *current,*last=head; 23 | for(int i=1; inext = current; 26 | last = current; 27 | } 28 | } 29 | 30 | struct Node * searchList(struct Node * head , int value) 31 | { 32 | while(head != NULL){ 33 | if(value == head->data) 34 | return head; 35 | else 36 | head = head->next; 37 | } 38 | return NULL; 39 | } 40 | 41 | void printList(struct Node *head) 42 | { 43 | while(head != NULL){ 44 | printf("%d ", head->data); 45 | head = head->next; 46 | } 47 | } 48 | 49 | struct Node * SearchListImproved(struct Node *node, int value) 50 | { 51 | struct Node * previous = NULL; 52 | while(node != NULL){ 53 | if(value == node->data){ 54 | previous->next = node->next; 55 | node->next = head; 56 | head = node; 57 | 58 | return head; 59 | } 60 | else{ 61 | previous = node ; 62 | node = node->next; 63 | } 64 | } 65 | } 66 | 67 | 68 | int main() 69 | { 70 | struct Node *searchResult; 71 | int values[] = {1, 8, 5, 12, 9}; 72 | createList(values, 5); 73 | printList(head); 74 | searchResult = searchList(head, 12); 75 | if(searchResult != NULL) 76 | printf("search result succeeded\nvalue found: %d ",searchResult->data); 77 | else 78 | printf("Failure!!!!\n"); 79 | 80 | SearchListImproved(head , 12); 81 | 82 | printf("\nLet's see the effect of improved function\n"); 83 | printList(head); 84 | return 0; 85 | } 86 | -------------------------------------------------------------------------------- /LinkedList/RecursiveLinkedList/addition_on_linkedList_recursive.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | struct Node 5 | { 6 | int data; 7 | struct Node *next; 8 | }*first=NULL; 9 | 10 | void Create_linkedList(int a[],int elements) 11 | { 12 | struct Node *last,*current; 13 | int i; 14 | 15 | first=(struct Node *)malloc(sizeof(struct Node)); 16 | 17 | first->data=a[0]; 18 | first->next=NULL; 19 | last=first; 20 | 21 | for(i=1;idata=a[i]; 25 | current->next=NULL; 26 | last->next=current; 27 | last=current; 28 | } 29 | } 30 | 31 | void Display_linkedList(struct Node *node) 32 | { 33 | while(node!=NULL){ 34 | printf("%d ",node->data ); 35 | node=node->next; 36 | } 37 | } 38 | 39 | int recursive_addition(struct Node *node) 40 | { 41 | if(node) 42 | return recursive_addition(node->next)+node->data; 43 | else 44 | return 0; 45 | 46 | } 47 | 48 | 49 | int main() 50 | { 51 | int array[]={10,20,30,40,50}; 52 | Create_linkedList(array,5); 53 | Display_linkedList(first); 54 | printf("\nthe sum of all elements in list = %d ",recursive_addition(first) ); 55 | return 0; 56 | } 57 | -------------------------------------------------------------------------------- /LinkedList/RecursiveLinkedList/countNodes.c.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | struct Node 5 | { 6 | int Data; 7 | struct Node *next; 8 | }*first=NULL; 9 | 10 | void Create_linkedList(int a[],int elements) 11 | { 12 | struct Node *last,*current; 13 | int i; 14 | first=(struct Node *)malloc(sizeof(struct Node)); 15 | 16 | first->Data=a[0]; 17 | first->next=NULL; 18 | last=first; 19 | 20 | for(i=1;iData=a[i]; 23 | current->next=NULL; 24 | last->next=current; 25 | last=current; 26 | } 27 | } 28 | 29 | int count_of_node(struct Node *node) 30 | { 31 | if(node!=NULL) 32 | return count_of_node(node->next)+1; 33 | else 34 | return 0; 35 | } 36 | 37 | 38 | int main() 39 | { 40 | int array[]={5,10,15,20,25}; 41 | Create_linkedList(array,5); 42 | printf("number of nodes:%d", count_of_node(first) ); 43 | return 0; 44 | } 45 | -------------------------------------------------------------------------------- /LinkedList/RecursiveLinkedList/displaying_linkedList_recursive.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | struct Node 5 | { 6 | int Data; 7 | struct Node *Next; 8 | }*first=NULL; 9 | 10 | void Create(int A[],int n) 11 | { 12 | int i; 13 | struct Node *last,*current; 14 | 15 | first =(struct Node *)malloc(sizeof(struct Node)); 16 | 17 | first->Data=A[0]; 18 | first->Next=NULL; 19 | last=first; 20 | 21 | for(i=1;iData=A[i]; 25 | current->Next=NULL; 26 | last->Next=current; 27 | last=current; 28 | } 29 | 30 | } 31 | 32 | void Display_recursive(struct Node *node) 33 | { 34 | if(node!=NULL){ 35 | printf("%d ",node->Data ); 36 | Display_recursive(node->Next); 37 | } 38 | } 39 | 40 | int max_element(struct Node *node) 41 | { 42 | int x; 43 | if(node==NULL) 44 | return 0; 45 | x=max_element(node->Next); 46 | return (x>node->Data)? x:node->Data; 47 | 48 | } 49 | 50 | int main(){ 51 | struct Node *node; 52 | int Array[]={8,3,7,12,9}; 53 | Create(Array,5); 54 | printf("Elements in the list are:\n"); 55 | Display_recursive(first); 56 | printf("\n"); 57 | printf("The maxima of the list=%d",max_element(first)); 58 | return 0; 59 | } 60 | -------------------------------------------------------------------------------- /LinkedList/RecursiveLinkedList/linearSearch_recursive.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | struct Node 5 | { 6 | int data; 7 | struct Node *next; 8 | }*head=NULL; 9 | 10 | struct Node * CreateNode(int value) 11 | { 12 | struct Node *node = (struct Node *)malloc(sizeof(struct Node)); 13 | node->data = value; 14 | node->next = NULL; 15 | return node; 16 | } 17 | 18 | void CreateLinkList(int values[], int length) 19 | { 20 | head=CreateNode(values[0]); 21 | struct Node * current, *last = head; 22 | 23 | for(int i=1; inext = current; 26 | last = current; 27 | } 28 | } 29 | 30 | void ShowList(struct Node * head) 31 | { 32 | while(head != NULL){ 33 | printf("%d ", head->data ); 34 | head = head->next; 35 | } 36 | } 37 | 38 | struct Node * searchList(struct Node * head, int key) 39 | { 40 | if(head) 41 | if(key == head->data ) 42 | return head; 43 | else 44 | return searchList(head->next, key); 45 | 46 | else 47 | return NULL; 48 | } 49 | 50 | int main(){ 51 | 52 | struct Node * searchResult; 53 | 54 | int values[] = {15, 8, 25, 7, 3, 12}; 55 | 56 | CreateLinkList(values, 6); 57 | 58 | ShowList(head); 59 | 60 | searchResult = searchList(head, 25); 61 | 62 | if(searchResult != NULL) 63 | printf("\nlist element Found %d",searchResult->data); 64 | else 65 | printf("\nlist element not found"); 66 | return 0; 67 | } -------------------------------------------------------------------------------- /LinkedList/RecursiveLinkedList/reversingLinksrecursively.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | struct Node 5 | { 6 | int data; 7 | struct Node * next; 8 | }*head = NULL , *last = NULL ; 9 | 10 | struct Node * createNode(int value) 11 | { 12 | struct Node * node = (struct Node *)malloc(sizeof(struct Node)); 13 | node->data = value; 14 | node->next = NULL; 15 | return node; 16 | } 17 | 18 | void createLinkList(int value) 19 | { 20 | struct Node * node; 21 | node = createNode(value); 22 | if(head == NULL) 23 | { 24 | head = last = node ; 25 | } 26 | else 27 | { 28 | last->next = node ; 29 | last = node; 30 | } 31 | } 32 | 33 | void ShowList(struct Node * head) 34 | { 35 | while(head != NULL) 36 | { 37 | printf("%d ", head->data); 38 | head = head->next; 39 | } 40 | } 41 | 42 | 43 | void reverseLinkList(struct Node *pointer , struct Node *node) 44 | { 45 | if(node != NULL){ 46 | reverseLinkList(node, node->next ); 47 | node->next = pointer; 48 | } 49 | else 50 | head = pointer; 51 | } 52 | 53 | 54 | int main() 55 | { 56 | int nodes,value; 57 | printf("Enter number of nodes :\n"); 58 | scanf("%d", &nodes); 59 | printf("enter all values of list\n"); 60 | for(int i = 0; i < nodes; i++) 61 | { 62 | scanf("%d", &value); 63 | createLinkList(value); 64 | } 65 | ShowList(head); 66 | reverseLinkList(NULL , head); 67 | printf("\n"); 68 | ShowList(head); 69 | return 0; 70 | } -------------------------------------------------------------------------------- /LinkedList/circularLinkedList/CircularLinkListRecursive.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Author : Fakhra najm 3 | */ 4 | 5 | 6 | #include 7 | #include 8 | 9 | struct Node{ 10 | int data; 11 | struct Node * next; 12 | }*Head; 13 | 14 | /** 15 | * creates the circular node 16 | * @param the value to be inserted into the node 17 | * @return node pointer to created node 18 | */ 19 | struct Node * createCircularNode(int value){ 20 | struct Node * node = (struct Node *)malloc(sizeof(struct Node)); 21 | node->data = value; 22 | node->next = node; 23 | return node; 24 | } 25 | /** 26 | * creates the circular linkedList 27 | * @param value to be inserted into nodes 28 | * @param length of given list of values 29 | */ 30 | void createLinkList(int values[], int length){ 31 | struct Node *last, *current; 32 | Head = createCircularNode(values[0]); 33 | last = Head; 34 | for (int i = 1; i < length; ++i) 35 | { 36 | current = createCircularNode(values[i]); 37 | last->next = current; 38 | current->next = Head; 39 | last = current; 40 | } 41 | } 42 | 43 | /** 44 | * prints values of the linkedlist recursively. 45 | * @param pointer to the head of the list . 46 | * if the last becomes head then the linkedList has completed one round. 47 | * after one round all the list would have been printed and we have to stop. 48 | */ 49 | 50 | void PrintList(struct Node * head){ 51 | static int round = 0; 52 | if(head != Head || round == 0){ 53 | round = 1; 54 | printf("%d ", head->data ); 55 | PrintList(head->next); 56 | } 57 | round = 0; 58 | } 59 | 60 | int main(){ 61 | int values[] = {1, 2, 3, 4, 5}; 62 | createLinkList(values, 5); 63 | PrintList(Head); 64 | return 0; 65 | } -------------------------------------------------------------------------------- /LinkedList/circularLinkedList/circularDoublyLinkList.c: -------------------------------------------------------------------------------- 1 | /* 2 | Author : Fakhra najm 3 | Operations on circularDoublyLinkedList 4 | * 1. Create 5 | * 2. Display 6 | * 3. Insert 7 | * 4. Delete 8 | */ 9 | 10 | #include 11 | #include 12 | 13 | struct Node{ 14 | struct Node * prev; 15 | int data; 16 | struct Node * next; 17 | }* Head ; 18 | 19 | struct Node * createNode(int value){ 20 | struct Node * node = (struct Node *)malloc(sizeof(struct Node)); 21 | node->prev = node; 22 | node->data = value; 23 | node->next = node; 24 | return node; 25 | } 26 | 27 | void createLinkList(int values[], int length){ 28 | Head = createNode(values[0]); 29 | struct Node * current , *last = Head; 30 | for (int i = 1; i < length; ++i){ 31 | current = createNode(values[i]); 32 | last->next = current; 33 | current->prev = last; 34 | current->next = Head; 35 | Head->prev = current; 36 | last = current; 37 | } 38 | } 39 | 40 | int findLength(struct Node * node){ 41 | int length = 0; 42 | do{ 43 | length++; 44 | node = node->next; 45 | }while(node != Head); 46 | return length; 47 | } 48 | 49 | void insertHead(struct Node *current, int value){ 50 | current = createNode(value); 51 | current->next = Head; 52 | Head->prev->next = current; 53 | current->prev = Head->prev; 54 | Head->prev = current; 55 | Head = current; 56 | } 57 | 58 | void insertNode(struct Node * Head, int index, int value ){ 59 | if(index < 0 || index > findLength(Head)) 60 | return; 61 | if(index == 0){ 62 | if(Head == NULL) 63 | Head = createNode(value); 64 | else 65 | insertHead(Head, value); 66 | } 67 | else{ 68 | struct Node *node = createNode(value); 69 | for (int i = 0; i < index-1; ++i) 70 | Head = Head->next; 71 | node->next = Head->next; 72 | Head->next->prev = node; 73 | Head->next = node; 74 | node->prev = Head; 75 | } 76 | } 77 | 78 | int removeNode(struct Node * node, int index){ 79 | int removed = -1; 80 | if(index > findLength(Head) || index < 0) 81 | return -1; 82 | if(index == 0){ 83 | node->prev->next = Head->next; 84 | Head = Head->next; 85 | Head->prev = node->prev; 86 | removed = node->data; 87 | free(node); 88 | } 89 | else{ 90 | for (int i = 0; i < index; ++i) 91 | node = node->next; 92 | node->prev->next = node->next; 93 | node->next->prev = node->prev; 94 | removed = node->data; 95 | free(node); 96 | } 97 | return removed; 98 | } 99 | 100 | void printList(struct Node * node){ 101 | do{ 102 | printf("%d ", node->data); 103 | node = node->next; 104 | }while(node != Head); 105 | printf("\n"); 106 | } 107 | 108 | 109 | int main(){ 110 | int values[] = {10, 20, 30, 40, 50}; 111 | createLinkList(values, 5); 112 | printf("created link list\n"); 113 | printList(Head); 114 | insertNode(Head, 0 , 60); 115 | printf("LinkList after insertion\n"); 116 | printList(Head); 117 | printf("link list after deletion of node having value %d\n", removeNode(Head,0)); 118 | printList(Head); 119 | return 0; 120 | } -------------------------------------------------------------------------------- /LinkedList/circularLinkedList/circularLinkListIterative.c: -------------------------------------------------------------------------------- 1 | /* 2 | Author : Fakhra najm 3 | operations on singly circular linkedList 4 | 1. create 5 | 2. display 6 | 3. find length 7 | 4. insert 8 | 5. delete 9 | */ 10 | 11 | 12 | #include 13 | #include 14 | 15 | struct Node{ 16 | int data; 17 | struct Node * next; 18 | }*Head; 19 | 20 | /* 21 | * creates the circular node for a linkedList 22 | * @param value to be inserted into the node 23 | * @return node pointer to the created node 24 | */ 25 | 26 | struct Node * createCircularNode(int value){ 27 | struct Node * node = (struct Node *)malloc(sizeof(struct Node)); 28 | node->data = value; 29 | node->next = node; 30 | return node; 31 | } 32 | 33 | /* 34 | * creates the circular LinkedList 35 | * @param values from which linkedList is to be created 36 | * @param length of the given list of values 37 | */ 38 | 39 | void createLinkList(int values[], int length){ 40 | struct Node *last, *current; 41 | Head = createCircularNode(values[0]); 42 | last = Head; 43 | for (int i = 1; i < length; ++i) 44 | { 45 | current = createCircularNode(values[i]); 46 | last->next = current; 47 | current->next = Head; 48 | last = current; 49 | } 50 | } 51 | 52 | /* 53 | * calculates the length of the CircularlinkedList 54 | * @param head pointer to the Head of the circularLinkedList 55 | * @return the length of the circularLinkedList 56 | */ 57 | 58 | int calculateLength(struct Node * head){ 59 | int length = 0 ; 60 | do{ 61 | length++; 62 | head = head->next; 63 | }while(head != Head); 64 | return length; 65 | } 66 | 67 | /* 68 | * prints the values of circular LinkedList 69 | * @param head pointer to the Head of the linkedList 70 | */ 71 | 72 | void PrintList(struct Node * head){ 73 | head = Head; 74 | do{ 75 | printf("%d ", head->data); 76 | head = head->next; 77 | }while(head != Head); 78 | printf("\n"); 79 | } 80 | 81 | /** 82 | * inserts a new node in the linkedList 83 | * @param pointer to the Head of the circular LinkedList 84 | * @param index where new node is to be inserted 85 | * @param value to be inserted inside the new node 86 | */ 87 | 88 | void insertValue(struct Node * head, int index, int value){ 89 | struct Node * node = createCircularNode(value); 90 | if(index < 0 || index > calculateLength(Head)) 91 | return; 92 | if(index == 0){ 93 | if(head == NULL){ 94 | head = node; 95 | } 96 | else{ 97 | while(head->next != Head) 98 | head = head->next; 99 | node->next = Head; 100 | head->next = node; 101 | Head = node; 102 | } 103 | } 104 | else{ 105 | for (int i = 0; i < index-1; i++) 106 | head = head->next; 107 | node->next = head->next; 108 | head->next = node; 109 | } 110 | } 111 | 112 | /* 113 | * removes the node from the circular LinkedList 114 | * @param current pointer to the Head of the linkedList 115 | * @param Prev_node pointer to the previous of the current node pointer 116 | * @param index from which node is to be deleted 117 | * @return the value of the deleted node. 118 | */ 119 | 120 | int removeNode(struct Node * current, struct Node * prev_node, int index){ 121 | int value = -1; 122 | if(index > calculateLength(Head) || index < 0) 123 | return -1; 124 | if(index == 0){ 125 | while(current->next != Head) 126 | current = current->next; 127 | current->next = Head->next; 128 | value = Head->data; 129 | free(Head); 130 | Head = current->next; 131 | } 132 | else{ 133 | for (int i = 0; i < index; ++i){ 134 | prev_node = current; 135 | current = current->next; 136 | } 137 | prev_node->next = current->next; 138 | value = current->data; 139 | free(current); 140 | } 141 | return value; 142 | } 143 | 144 | int main(){ 145 | int values[] = {1, 2, 3, 4, 5}; 146 | createLinkList(values, 5); 147 | printf("original linkList:\n"); 148 | PrintList(Head); 149 | insertValue(Head, 0, 6); 150 | printf("The new linkList:\n"); 151 | PrintList(Head); 152 | printf("deleted value:%d\n",removeNode(Head, NULL, 0)); 153 | printf("LinkedList Restored\n"); 154 | PrintList(Head); 155 | return 0; 156 | } -------------------------------------------------------------------------------- /LinkedList/operationsOnLinkedList/checkSort.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | struct Node 5 | { 6 | int data; 7 | struct Node *next; 8 | }*head = NULL, *last = NULL; 9 | 10 | 11 | struct Node * createNode(int value) 12 | { 13 | struct Node *node = (struct Node *)malloc(sizeof(struct Node)); 14 | node->data = value; 15 | node->next = NULL; 16 | return node; 17 | } 18 | 19 | void createLinkList(int value) 20 | { 21 | struct Node *node = createNode(value); 22 | if(head == NULL) 23 | { 24 | head = last = node; 25 | } 26 | else 27 | { 28 | last->next = node; 29 | last = node; 30 | } 31 | } 32 | 33 | void ShowList(struct Node *head) 34 | { 35 | while(head != NULL) 36 | { 37 | printf("%d ", head->data); 38 | head = head->next; 39 | } 40 | } 41 | 42 | int CheckSort(struct Node *head) 43 | { 44 | int x = head->data; 45 | head = head->next; 46 | while(head != NULL){ 47 | if(head->data < x) 48 | return 0; 49 | x = head->data ; 50 | head = head->next; 51 | } 52 | return 1; 53 | } 54 | 55 | int main() 56 | { 57 | int nodes, value; 58 | printf("Enter number of nodes:\n"); 59 | scanf("%d", &nodes); 60 | 61 | printf("\nEnter all elements\n"); 62 | for (int i = 0; i < nodes; i++) 63 | { 64 | scanf("%d", &value); 65 | createLinkList(value); 66 | } 67 | 68 | ShowList(head); 69 | 70 | if(CheckSort(head)) 71 | printf("\nlist is sorted\n"); 72 | else 73 | printf("\nlist is not sorted\n"); 74 | 75 | return 0; 76 | } -------------------------------------------------------------------------------- /LinkedList/operationsOnLinkedList/concatLinkLists.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | struct Node 5 | { 6 | int data; 7 | struct Node * next; 8 | }*first = NULL , *second = NULL , *third = NULL; 9 | 10 | struct Node * createNode(int value) 11 | { 12 | struct Node * node = (struct Node *)malloc(sizeof(struct Node)); 13 | node->data = value; 14 | node->next = NULL; 15 | return node; 16 | } 17 | 18 | struct Node * createLinkList(int values[], int length) 19 | { 20 | first= createNode(values[0]); 21 | struct Node *current ,*last = first; 22 | for(int i = 1; i < length; i++){ 23 | current = createNode(values[i]); 24 | last->next = current; 25 | last = current; 26 | } 27 | } 28 | 29 | struct Node * createSecondList(int values[], int length) 30 | { 31 | second = createNode(values[0]); 32 | struct Node *current ,*last = second; 33 | for(int i = 1; i < length; i++){ 34 | current = createNode(values[i]); 35 | last->next = current; 36 | last = current; 37 | } 38 | } 39 | 40 | struct Node * joinTwoList(struct Node * head , struct Node * second) 41 | { 42 | third = first; 43 | while(first->next != NULL) 44 | { 45 | first = first->next; 46 | } 47 | 48 | first->next = second; 49 | return third; 50 | } 51 | 52 | void ShowList(struct Node * head) 53 | { 54 | while(head != NULL) 55 | { 56 | printf("%d ", head->data); 57 | head = head->next; 58 | } 59 | printf("\n"); 60 | } 61 | 62 | int main() 63 | { 64 | int values1[] = {2, 4, 6, 8, 10}; 65 | int values2[]= {1,3,5}; 66 | createLinkList(values1, 5); 67 | createSecondList(values2, 3); 68 | ShowList(first); 69 | ShowList(second); 70 | joinTwoList(first, second); 71 | ShowList(third); 72 | } -------------------------------------------------------------------------------- /LinkedList/operationsOnLinkedList/linkedList_delete.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | struct Node 5 | { 6 | int data; 7 | struct Node * next; 8 | }*head=NULL; 9 | 10 | struct Node * createNode(int value) 11 | { 12 | struct Node * node = (struct Node *)malloc(sizeof(struct Node)); 13 | node->data = value; 14 | node->next = NULL; 15 | return node; 16 | } 17 | 18 | void createLinkList(int values[], int length) 19 | { 20 | head = createNode(values[0]); 21 | struct Node *current, *last = head; 22 | for(int i = 1; i < length; i++){ 23 | current = createNode(values[i]); 24 | last->next = current; 25 | last = current; 26 | } 27 | } 28 | 29 | void PrintList(struct Node * head) 30 | { 31 | while(head){ 32 | printf("%d ", head->data); 33 | head = head->next; 34 | } 35 | } 36 | 37 | void removeHead() 38 | { 39 | struct Node * node = createNode(head->data); 40 | head = head->next; 41 | node = NULL; 42 | } 43 | 44 | void removeNode(struct Node *node, int value) 45 | { 46 | struct Node * prev_node = (struct Node *)malloc(sizeof(struct Node)); 47 | 48 | if(head->data == value) 49 | removeHead(); 50 | 51 | else{ 52 | while(node != NULL) 53 | { 54 | if(node->data != value) 55 | { 56 | prev_node = node ; 57 | node = node->next; 58 | } 59 | else 60 | { 61 | prev_node->next = node->next; 62 | node = NULL; 63 | } 64 | } 65 | } 66 | } 67 | 68 | 69 | int main() 70 | { 71 | int value; 72 | int values[] = {1, 4, 7, 5, 8}; 73 | createLinkList(values, 5); 74 | printf("The given link list is\n"); 75 | PrintList(head); 76 | printf("\nEnter the value for deletion:\n"); 77 | scanf("%d" , &value); 78 | removeNode(head ,value); 79 | printf("The new link list is as below\n"); 80 | PrintList(head); 81 | return 0; 82 | } -------------------------------------------------------------------------------- /LinkedList/operationsOnLinkedList/loopDetection.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | struct Node 5 | { 6 | int data; 7 | struct Node *next; 8 | }*Head = NULL; 9 | 10 | struct Node * createNode(int value) 11 | { 12 | struct Node *node = (struct Node *)malloc(sizeof(struct Node)); 13 | node->data = value; 14 | node->next = NULL; 15 | return node; 16 | } 17 | void CreateLinkList(int values[], int length) 18 | { 19 | Head = createNode(values[0]); 20 | struct Node * current, *last = Head; 21 | for (int i = 1; i < length; i++) { 22 | current = createNode(values[i]); 23 | last->next = current; 24 | last = current; 25 | } 26 | } 27 | 28 | void PrintList(struct Node *head) 29 | { 30 | while(head != NULL) 31 | { 32 | printf("%d ", head->data); 33 | head = head->next; 34 | } 35 | printf("\n"); 36 | } 37 | 38 | void CreateLoop(struct Node * head) 39 | { 40 | struct Node *first, *last; 41 | first = head->next; 42 | while(head->next ) 43 | { 44 | head = head->next; 45 | } 46 | last = head; 47 | last->next = first; 48 | } 49 | 50 | int detectLoop(struct Node *head ) 51 | { 52 | struct Node *current , *last; 53 | current = last = head; 54 | do{ 55 | current = current->next; 56 | last = last->next; 57 | last = last? last->next:last; 58 | }while(current && last && current != last); 59 | if(current == last){ 60 | return 1; 61 | } 62 | else{ 63 | return 0; 64 | } 65 | } 66 | 67 | int main() 68 | { 69 | int values[] = {1, 6, 4, 7, 8, 5, 3, 2, 9, 10}; 70 | CreateLinkList(values, 10); 71 | PrintList(Head); 72 | CreateLoop(Head); 73 | if(detectLoop(Head) == 1) 74 | { 75 | printf("loop detected!!"); 76 | } 77 | else{ 78 | printf("loop not detected!!"); 79 | } 80 | 81 | return 0; 82 | } -------------------------------------------------------------------------------- /LinkedList/operationsOnLinkedList/mergeTwoLinks.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | struct Node 5 | { 6 | int data; 7 | struct Node * next; 8 | }*first = NULL , *second = NULL , *third = NULL; 9 | 10 | struct Node * createNode(int value) 11 | { 12 | struct Node * node = (struct Node *)malloc(sizeof(struct Node)); 13 | node->data = value; 14 | node->next = NULL; 15 | return node; 16 | } 17 | 18 | struct Node * createFirstList(int values[], int length) 19 | { 20 | first= createNode(values[0]); 21 | struct Node *current ,*last = first; 22 | for(int i = 1; i < length; i++){ 23 | current = createNode(values[i]); 24 | last->next = current; 25 | last = current; 26 | } 27 | } 28 | 29 | struct Node * createSecondList(int values[], int length) 30 | { 31 | second = createNode(values[0]); 32 | struct Node *current ,*last = second; 33 | for(int i = 1; i < length; i++){ 34 | current = createNode(values[i]); 35 | last->next = current; 36 | last = current; 37 | } 38 | } 39 | 40 | void ShowList(struct Node * head) 41 | { 42 | while(head != NULL) 43 | { 44 | printf("%d ", head->data); 45 | head = head->next; 46 | } 47 | printf("\n"); 48 | } 49 | 50 | struct Node * mergeData(struct Node *first, struct Node *second) 51 | { 52 | struct Node *last = NULL; 53 | if(first->data > second->data){ 54 | third = last = second ; 55 | second = second->next; 56 | last->next = NULL; 57 | } 58 | else{ 59 | third = last = first; 60 | first = first->next; 61 | last->next = NULL; 62 | } 63 | while(first && second) 64 | { 65 | if(first->data > second->data){ 66 | last->next = second; 67 | last = second; 68 | second = second->next; 69 | last->next = NULL; 70 | } 71 | else{ 72 | last->next = first; 73 | last = first; 74 | first = first->next; 75 | last->next = NULL; 76 | } 77 | } 78 | if(first) 79 | last->next = first; 80 | else 81 | last->next = second; 82 | return third; 83 | } 84 | 85 | int main() 86 | { 87 | int values1[] = {2, 4, 6, 8, 10, 12, 14, 16, 18, 20}; 88 | int values2[] = {1, 3, 5, 7, 9, 11, 13, 15, 17, 19}; 89 | createFirstList(values1, 10); 90 | createSecondList(values2, 10); 91 | printf("First Link list:\n"); 92 | ShowList(first); 93 | printf("Second Link list:\n"); 94 | ShowList(second); 95 | mergeData(first, second); 96 | printf("after merge new Link list formed:\n"); 97 | ShowList(third); 98 | } -------------------------------------------------------------------------------- /LinkedList/operationsOnLinkedList/removingDuplicates.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | struct Node 5 | { 6 | int data; 7 | struct Node * next; 8 | }*head = NULL , *last = NULL ; 9 | 10 | struct Node * createNode(int value) 11 | { 12 | struct Node * node = (struct Node *)malloc(sizeof(struct Node)); 13 | node->data = value; 14 | node->next = NULL; 15 | return node; 16 | } 17 | 18 | void createLinkList(int value) 19 | { 20 | struct Node * node; 21 | node = createNode(value); 22 | if(head == NULL) 23 | { 24 | head = last = node ; 25 | } 26 | else 27 | { 28 | last->next = node ; 29 | last = node; 30 | } 31 | } 32 | 33 | void removeDuplicate(struct Node *head) 34 | { 35 | struct Node * current = head->next; 36 | while(current != NULL) 37 | { 38 | if(current->data != head->data ){ 39 | head = current; 40 | current = current->next; 41 | } 42 | else{ 43 | head->next = current->next; 44 | free(current); 45 | current = head->next; 46 | } 47 | } 48 | } 49 | 50 | void ShowList(struct Node * head) 51 | { 52 | while(head != NULL) 53 | { 54 | printf("%d ", head->data); 55 | head = head->next; 56 | } 57 | } 58 | 59 | int main() 60 | { 61 | int nodes,value; 62 | printf("Enter number of nodes :\n"); 63 | scanf("%d", &nodes); 64 | printf("enter all values of list\n"); 65 | for(int i = 0; i < nodes; i++) 66 | { 67 | scanf("%d", &value); 68 | createLinkList(value); 69 | } 70 | ShowList(head); 71 | removeDuplicate(head); 72 | printf("\n"); 73 | ShowList(head); 74 | 75 | return 0; 76 | } -------------------------------------------------------------------------------- /LinkedList/operationsOnLinkedList/reversingElements.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | struct Node 5 | { 6 | int data; 7 | struct Node * next; 8 | }*head = NULL , *last = NULL ; 9 | 10 | struct Node * createNode(int value) 11 | { 12 | struct Node * node = (struct Node *)malloc(sizeof(struct Node)); 13 | node->data = value; 14 | node->next = NULL; 15 | return node; 16 | } 17 | 18 | void createLinkList(int value) 19 | { 20 | struct Node * node; 21 | node = createNode(value); 22 | if(head == NULL) 23 | { 24 | head = last = node ; 25 | } 26 | else 27 | { 28 | last->next = node ; 29 | last = node; 30 | } 31 | } 32 | 33 | void ShowList(struct Node * head) 34 | { 35 | while(head != NULL) 36 | { 37 | printf("%d ", head->data); 38 | head = head->next; 39 | } 40 | } 41 | 42 | struct Node * reverseLinkList(struct Node *node, int nodes) 43 | { 44 | int i = 0; 45 | int *values = (int *)malloc(nodes*sizeof(int)); 46 | while(node != NULL) 47 | { 48 | values[i++] = node->data; 49 | node = node->next; 50 | } 51 | 52 | i--; node = head; 53 | while(node){ 54 | node->data = values[i--]; 55 | node = node->next; 56 | } 57 | 58 | return node; 59 | } 60 | 61 | int main() 62 | { 63 | int nodes,value; 64 | printf("Enter number of nodes :\n"); 65 | scanf("%d", &nodes); 66 | printf("enter all values of list\n"); 67 | for(int i = 0; i < nodes; i++) 68 | { 69 | scanf("%d", &value); 70 | createLinkList(value); 71 | } 72 | ShowList(head); 73 | reverseLinkList(head , nodes); 74 | printf("\n"); 75 | ShowList(head); 76 | return 0; 77 | } -------------------------------------------------------------------------------- /LinkedList/operationsOnLinkedList/reversingLinks.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | struct Node 5 | { 6 | int data; 7 | struct Node * next; 8 | }*head = NULL , *last = NULL ; 9 | 10 | struct Node * createNode(int value) 11 | { 12 | struct Node * node = (struct Node *)malloc(sizeof(struct Node)); 13 | node->data = value; 14 | node->next = NULL; 15 | return node; 16 | } 17 | 18 | void createLinkList(int value) 19 | { 20 | struct Node * node; 21 | node = createNode(value); 22 | if(head == NULL) 23 | { 24 | head = last = node ; 25 | } 26 | else 27 | { 28 | last->next = node ; 29 | last = node; 30 | } 31 | } 32 | 33 | void ShowList(struct Node * head) 34 | { 35 | while(head != NULL) 36 | { 37 | printf("%d ", head->data); 38 | head = head->next; 39 | } 40 | } 41 | 42 | 43 | void reverseLinkList(struct Node *node) 44 | { 45 | struct Node * current = NULL , * prev_node = NULL; 46 | while(node != NULL){ 47 | prev_node = current; 48 | current = node; 49 | node = node->next; 50 | current->next = prev_node; 51 | } 52 | head = current; 53 | 54 | } 55 | 56 | 57 | int main() 58 | { 59 | int nodes,value; 60 | printf("Enter number of nodes :\n"); 61 | scanf("%d", &nodes); 62 | printf("enter all values of list\n"); 63 | for(int i = 0; i < nodes; i++) 64 | { 65 | scanf("%d", &value); 66 | createLinkList(value); 67 | } 68 | ShowList(head); 69 | reverseLinkList(head); 70 | printf("\n"); 71 | ShowList(head); 72 | return 0; 73 | } -------------------------------------------------------------------------------- /LinkedList/studentChallenge/findMidInSinglyLL.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | struct Node{ 5 | struct Node * prev; 6 | int data; 7 | struct Node * next; 8 | }*head; 9 | 10 | struct Node * createNode(int value){ 11 | struct Node * node = (struct Node *)malloc(sizeof(struct Node)); 12 | node->data = value; 13 | node->next = NULL; 14 | return node; 15 | } 16 | 17 | void createLinkList(int values[], int length){ 18 | head = createNode(values[0]); 19 | struct Node * current, *last = head; 20 | for (int i = 1; i < length; ++i){ 21 | current = createNode(values[i]); 22 | last->next = current; 23 | last = current; 24 | } 25 | } 26 | 27 | int findMid(struct Node * head, struct Node *tail){ 28 | while(head){ 29 | head = head->next; 30 | if(head) 31 | head = head->next; 32 | if(head) 33 | tail = tail->next; 34 | } 35 | return tail->data; 36 | } 37 | 38 | void printList(struct Node * head){ 39 | while(head){ 40 | printf("%d ", head->data ); 41 | head = head->next; 42 | } 43 | printf("\n"); 44 | } 45 | 46 | int main(){ 47 | int values[5]; 48 | printf("Number of nodes are : 5\n"); 49 | printf("Enter all elements to be inserted in nodes\n"); 50 | for (int i = 0; i < 5; ++i) 51 | scanf("%d", &values[i] ); 52 | createLinkList(values, 5); 53 | printf("created LinkList is\n"); 54 | printList(head); 55 | printf("Middle node value = %d\n",findMid(head,head) ); 56 | return 0; 57 | } -------------------------------------------------------------------------------- /LinkedList/studentChallenge/middleElement.c: -------------------------------------------------------------------------------- 1 | /* 2 | finding middle element of a linked list 3 | *Here i'm taking circular doubly linkList 4 | *i am taking two pointers one is pointing on head and another on the previous to the head 5 | *then moving head pointer to next and last pointer to previous of it 6 | *the idea is that when head pointer becomes equal to last pointer then it is the middle node 7 | *when head pointer and last pointer are side by side then there are even number of nodes and hence no middle node 8 | */ 9 | 10 | #include 11 | #include 12 | 13 | struct Node{ 14 | struct Node * prev; 15 | int data; 16 | struct Node * next; 17 | }*head; 18 | 19 | struct Node * createNode(int value){ 20 | struct Node * node = (struct Node *)malloc(sizeof(struct Node)); 21 | node->prev = node; 22 | node->data = value; 23 | node->next = node; 24 | return node; 25 | } 26 | 27 | void createLinkList(int values[], int length){ 28 | head = createNode(values[0]); 29 | struct Node * current, *last = head; 30 | for (int i = 1; i < length; ++i){ 31 | current = createNode(values[i]); 32 | last->next = current; 33 | current->next = head; 34 | current->prev = last; 35 | head->prev = current; 36 | last = current; 37 | } 38 | } 39 | 40 | int findMid(struct Node * Head, struct Node *last){ 41 | do{ 42 | Head = Head->next; 43 | last = last->prev; 44 | if(Head == last) 45 | return Head->data; 46 | }while(Head != head); 47 | return -1; 48 | } 49 | 50 | void printList(struct Node * node){ 51 | do{ 52 | printf("%d ", node->data ); 53 | node = node->next; 54 | }while(node != head); 55 | printf("\n"); 56 | } 57 | 58 | int main(){ 59 | int nodes; 60 | printf("Enter number of nodes:\n"); 61 | scanf("%d", &nodes); 62 | int *values = (int *)malloc(nodes*sizeof(int)); 63 | printf("Enter all elements to be inserted in nodes\n"); 64 | for (int i = 0; i < nodes; ++i) 65 | scanf("%d", &values[i] ); 66 | createLinkList(values, nodes); 67 | printf("created LinkList is\n"); 68 | printList(head); 69 | if(findMid(head, head->prev) != -1) 70 | printf("Middle element:%d ",findMid(head, head->prev) ); 71 | else 72 | printf("Number of nodes is even i.e. no middle element\n"); 73 | return 0; 74 | } -------------------------------------------------------------------------------- /LinkedList/studentChallenge/polynomial.c: -------------------------------------------------------------------------------- 1 | /** 2 | Author : Fakhra Najm 3 | email : fnajm09@gmail.com 4 | polynomial via linkedList 5 | * 1. create. 6 | * 2. evaluate. 7 | * 3. display. 8 | */ 9 | 10 | #include 11 | #include 12 | #include 13 | 14 | struct polynomial 15 | { 16 | int coeff; 17 | int exponent; 18 | struct polynomial *next_term; 19 | }*head_term = NULL, *last = NULL; 20 | 21 | struct polynomial *createNode(int coefficient, int exp){ 22 | struct polynomial *node = (struct polynomial*)malloc(sizeof(struct polynomial)); 23 | if(head_term == NULL){ 24 | head_term = (struct polynomial *)malloc(sizeof(struct polynomial)); 25 | head_term->coeff = coefficient; 26 | head_term->exponent = exp; 27 | head_term->next_term = NULL; 28 | last = head_term; 29 | return head_term; 30 | } 31 | else{ 32 | last->next_term = node; 33 | node->coeff = coefficient; 34 | node->exponent = exp; 35 | node->next_term = NULL; 36 | last = node; 37 | } 38 | return node; 39 | } 40 | 41 | void createTerm(struct polynomial *head_term){ 42 | int terms, coefficient, exp; 43 | printf("Enter number of terms\n"); 44 | scanf("%d", &terms); 45 | printf("enter all terms details\n"); 46 | for (int i = 0; i < terms; ++i){ 47 | scanf("%d%d", &coefficient, &exp); 48 | createNode(coefficient, exp); 49 | } 50 | } 51 | 52 | int evaluateTerms(struct polynomial * head_term, int var_value){ 53 | int result = 0; 54 | while(head_term){ 55 | result = result + (head_term->coeff)*pow(var_value, head_term->exponent); 56 | head_term = head_term->next_term; 57 | } 58 | return result; 59 | } 60 | 61 | void printTerms(struct polynomial *head_term){ 62 | while(head_term){ 63 | printf("%dx%d+", head_term->coeff, head_term->exponent ); 64 | head_term = head_term->next_term; 65 | } 66 | printf("\n"); 67 | } 68 | 69 | int main(){ 70 | int var_value; 71 | createTerm(head_term); 72 | printTerms(head_term); 73 | printf("Enter variable value:\n"); 74 | scanf("%d", &var_value); 75 | printf("Result : %d\n",evaluateTerms(head_term, var_value) ); 76 | return 0; 77 | } -------------------------------------------------------------------------------- /LinkedList/studentChallenge/sparseMatrix.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | struct Node{ 5 | int column; 6 | int value; 7 | struct Node *next; 8 | }*head = NULL, *last = NULL; 9 | 10 | // returns a linked list node 11 | struct Node * createNode(int col, int val){ 12 | // create a linked list node and store its location into a pointer 13 | struct Node * node = (struct Node *)malloc(sizeof(struct Node)); 14 | 15 | // assign values to the using pointer of the node 16 | node->column = col; 17 | node->value = val; 18 | node->next = NULL; 19 | // return created node's pointer 20 | return node; 21 | } 22 | 23 | // inserts values add the end of linked list 24 | void insertNode(int col, int val){ 25 | // store pointer of the created node in head if head is null 26 | if(head == NULL){ 27 | head = last = createNode(col, val); 28 | } 29 | else { 30 | // create a new node and store its pointer 31 | struct Node * node = createNode(col, val); 32 | // make last node point to newly created node 33 | last->next = node; 34 | // set newly created node as last node 35 | last = node; 36 | } 37 | } 38 | 39 | struct Node * createSparse(int row) { 40 | int col,val; 41 | 42 | // make an array of size equal to row size, which will hold pointer to linked list 43 | struct Node *rows = (struct Node *)malloc(row * sizeof(struct Node *)); 44 | 45 | // loop for all elements 46 | for(int i = 0 ; i < row ; i++) { 47 | // take the size of column 48 | printf("Enter number of columns at row: %d\n", i); 49 | scanf("%d", &col); 50 | /* 51 | scan each element at each row 52 | this loop will end when all values of a row has been read 53 | for each row a new linked list will be made 54 | when a linked list becomes complete, the of that list will be 55 | stored to the row array. 56 | */ 57 | for (int j = 0; j < col; ++j) { 58 | printf("Enter value"); 59 | // take the new value 60 | scanf("%d", &val); 61 | // insert into the linked list 62 | // j will be the column number 63 | insertNode(j,val); 64 | } 65 | /* 66 | rows is array of struct Node*, so each box of array contains 67 | val, col and next 68 | as next should point to the head of the linked list 69 | so we store the head of the created linked list 70 | val and col will be blank 71 | array just hold the head of the linked list 72 | */ 73 | rows[i].next = head; 74 | head = NULL; // reset value to null, to create next linked list 75 | last = NULL; // reset value to null, to create next linked list 76 | } 77 | return rows; 78 | } 79 | 80 | // print linked list 81 | void printll(struct Node* head) { 82 | while(head != NULL) { 83 | printf("%d", head ->value); 84 | head = head -> next; 85 | } 86 | } 87 | 88 | // iterate over the array and find the head of each linked list 89 | void printsparse(struct Node *sparse, int row) { 90 | for(int i = 0; i < row; i++) { 91 | printll(sparse[i].next); 92 | printf("\n"); 93 | } 94 | } 95 | 96 | int main() { 97 | int row; 98 | // take number of rows 99 | printf("Enter number of rows\n"); 100 | scanf("%d",&row); 101 | struct Node * sparse = createSparse(row); 102 | printsparse(sparse, row); 103 | return 0; 104 | } -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | CC := gcc 2 | 3 | CFLAGS := -g -Wall 4 | LDFLAGS := -lm 5 | 6 | SRCS := $(shell find . -name "*.c") 7 | OBJS := $(SRCS:%.c=%.app) 8 | 9 | all: $(OBJS) 10 | 11 | %.app: %.c 12 | $(CC) $(CFLAGS) $< -o $@ $(LDFLAGS) 13 | 14 | clean: 15 | rm -rf $(OBJS) 16 | 17 | -------------------------------------------------------------------------------- /Matrices/Lower-triangular-matrix/column_major_method.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | struct Matrix { 5 | int *A; 6 | int n; 7 | }; 8 | 9 | //set function will set the non-zero elements in the single dimensional array from the given matrix 10 | void set(struct Matrix *m,int i,int j,int x){ 11 | if(i>=j) 12 | //copying non-zero elements from the lower triangular matrix column by column in the created single dimensional array 13 | m->A[(m->n*(j-1))+((j-1)*(j-2)/2)+(i-j)]=x; 14 | } 15 | 16 | //retreiving the data from the single dimensional array if index of row is greater than or equal to column index otherwise ,it will return zero 17 | int get(struct Matrix m,int i,int j){ 18 | if(i>=j) 19 | return m.A[(m.n*(j-1))+((j-1)*(j-2)/2)+(i-j)]; 20 | else 21 | return 0; 22 | } 23 | 24 | //prints the matrix on the screen with the help of single dimensional array in heap 25 | //if the row index is greater than or equal to column index then it will return elements from created 1D array,otherwise it will print zero 26 | void Display(struct Matrix m){ 27 | int i,j; 28 | for(i=1;i<=m.n;i++){ 29 | for(j=1;j<=m.n;j++){ 30 | if(i>=j) 31 | printf("%d ",m.A[(m.n*(j-1))+((j-1)*(j-2)/2)+(i-j)]); 32 | else 33 | printf("0 "); 34 | } 35 | 36 | printf("\n"); 37 | } 38 | } 39 | 40 | 41 | int main(){ 42 | struct Matrix m; 43 | int i,j,x; 44 | 45 | printf("Enter the dimension of the matrix:"); 46 | scanf("%d",&m.n); 47 | 48 | //creating a single dimensional array dynamically to store non-zero elements of the matrix 49 | 50 | m.A=(int *)malloc(m.n*(m.n-1)/2*sizeof(int)); 51 | 52 | printf("Enter all elements\n"); 53 | 54 | for(i=1;i<=m.n;i++){ 55 | for(j=1;j<=m.n;j++){ 56 | scanf("%d",&x); 57 | set(&m,i,j,x); 58 | } 59 | } 60 | printf("\n\n"); 61 | Display(m); 62 | return 0; 63 | } 64 | -------------------------------------------------------------------------------- /Matrices/Lower-triangular-matrix/lower_triangular_matrix.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | //if column index is lesser than row index then elements are zero 5 | //if row is greater than or equal to column then that is the non zero part of lower triangular matrix 6 | 7 | int Display(int S[5][5],int n){ 8 | int i,j; 9 | 10 | for(i=0;i=j) 13 | printf("%d ",S[i][j]); 14 | else printf("0 "); 15 | 16 | } 17 | printf("\n"); 18 | } 19 | } 20 | 21 | int main() 22 | { 23 | int A[5][5]={1,0,0,0,0,1,2,0,0,0,1,2,3,0,0,1,2,3,4,0,1,2,3,4,5}; 24 | int n,i,j; 25 | printf("Enter dimension of the square matrix: "); 26 | scanf("%d",&n); 27 | printf("The diagonal elements are:\n"); 28 | for(i=0;i 2 | #include 3 | 4 | struct Matrices { 5 | int *A; 6 | int n; 7 | }; 8 | 9 | //printing the entire lower triangular matrix with the help of 1D matrix 10 | //if row index is greater than or equal to column index, it prints corresponding index elememt from the created array,otherwise it will ptint zero 11 | 12 | void Display(struct Matrices m){ 13 | int i,j; 14 | for(i=1;i<=m.n;i++){ 15 | for(j=1;j<=m.n;j++){ 16 | if(i>=j) 17 | printf("%d ",m.A[i*(i-1)/2+j-1] ); 18 | else 19 | printf("0 "); 20 | } 21 | printf("\n"); 22 | } 23 | 24 | } 25 | 26 | //setting the non-zero elements in the one dimensional array 27 | 28 | void set(struct Matrices *m,int i,int j,int x){ 29 | //non-zero elements is only present there where row index is greater than or equal to column index 30 | if(i>=j) 31 | //setting the non-zero elements in the created single dimensional array row by row 32 | m->A[i*(i-1)/2+j-1]=x; 33 | } 34 | 35 | //returning the elments from the matrix with the help of one dimensional array 36 | int Get(struct Matrices m,int i,int j){ 37 | //Check for non-zero elements 38 | if(i>=j) 39 | return m.A[i*(i-1)/2+j-1]; 40 | else 41 | return 0; 42 | } 43 | 44 | int main(){ 45 | struct Matrices m; 46 | int i,j,x; 47 | printf("Enter dimmension:"); 48 | scanf("%d",&m.n); 49 | 50 | //creating a single dimensional array dynamically to store all non zero elements from the matrix row by row 51 | //the size of the array is equal to the total number of non-zero elements in the matrix 52 | 53 | m.A=(int *)malloc(m.n*(m.n+1)/2*sizeof(int)); 54 | 55 | for(i=1;i<=m.n;i++){ 56 | for(j=1;j<=m.n;j++){ 57 | scanf("%d",&x); 58 | set(&m,i,j,x); 59 | } 60 | } 61 | printf("\n\n"); 62 | 63 | Display(m); 64 | 65 | return 0; 66 | } 67 | -------------------------------------------------------------------------------- /Matrices/TriDiagonal_matrix.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | //array which will store the upper, lower and main diagonal elements of the triDiagonal Matrix 5 | 6 | struct Matrix{ 7 | int *A; 8 | int n; 9 | }; 10 | 11 | 12 | //main diagonal:the difference of indices is zero in every cases 13 | //upper diagonal:the difference of indices is -1 in every cases 14 | //lower Diagonal:the difference of indices is 1 in every cases 15 | //setting all the non-zero elements in 1D array diagonal by diagonal 16 | 17 | void Set(struct Matrix *m,int i,int j,int x) 18 | { 19 | if(i-j==0) 20 | m->A[m->n-1+i-1]=x; 21 | else if(i-j==1) 22 | m->A[i-2]=x; 23 | else if(i-j==-1) 24 | m->A[2*m->n-1+i-1]=x; 25 | } 26 | 27 | // Returns diagonal elements 28 | 29 | int Get(struct Matrix m,int i,int j) 30 | { 31 | if(i-j==0) 32 | return m.A[m.n-1+i-1]; 33 | else if(i-j==1) 34 | return m.A[i-2]; 35 | else if(i-j==-1) 36 | return m.A[2*m.n-1+i-1]; 37 | else 38 | return 0; 39 | } 40 | 41 | //prints the triDiagonal Matrix 42 | 43 | void Display(struct Matrix m) 44 | { 45 | int i,j; 46 | 47 | for(i=1;i<=m.n;i++){ 48 | for(j=1;j<=m.n;j++){ 49 | if(i-j==0) 50 | printf("%d ",m.A[m.n-1+i-1] ); 51 | else if(i-j==1) 52 | printf("%d ",m.A[i-2] ); 53 | else if(i-j==-1) 54 | printf("%d ",m.A[2*m.n-1+i-1]); 55 | else 56 | printf("0 "); 57 | } 58 | printf("\n"); 59 | } 60 | } 61 | 62 | int main() 63 | { 64 | int i,j,x; 65 | 66 | struct Matrix m; 67 | 68 | m.A=(int *)malloc((3*m.n-2)*sizeof(int)); 69 | 70 | printf("Enter dimension of the Matrix:"); 71 | scanf("%d",&m.n); 72 | 73 | printf("Enter the elements of the Matrix:"); 74 | 75 | for(i=1;i<=m.n;i++){ 76 | for(j=1;j<=m.n;j++){ 77 | scanf("%d",&x); 78 | Set(&m,i,j,x); 79 | } 80 | } 81 | printf("\n\n"); 82 | 83 | Display(m); 84 | 85 | printf(" \nAll the diagonal elements are\n"); 86 | for(i=1;i<=m.n;i++){ 87 | for(j=1;j<=m.n;j++){ 88 | if(i-j==0) 89 | printf("%d ",Get(m,i,j) ); 90 | } 91 | printf("\n"); 92 | } 93 | 94 | printf(" \nAll the upper diagonal elements are\n"); 95 | 96 | for(i=1;i<=m.n;i++){ 97 | for(j=1;j<=m.n;j++){ 98 | if(i-j==-1) 99 | printf("%d \n",Get(m,i,j) ); 100 | } 101 | } 102 | 103 | printf(" \nAll the lower diagonal elements are\n"); 104 | 105 | for(i=1;i<=m.n;i++){ 106 | for(j=1;j<=m.n;j++){ 107 | if(i-j==1) 108 | printf("%d \n",Get(m,i,j) ); 109 | } 110 | } 111 | 112 | 113 | return 0; 114 | } 115 | -------------------------------------------------------------------------------- /Matrices/Upper-triangular-matrix/column_major_mapping.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | struct Matrices { 5 | int *A; 6 | int n; 7 | }; 8 | 9 | /* 10 | * In upper triangular matrix lower triangular elememts are all zeroes 11 | * In upper triangular matrix row index is always less than or equal to column index 12 | */ 13 | 14 | void Display(struct Matrices m){ 15 | int i,j; 16 | for(i=1;i<=m.n;i++){ 17 | for(j=1;j<=m.n;j++){ 18 | if(i<=j) 19 | printf("%d ",m.A[j*(j-1)/2+(i-1)] ); 20 | else 21 | printf("0 "); 22 | } 23 | printf("\n"); 24 | } 25 | 26 | } 27 | 28 | //Sets the elements on the matrix if index of column is greater than the row index otherwise,the element is zero 29 | 30 | void set(struct Matrices *m,int i,int j,int x){ 31 | if(i<=j) 32 | 33 | //copying elements column by column from matrix in the single dimensional created array 34 | 35 | m->A[j*(j-1)/2+(i-1)]=x; 36 | } 37 | 38 | //if the requested index for column is greater than requested index for row then the get function will return data from single dimensional created array 39 | //otherwise it will return zero as in upper triangular matrix lower triangular part is always zero 40 | 41 | int Get(struct Matrices m,int i,int j){ 42 | if(i<=j) 43 | return m.A[j*(j-1)/2+(i-1)]; 44 | else 45 | return 0; 46 | } 47 | 48 | int main(){ 49 | struct Matrices m; 50 | int i,j,x; 51 | printf("Enter dimmension:"); 52 | scanf("%d",&m.n); 53 | 54 | //we are meant to store only non zero elements in a 55 | //single dimensional array 56 | 57 | m.A=(int *)malloc(m.n*(m.n+1)/2*sizeof(int)); 58 | 59 | for(i=1;i<=m.n;i++){ 60 | for(j=1;j<=m.n;j++){ 61 | scanf("%d",&x); 62 | set(&m,i,j,x); 63 | } 64 | } 65 | printf("\n\n"); 66 | 67 | Display(m); 68 | 69 | return 0; 70 | } 71 | -------------------------------------------------------------------------------- /Matrices/Upper-triangular-matrix/row_major_mapping.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | struct Matrices { 5 | int *A; 6 | int n; 7 | }; 8 | 9 | //display function will only display the elements of created single dimensional array when 10 | //the column index is greater than or equal to row index,otherwise it will return 0 11 | 12 | void Display(struct Matrices m){ 13 | int i,j; 14 | for(i=1;i<=m.n;i++){ 15 | for(j=1;j<=m.n;j++){ 16 | if(i<=j) 17 | printf("%d ",m.A[m.n*(i-1)-(i-1)*(i-2)/2+(j-1)] ); 18 | else 19 | printf("0 "); 20 | } 21 | printf("\n"); 22 | } 23 | 24 | } 25 | 26 | //the set function will only take datas which is non zero in the matrix that is for index of column must be 27 | //greater than or equal to row index 28 | 29 | void set(struct Matrices *m,int i,int j,int x){ 30 | if(i<=j) 31 | 32 | //copying elements row by row in the array from the matrix 33 | 34 | m->A[(i-1)*m->n-(i-1)*(i-2)/2+(j-1)]=x; 35 | } 36 | 37 | 38 | //get function will retrieve elements from created single dimensional array if 39 | //column index is greater than or equal to row index ,otherwise it will return zero 40 | int Get(struct Matrices m,int i,int j){ 41 | if(i<=j) 42 | return m.A[(i-1)*m.n-(i-1)*(i-2)/2+(j-1)]; 43 | else 44 | return 0; 45 | } 46 | 47 | int main(){ 48 | struct Matrices m; 49 | int i,j,x; 50 | printf("Enter dimmension:"); 51 | scanf("%d",&m.n); 52 | 53 | //only need to store non-zero elements from the matrix as all other elements are going to be zero 54 | //creating array dynamically of size p = total number of non zero elements 55 | 56 | m.A=(int *)malloc(m.n*(m.n+1)/2*sizeof(int)); 57 | 58 | for(i=1;i<=m.n;i++){ 59 | for(j=1;j<=m.n;j++){ 60 | scanf("%d",&x); 61 | set(&m,i,j,x); 62 | } 63 | } 64 | printf("\n\n"); 65 | 66 | Display(m); 67 | 68 | return 0; 69 | } 70 | -------------------------------------------------------------------------------- /Matrices/diagonal_matrix.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | //creating a class of one dimensional array to store all the diagonal elements of any square diagonal matrix 4 | struct Matrix 5 | { 6 | int A[10]; 7 | int n; 8 | }; 9 | 10 | //set is to insert the diagonal elements inside the matrix 11 | void Set(struct Matrix *m,int i,int j,int x){ 12 | if(i==j) 13 | m->A[i-1]=x; 14 | } 15 | 16 | //Retrieves an element from the matrix at any index 17 | int Get(struct Matrix m,int i,int j){ 18 | if(i==j) 19 | printf("%d\n",m.A[i-1]); 20 | else return 0; 21 | } 22 | 23 | //Prints all the elements of the square matrix row by row 24 | void Display(struct Matrix m){ 25 | int i,j; 26 | for(i=0;i 2 | using namespace std; 3 | 4 | class Matrix{ 5 | protected: 6 | int row,col; 7 | Matrix(int row, int col){ 8 | this -> row = row; 9 | this -> col = col; 10 | } 11 | }; 12 | 13 | class Diagonal : Matrix{ 14 | private: 15 | int *diagonal_values; 16 | public: 17 | Diagonal(int row, int col, int elements[]) : Matrix(row, col){ 18 | diagonal_values = new int[row]; 19 | for(int index = 1; index <= row; ++index) 20 | diagonal_values[index] = elements[index]; 21 | } 22 | void printMatrix(); 23 | }; 24 | 25 | class Symmetric : Matrix{ 26 | private : 27 | int * elements; 28 | public: 29 | Symmetric(int dimension, int values[]) : Matrix(dimension, dimension){ 30 | elements = new int[dimension]; 31 | for(int i = 1; i <= row; ++i){ 32 | for(int j = 1; j <= i + 1; ++j){ 33 | if(i <= j) { 34 | elements[row*(i-1) - ((i-1)*(i-2))/2 + j -1 ] = values[i]; 35 | } 36 | else{ 37 | elements[row*(j-1) - ((j-1)*(j-2))/2 + i -1] = values[i]; 38 | } 39 | } 40 | } 41 | } 42 | void printMatrix(); 43 | }; 44 | 45 | void Diagonal :: printMatrix(){ 46 | for(int i = 1; i <= this -> row; ++i ){ 47 | for(int j = 1; j <= this -> col; ++j){ 48 | if(i == j) cout << this -> diagonal_values[i] << " "; 49 | else cout << "0 "; 50 | } 51 | cout << endl; 52 | } 53 | } 54 | 55 | void Symmetric :: printMatrix(){ 56 | for(int i = 1; i <= row; ++i){ 57 | for(int j = 1; j <= col; ++j){ 58 | if(i <= j){ 59 | cout << elements[row*(i-1) - ((i-1)*(i-2))/2 + j-1] << " " ; 60 | } 61 | else{ 62 | cout << elements[row*(j-1) - ((j-1)*(j-2))/2 + i - 1 ] << " " ; 63 | } 64 | } 65 | cout << endl; 66 | } 67 | } 68 | 69 | 70 | int main(){ 71 | int arr[3] = {1,1,1}; 72 | Diagonal matrix = Diagonal(3, 3, arr); 73 | matrix.printMatrix(); 74 | 75 | int array[6] = {1,2,3,4,5}; 76 | cout << endl; 77 | Symmetric sym = Symmetric(3,array); 78 | sym.printMatrix(); 79 | 80 | return 0; 81 | } -------------------------------------------------------------------------------- /Matrices/polynomial_addition.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | /* 5 | * the polynomial representation can be done with knowing coefficient ,exponent and the number of terms that polynomial possess 6 | */ 7 | 8 | struct Term{ 9 | int coeff; 10 | int exponent; 11 | }; 12 | 13 | /* 14 | * @class Polynomial 15 | * @terms total number of terms in polynomial 16 | * @t points to the array of Terms 17 | */ 18 | 19 | struct Polynomial 20 | { 21 | int terms; 22 | struct Term *t; 23 | 24 | }; 25 | 26 | void Create_polynomial(struct Polynomial *p){ 27 | int i,j; 28 | printf("Enter the total number of terms in Polynomial"); 29 | scanf("%d",&p->terms); 30 | 31 | /*creating the array of object Term which contains all the cofficient corresponding to their exponent row by row*/ 32 | 33 | p->t=(struct Term *)malloc(p->terms*sizeof(struct Term)); 34 | 35 | printf("Enter all terms of Polynomial\n"); 36 | 37 | for(i=0;iterms;i++){ 38 | printf("term %d",i+1 ); 39 | scanf("%d%d",&p->t[i].coeff,&p->t[i].exponent); 40 | } 41 | 42 | } 43 | 44 | /*Prints the polynomial on the screen by retrieving data through the array */ 45 | 46 | void Display(struct Polynomial p) 47 | { 48 | int i; 49 | for(i=0;it=(struct Term *)malloc(p1->terms+p2->terms*sizeof(struct Term)); 80 | 81 | while(iterms && jterms){ 82 | if(p1->t[i].exponent >p2->t[j].exponent ) 83 | result->t[k++]=p1->t[i++]; 84 | else if(p1->t[i].exponent t[j].exponent ) 85 | result->t[k++]=p2->t[j++]; 86 | else{ 87 | result->t[k]=p1->t[i]; 88 | result->t[k++].coeff=p1->t[i++].coeff+p2->t[j++].coeff; 89 | } 90 | } 91 | 92 | for(;iterms;i++) 93 | result->t[k++]=p1->t[i++]; 94 | for(;jterms;j++) 95 | result->t[k++]=p2->t[j++]; 96 | 97 | result->terms=k; 98 | 99 | return result; 100 | 101 | } 102 | 103 | 104 | 105 | int main(){ 106 | struct Polynomial p1,p2,*p3; 107 | Create_polynomial(&p1); 108 | Create_polynomial(&p2); 109 | Display(p1); 110 | printf("\n"); 111 | Display(p2); 112 | printf("\n"); 113 | p3=Add(&p1,&p2); 114 | printf("\n"); 115 | Display(*p3); 116 | 117 | return 0; 118 | } 119 | -------------------------------------------------------------------------------- /Matrices/sparse_matrix.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Topic : Sparse Matrix 3 | * very few Non zero elements is present in such matrix 4 | * Store only nonzero elements and optimize space 5 | * Two methods : 6 | 1. Three column representation/ Co-ordinate List Representation 7 | 2. Compressed Sparse Row 8 | * Operations : 9 | 1. Create => Compressed Sparse Row Representation 10 | 2. Add => Co-ordinate List Representation 11 | */ 12 | 13 | #include 14 | using namespace std; 15 | 16 | class Elements{ 17 | public : 18 | int i, j, val; 19 | }; 20 | 21 | class Sparse { 22 | private: 23 | int nonzero_elements; 24 | int row; 25 | int col; 26 | Elements * details; 27 | public: 28 | 29 | Sparse(){ 30 | 31 | cout << "Enter Dimension m x n : " << endl; 32 | cin >> this -> row >> this -> col; 33 | 34 | cout << "Enter number of nonzero elements :" << endl; 35 | cin >> this -> nonzero_elements; 36 | 37 | this -> details = new Elements[this -> nonzero_elements]; 38 | 39 | for(int elements = 0; elements < this -> nonzero_elements; ++elements){ 40 | 41 | cout << "Enter row index i :" << endl; 42 | cin >> details[elements].i; 43 | 44 | cout << "Enter column index j : " << endl; 45 | cin >> details[elements].j; 46 | 47 | cout << "Enter value of M[i][j] : " << endl; 48 | cin >> details[elements].val; 49 | } 50 | 51 | } 52 | 53 | void print(); 54 | }; 55 | 56 | 57 | void Sparse :: print(){ 58 | int index = 0; 59 | for(int i = 1; i <= this -> row; ++i){ 60 | for(int j = 1; j <= this -> col; ++j){ 61 | if(this -> details[index].i == i && this -> details[index].j == j){ 62 | cout << details[index++].val << " "; 63 | } 64 | else{ 65 | cout << "0 "; 66 | } 67 | } 68 | cout << endl; 69 | } 70 | } 71 | 72 | int main(){ 73 | Sparse matrix; 74 | matrix.print(); 75 | return 0; 76 | } -------------------------------------------------------------------------------- /Matrices/symmetric_matrix.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | struct Matrix 5 | { 6 | int *A; 7 | int n; 8 | }; 9 | 10 | //prints the symmetric matrix 11 | void Display(struct Matrix m) 12 | { 13 | int i,j; 14 | for(i=1;i<=m.n;i++){ 15 | for(j=1;j<=m.n;j++){ 16 | if(i<=j) 17 | printf("%d ",m.A[m.n*(i-1)-(i-1)*(i-2)/2+(j-1)]); 18 | else 19 | printf("%d ",m.A[m.n*(j-1)-(j-1)*(j-2)/2+(i-1)] ); 20 | } 21 | printf("\n"); 22 | } 23 | } 24 | 25 | //stores all the upper triangular elements in the array 26 | //all the upper triangular elements are copied in lower triangular elements 27 | void Set(struct Matrix *m,int i,int j,int x) 28 | { 29 | if(i<=j) 30 | m->A[m->n*(i-1)-(i-1)*(i-2)/2+(j-1)]=x; 31 | else 32 | m->A[m->n*(j-1)-(j-1)*(j-2)/2+(i-1)]=x; 33 | } 34 | 35 | //Returns desired elements from the array 36 | //it will check if the given index lies in upper triangular part or not and then return elements from array 37 | //two times occuring elements are stored only once and it will return mirror image of the required index which is same as passed index 38 | int Get(struct Matrix m,int i,int j) 39 | { 40 | if(i<=j) 41 | return m.A[m.n*(i-1)-(i-1)*(i-2)/2+(j-1)]; 42 | else 43 | return m.A[m.n*(j-1)-(j-1)*(j-2)/2+(i-1)]; 44 | } 45 | 46 | int main(){ 47 | int i,j,x; 48 | struct Matrix m; 49 | printf("Enter the dimension of the Matrix: "); 50 | scanf("%d",&m.n); 51 | 52 | //creating a single dimensional array so that the repeated elements are stored only once row by row 53 | //the size the array is the size of elments of upper triangular matrix 54 | m.A=(int *)malloc(m.n*(m.n+1)/2*sizeof(int)); 55 | 56 | for(i=1;i<=m.n;i++){ 57 | for(j=1;j<=m.n;j++){ 58 | scanf("%d",&x); 59 | Set(&m,i,j,x); 60 | } 61 | } 62 | printf("\n"); 63 | 64 | Display(m); 65 | 66 | printf("\nAll symmetric elements are:\n"); 67 | 68 | //prints all the elements which occurs twice in the given square symmetric matrix 69 | for(i=1;i<=m.n;i++){ 70 | for(j=1;j<=m.n;j++){ 71 | if(i<=j) 72 | printf("%d ",Get(m,i,j)); 73 | } 74 | } 75 | return 0; 76 | } 77 | -------------------------------------------------------------------------------- /Matrices/toeplitz_matrix.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | // Toeplitz matrix is the matrix having all the same diagonal elements. 5 | // Toeplitz matrix uses single dimensional array to store all the distinct elements in the matrix 6 | 7 | struct Matrix 8 | { 9 | int *A; 10 | int n; 11 | }; 12 | 13 | //elements of the first row lies in upper triangular Matrix while elements of first column lies in lower triangular matrix 14 | //setting all distinct elements in the array 15 | 16 | void Set(struct Matrix *m,int i,int j,int x ) 17 | { 18 | if(i<=j) 19 | m->A[j-i]=x; 20 | else if(i>j) 21 | m->A[m->n+(i-j)-1]=x; 22 | } 23 | 24 | // @return the elements of the toeplitz matrix 25 | 26 | int Get(struct Matrix m,int i,int j) 27 | { 28 | if(i<=j) 29 | return m.A[j-i]; 30 | else if(i>j) 31 | return m.A[m.n+(i-j)-1]; 32 | } 33 | 34 | //Print distinct elements of the matrix 35 | 36 | void Display(struct Matrix m) 37 | { 38 | int i,j; 39 | for(i=1;i<=m.n;i++){ 40 | for(j=1;j<=m.n;j++){ 41 | if(i<=j) 42 | printf("%d ",m.A[j-i]); 43 | else 44 | printf("%d ",m.A[m.n+(i-j)-1]); 45 | } 46 | printf("\n"); 47 | } 48 | } 49 | 50 | int main(){ 51 | 52 | int i,j,x; 53 | 54 | struct Matrix m; 55 | 56 | printf("Enter dimension of the array:"); 57 | scanf("%d",&m.n); 58 | 59 | //storing all the first row elements and first column elements in the Array 60 | //the size of the array will be total of first row elements and first column elements i.e. "(n)+n-1" 61 | //row 1 column 1 as it is common in both 62 | 63 | m.A=(int *)malloc(2*m.n-1*sizeof(int)); 64 | 65 | printf("\nEnter all elements of the matrix\n"); 66 | 67 | for(i=1;i<=m.n;i++){ 68 | for(j=1;j<=m.n;j++){ 69 | scanf("%d",&x); 70 | Set(&m,i,j,x); 71 | } 72 | } 73 | 74 | printf("\n\n"); 75 | 76 | Display(m); 77 | 78 | printf("\n\n"); 79 | 80 | printf("the distinct elements in Matrix are\n"); 81 | 82 | for(i=1;i<=m.n;i++){ 83 | for(j=1;j<=m.n;j++){ 84 | if(i==1) 85 | printf("%d ",Get(m,i,j) ); 86 | else if(j==1){ 87 | for(i=1;i 10 | #include 11 | 12 | struct Queue{ 13 | int size; 14 | int front; 15 | int rear; 16 | int *items; 17 | }; 18 | 19 | void createQ(struct Queue *queue){ 20 | queue->size = 10; 21 | queue->front = -1; 22 | queue->rear = -1; 23 | queue->items = (int *)malloc(queue->size*sizeof(int)); 24 | } 25 | 26 | int isEmpty(struct Queue *queue){ 27 | if(queue->front == queue->rear) 28 | return 1; 29 | return 0; 30 | } 31 | 32 | int isFull(struct Queue *queue){ 33 | if(queue->rear == queue->size-1) 34 | return 1; 35 | return 0; 36 | } 37 | 38 | void enqueueFront(struct Queue *queue, int value){ 39 | if(isFull(queue)) 40 | printf("Queue is full\n"); 41 | else if(queue->front == -1){ 42 | queue->front ++; 43 | queue->items[queue->front] = value; 44 | } 45 | else{ 46 | queue->items[queue->front] = value; 47 | queue->front --; 48 | } 49 | } 50 | 51 | void enqueueRear(struct Queue *queue, int value){ 52 | if(isFull(queue)) 53 | printf("Queue is full\n"); 54 | else{ 55 | queue->rear ++; 56 | queue->items[queue->rear] = value; 57 | } 58 | } 59 | 60 | int dequeueFront(struct Queue *queue){ 61 | int value = -1; 62 | if(isEmpty(queue)) 63 | return value; 64 | queue->front ++; 65 | value = queue->items[queue->front]; 66 | 67 | return value; 68 | } 69 | 70 | int dequeueRear(struct Queue *queue){ 71 | if(isEmpty(queue)) 72 | return -1; 73 | int value = queue->items[queue->rear]; 74 | queue->rear --; 75 | return value; 76 | } 77 | 78 | int main(){ 79 | struct Queue queue; 80 | createQ(&queue); 81 | enqueueRear(&queue, 10); 82 | enqueueRear(&queue, 20); 83 | enqueueRear(&queue, 30); 84 | enqueueRear(&queue, 40); 85 | enqueueRear(&queue, 50); 86 | printf("%d ",dequeueFront(&queue)); 87 | printf("%d ",dequeueRear(&queue)); 88 | printf("%d ",dequeueRear(&queue)); 89 | printf("%d ",dequeueRear(&queue)); 90 | printf("%d ",dequeueRear(&queue)); 91 | enqueueFront(&queue, 60); 92 | printf("%d\n",dequeueFront(&queue)); 93 | enqueueFront(&queue, 70); 94 | printf("%d\n",dequeueFront(&queue)); 95 | return 0; 96 | } -------------------------------------------------------------------------------- /Queue/QueueArray.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Author Fakhra Najm 3 | * EMail fnajm09@gmail.com 4 | 5 | Implementation of Queue using Array 6 | * 1. createQ 7 | * 2. enqueue 8 | * 3. dequeue 9 | * 4. printQ 10 | */ 11 | 12 | #include 13 | #include 14 | 15 | struct Queue 16 | { 17 | int size; 18 | int front; // index pointer to front end 19 | int rear; // index pointer to rear end 20 | int *items; 21 | }; 22 | 23 | /* 24 | * creates and initialize the members of queue 25 | * @param q pointer to the Queue 26 | */ 27 | 28 | void createQ(struct Queue *q){ 29 | printf("Enter size of the queue:\n"); 30 | scanf("%d", &q->size); 31 | q->front = q->rear = -1; 32 | q->items = (int *)malloc(q->size*sizeof(int)); 33 | } 34 | 35 | /* 36 | * inserts the passed value in the queue 37 | * @param q pointer to the queue 38 | * @param value to be inserted 39 | */ 40 | 41 | void enqueue(struct Queue *q, int value){ 42 | if(q->rear == q->size-1) 43 | printf("Queue is full\n"); 44 | else{ 45 | q->rear ++; 46 | q->items[q->rear] = value; 47 | } 48 | } 49 | 50 | /* 51 | * deletes the front element from queue 52 | * @param q pointer to the Queue 53 | * @return deleted value 54 | */ 55 | 56 | int dequeue(struct Queue *q){ 57 | int value = -1; 58 | if(q->front == q->rear) 59 | printf("Queue is empty\n"); 60 | else{ 61 | q->front ++; 62 | value = q->items[q->front]; 63 | } 64 | return value; 65 | } 66 | 67 | /* 68 | * prints the elements of Queue 69 | */ 70 | 71 | void printQ(struct Queue q){ 72 | for (int i = q.front+1; i <= q.rear; ++i) 73 | printf("%d ", q.items[i]); 74 | printf("\n"); 75 | } 76 | 77 | int main(){ 78 | struct Queue q; 79 | createQ(&q); 80 | enqueue(&q, 10); 81 | enqueue(&q, 20); 82 | enqueue(&q, 30); 83 | enqueue(&q, 40); 84 | enqueue(&q, 50); 85 | printQ(q); 86 | printf("%d\n",dequeue(&q)); 87 | printQ(q); 88 | return 0; 89 | } 90 | -------------------------------------------------------------------------------- /Queue/QueueLL.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Author : Fakhra Najm. 3 | * EMail : fnajm09@gmail.com. 4 | Implementation of queue using linkedList. 5 | * 1. enqueue 6 | * 2. dequeue 7 | * 3. printQ 8 | */ 9 | 10 | #include 11 | #include 12 | 13 | struct Node{ 14 | int data; 15 | struct Node *next; 16 | }*front = NULL, *rear = NULL; 17 | 18 | void enqueue(int value){ 19 | struct Node *queue = (struct Node *)malloc(sizeof(struct Node)); 20 | if(queue == NULL) 21 | printf("queue is full\n"); 22 | else{ 23 | queue->data = value; 24 | queue->next = NULL; 25 | if(front == NULL){ 26 | front = rear = queue; 27 | } 28 | else{ 29 | rear->next = queue; 30 | rear = queue; 31 | } 32 | } 33 | } 34 | 35 | int dequeue(){ 36 | int value = -1; 37 | if(front == NULL) 38 | printf("queue is empty\n"); 39 | else{ 40 | struct Node *queue = front; 41 | front = front->next; 42 | value = queue->data; 43 | free(queue); 44 | } 45 | return value; 46 | } 47 | 48 | void printQ(){ 49 | struct Node *node = front; 50 | while(node){ 51 | printf("%d ",node->data ); 52 | node = node->next; 53 | } 54 | printf("\n"); 55 | } 56 | 57 | int main(){ 58 | enqueue(10); 59 | enqueue(20); 60 | enqueue(30); 61 | enqueue(40); 62 | printQ(); 63 | printf("%d is deleted\n",dequeue()); 64 | printQ(); 65 | return 0; 66 | } -------------------------------------------------------------------------------- /Queue/QueueStack.c: -------------------------------------------------------------------------------- 1 | /* 2 | Author Fakhra Najm 3 | Email fnajm09@gmail.com 4 | */ 5 | 6 | #include 7 | #include 8 | 9 | struct Node{ 10 | int data; 11 | struct Node *next; 12 | }; 13 | 14 | struct Queue{ 15 | struct Node *stack1; 16 | struct Node *stack2; 17 | }; 18 | 19 | int isEmpty(struct Node *stack){ 20 | if(stack == NULL) 21 | return 1; 22 | return 0; 23 | } 24 | 25 | void push(struct Node **stack, int value){ 26 | struct Node * node = (struct Node *)malloc(sizeof(struct Node)); 27 | if(node == NULL) 28 | printf("stack is full\n"); 29 | else{ 30 | node->data = value; 31 | node->next = (*stack); 32 | (*stack) = node; 33 | } 34 | } 35 | 36 | int pop(struct Node **stack){ 37 | int value; 38 | if(isEmpty(*stack)) 39 | return -1; 40 | else{ 41 | struct Node *node = (*stack); 42 | *stack = node->next; 43 | value = node->data; 44 | free(node); 45 | } 46 | return value; 47 | } 48 | 49 | void enqueue(struct Queue *queue, int value){ 50 | push(&queue->stack1, value); 51 | } 52 | 53 | int dequeue(struct Queue *queue){ 54 | if(isEmpty(queue->stack2)){ 55 | if(isEmpty(queue->stack1)){ 56 | printf("queue is empty"); 57 | return -1; 58 | } 59 | else{ 60 | while(!isEmpty(queue->stack1)) 61 | push(&queue->stack2, pop(&queue->stack1)); 62 | } 63 | } 64 | return pop(&queue->stack2); 65 | } 66 | 67 | int main(){ 68 | struct Queue *queue = (struct Queue *)malloc(sizeof(struct Queue)); 69 | queue->stack2 = queue->stack1 = NULL; 70 | enqueue(queue, 10); 71 | enqueue(queue, 20); 72 | printf("%d\n",dequeue(queue) ); 73 | printf("%d\n",dequeue(queue) ); 74 | 75 | return 0; 76 | } -------------------------------------------------------------------------------- /Queue/circularQueueArray.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Author Fakhra Najm 3 | * EMail fnajm09@gmail.com 4 | 5 | OPerations on circular queue 6 | * 1. createQ 7 | * 2. enqueue 8 | * 3. dequeue 9 | * 4. printQ 10 | */ 11 | 12 | #include 13 | #include 14 | 15 | struct Queue 16 | { 17 | int size; 18 | int front; // index pointer to front end 19 | int rear; // index pointer to rear end 20 | int *items; 21 | }; 22 | 23 | /* 24 | * creates and initialize the members of queue 25 | * @param q pointer to the Queue 26 | */ 27 | 28 | void createQ(struct Queue *q){ 29 | printf("Enter size of the queue:\n"); 30 | scanf("%d", &q->size); 31 | q->front = q->rear = 0; 32 | q->items = (int *)malloc(q->size*sizeof(int)); 33 | } 34 | 35 | /* 36 | * inserts the passed value in the circular queue 37 | * @param q pointer to the queue 38 | * @param value to be inserted 39 | */ 40 | 41 | void enqueue(struct Queue *q, int value){ 42 | if((q->rear+1)%q->size == q->front) 43 | printf("Queue is full\n"); 44 | else{ 45 | q->rear = (q->rear+1)%q->size; 46 | q->items[q->rear] = value; 47 | } 48 | } 49 | 50 | /* 51 | * deletes the first inserted element from the queue 52 | * @param q pointer to the Queue 53 | * @return deleted value 54 | */ 55 | 56 | int dequeue(struct Queue *q){ 57 | int value = -1; 58 | if(q->front == q->rear) 59 | printf("Queue is empty\n"); 60 | else{ 61 | q->front = (q->front+1)%q->size; 62 | value = q->items[q->front]; 63 | } 64 | return value; 65 | } 66 | 67 | /* 68 | * prints elements of the circular Queue 69 | */ 70 | 71 | void printQ(struct Queue q){ 72 | int i = q.front+1; 73 | do{ 74 | printf("%d ",q.items[i] ); 75 | i = (i+1)%q.size; 76 | }while(i != (q.rear+1)%q.size); 77 | printf("\n"); 78 | } 79 | 80 | int main(){ 81 | struct Queue q; 82 | createQ(&q); 83 | enqueue(&q, 10); 84 | enqueue(&q, 20); 85 | enqueue(&q, 30); 86 | enqueue(&q, 40); 87 | enqueue(&q, 50); 88 | printQ(q); 89 | printf("%d\n",dequeue(&q)); 90 | printQ(q); 91 | return 0; 92 | } -------------------------------------------------------------------------------- /Queue/recursiveQueue.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Author Fakhra Najm 3 | * Email fnajm09@gmail.com 4 | * Queue using one stack 5 | */ 6 | 7 | #include 8 | #include 9 | 10 | struct Node { 11 | int data; 12 | struct Node *next; 13 | }*top = NULL; 14 | 15 | int isEmpty(){ 16 | if(top == NULL) 17 | return 1; 18 | return 0; 19 | } 20 | 21 | void push(int value){ 22 | struct Node *node = (struct Node*)malloc(sizeof(struct Node)); 23 | if(node == NULL) 24 | printf("Stack is Full\n"); 25 | else{ 26 | node->data = value; 27 | node->next = top; 28 | top = node; 29 | } 30 | } 31 | 32 | int pop(){ 33 | int value; 34 | if(isEmpty()) 35 | return -1; 36 | else{ 37 | struct Node *node = top; 38 | top = top->next; 39 | value = node->data; 40 | free(node); 41 | } 42 | return value; 43 | } 44 | 45 | void enqueue(int value){ 46 | push(value); 47 | } 48 | 49 | int dequeue(struct Node *head){ 50 | int value = -1; 51 | if(head){ 52 | dequeue(head->next); 53 | value = pop(); 54 | printf("%d\n",value); 55 | } 56 | return value; 57 | } 58 | 59 | int main(){ 60 | enqueue(10); 61 | enqueue(20); 62 | enqueue(30); 63 | enqueue(40); 64 | printf("%d\n",dequeue(top)); 65 | //printf("%d\n",dequeue(top)); 66 | return 0; 67 | } 68 | -------------------------------------------------------------------------------- /Stack/StackArray.c: -------------------------------------------------------------------------------- 1 | /* 2 | Author Fakhra Najm 3 | email fnajm09@gmail.com 4 | * stack implementation using array 5 | * 1. push 6 | * 2. pop 7 | * 3. peek 8 | * 4. stackTop 9 | * 5. isFull 10 | * 6. isEmpty 11 | */ 12 | 13 | #include 14 | #include 15 | 16 | struct stack{ 17 | int size; 18 | int top; 19 | int *items; 20 | }; 21 | 22 | /* 23 | * inserts value in the stack 24 | * @param st pointer to the top of stack 25 | * @param value to be inserted 26 | */ 27 | 28 | void push(struct stack *st, int value){ 29 | if(st->top == st->size-1) 30 | printf("stack overflow\n"); 31 | else{ 32 | st->top++; 33 | st->items[st->top] = value; 34 | } 35 | } 36 | 37 | /* 38 | * deletes the top value of the stack 39 | * @param st pointer to the top of stack 40 | * @return removed value 41 | */ 42 | 43 | int pop(struct stack *st){ 44 | int removed= -1; 45 | if(st->top == -1) 46 | printf("stack underflow\n"); 47 | else{ 48 | removed = st->items[st->top]; 49 | st->top--; 50 | } 51 | return removed; 52 | } 53 | 54 | /* 55 | * @param st calling stack 56 | * @param index from which value is to be returned 57 | * @return value at the given index 58 | */ 59 | 60 | int peek(struct stack st, int index){ 61 | int value = -1; 62 | if(st.top-index+1 < 0) 63 | printf("invalid index\n"); 64 | else{ 65 | value = st.items[st.top-index+1]; 66 | } 67 | return value; 68 | } 69 | 70 | /* 71 | * @param st calling stack 72 | * return value of the top 73 | */ 74 | 75 | int stackTop(struct stack st){ 76 | if (st.top == -1){ 77 | return -1; 78 | } 79 | else{ 80 | return st.items[st.top]; 81 | } 82 | } 83 | 84 | /* 85 | * @return whether stack is full or not 86 | */ 87 | 88 | int isFull(struct stack st){ 89 | if(st.top == st.size-1) 90 | return 1; 91 | else 92 | return 0; 93 | } 94 | 95 | /* 96 | * @return whether stack is empty or not 97 | */ 98 | 99 | int isEmpty(struct stack st){ 100 | if(st.top == -1) 101 | return 1; 102 | else 103 | return 0; 104 | } 105 | 106 | void printStack(struct stack st){ 107 | if(st.top == -1) 108 | return; 109 | for (int i = st.top; i >= 0; i--){ 110 | printf("%d ",st.items[i] ); 111 | } 112 | printf("\n"); 113 | } 114 | 115 | int main(){ 116 | struct stack st; 117 | printf("Enter size of stack:\n"); 118 | scanf("%d",&st.size); 119 | st.items = (int *)malloc(st.size*sizeof(int)); 120 | st.top = -1; 121 | push(&st,1); 122 | push(&st,2); 123 | push(&st,3); 124 | push(&st,4); 125 | push(&st,5); 126 | printStack(st); 127 | printf("%d\n",pop(&st) ); 128 | printStack(st); 129 | printf("%d\n",peek(st,0) ); 130 | printf("%d\n",stackTop(st) ); 131 | if(isFull == 1) 132 | printf("stack is full\n"); 133 | else 134 | printf("stack is not full\n"); 135 | if(isEmpty == 1) 136 | printf("stack is empty\n"); 137 | else 138 | printf("stack is not empty\n"); 139 | return 0; 140 | } -------------------------------------------------------------------------------- /Stack/StackLL.c: -------------------------------------------------------------------------------- 1 | /* 2 | Author Fakhra Najm 3 | email : fnajm09@gmail.com 4 | Implementation of Stack using LinkedList 5 | * 1. push 6 | * 2. pop 7 | * 3. peek 8 | */ 9 | 10 | #include 11 | #include 12 | 13 | struct stack{ 14 | int data; 15 | struct stack *next; 16 | }*top = NULL; 17 | 18 | /* 19 | * Inserts value in the stack 20 | * @param value to be inserted 21 | */ 22 | 23 | void push(int value){ 24 | struct stack *node = (struct stack *)malloc(sizeof(struct stack)); 25 | if(node == NULL) 26 | printf("Stack is full"); 27 | else{ 28 | node->data = value; 29 | node->next = top; 30 | top = node; 31 | } 32 | } 33 | 34 | /* 35 | * deletes top value of the stack 36 | * @return deleted value 37 | */ 38 | int pop(){ 39 | int deleted = -1; 40 | if(top == NULL) 41 | printf("stack is empty\n"); 42 | else{ 43 | struct stack * node = top; 44 | deleted = node->data; 45 | top = top->next; 46 | free(node); 47 | } 48 | return deleted; 49 | } 50 | 51 | /* 52 | * gives the value of element at given position 53 | * @param index of the stack 54 | * @return value at the given index 55 | */ 56 | 57 | int peek(int index){ 58 | struct stack *node = top; 59 | for(int i = 0; node!= NULL && i < index-1; ++i){ 60 | node = node->next; 61 | } 62 | if(node) 63 | return node->data; 64 | return -1; 65 | } 66 | 67 | // returns the value of top of stack 68 | 69 | int stackTop(){ 70 | if(top != NULL) 71 | return top->data; 72 | return -1; 73 | } 74 | 75 | // checking whether stack is full or not 76 | 77 | int isFull(){ 78 | struct stack *node = (struct stack *)malloc(sizeof(struct stack)); 79 | if(node == NULL) 80 | return 1; 81 | return 0; 82 | } 83 | 84 | // checking whether stack is empty or not 85 | 86 | int isEmpty(){ 87 | if(top == NULL) 88 | return 1; 89 | return 0; 90 | } 91 | 92 | // prints linkedList 93 | 94 | void printStack(){ 95 | struct stack *node = top; 96 | while(node){ 97 | printf("%d ",node->data ); 98 | node = node->next; 99 | } 100 | printf("\n"); 101 | } 102 | 103 | int main(){ 104 | push(10); 105 | push(20); 106 | push(30); 107 | push(40); 108 | push(50); 109 | printStack(); 110 | printf("search Result:%d\n",peek(1) ); 111 | printf("Deleted value:%d\n",pop() ); 112 | printStack(); 113 | printf("search Result:%d\n",stackTop() ); 114 | if(isEmpty() == 1) 115 | printf("stack is empty\n"); 116 | else 117 | printf("stack is not empty\n"); 118 | if(isFull() == 1) 119 | printf("stack is full\n"); 120 | else 121 | printf("stack is not full\n"); 122 | return 0; 123 | } -------------------------------------------------------------------------------- /Stack/application.c: -------------------------------------------------------------------------------- 1 | /* 2 | Author : Fakhra Najm 3 | EMail : fnajm09@gmail.com 4 | 5 | Applications of Stack 6 | * 1. parenthesis matching 7 | * 2. infix to postfix conversion 8 | Operations: 9 | * 1. checkmatch 10 | * 2. isOperand 11 | * 3. precedence 12 | * 4. inStack 13 | * 5. outStack 14 | * 6. makePostfix 15 | * 7. evaluate 16 | */ 17 | 18 | #include 19 | #include 20 | #include 21 | 22 | struct stack{ 23 | int data; 24 | struct stack *next; 25 | }*top = NULL; 26 | 27 | /* 28 | * inserts value inside the node of stack 29 | * @param value to be inserted 30 | */ 31 | 32 | void push(int value){ 33 | struct stack *node = (struct stack *)malloc(sizeof(struct stack)); 34 | if(node == NULL) 35 | printf("Stack is full"); 36 | else{ 37 | node->data = value; 38 | node->next = top; 39 | top = node; 40 | } 41 | } 42 | 43 | /* 44 | * deletes the top value of the stack 45 | * @return deleted value 46 | */ 47 | int pop(){ 48 | int deleted = -1; 49 | if(top == NULL) 50 | printf("stack is empty\n"); 51 | else{ 52 | struct stack * node = top; 53 | deleted = node->data; 54 | top = top->next; 55 | free(node); 56 | } 57 | return deleted; 58 | } 59 | 60 | // checking whether stack is full or not 61 | 62 | int isFull(){ 63 | struct stack *node = (struct stack *)malloc(sizeof(struct stack)); 64 | if(node == NULL) 65 | return 1; 66 | return 0; 67 | } 68 | 69 | // checking whether stack is empty or not 70 | 71 | int isEmpty(){ 72 | if(top == NULL) 73 | return 1; 74 | return 0; 75 | } 76 | 77 | // returns the value of top of stack 78 | 79 | int stackTop(){ 80 | if(top != NULL) 81 | return top->data; 82 | return -1; 83 | } 84 | 85 | /* 86 | * checks valid parantheses 87 | * @param expression pointer to the given expression 88 | */ 89 | 90 | int checkmatch(char *expression){ 91 | for(int i = 0; expression[i] != '\0'; i++){ 92 | if(expression[i] == '(' || expression[i] == '[' || expression[i] == '{') 93 | push(expression[i]); 94 | else if(expression[i] == ')' || expression[i] == '}' || expression[i] == ']'){ 95 | if(isEmpty()) 96 | return 0; 97 | else if(expression[i]-stackTop() == 1 || expression[i]-stackTop() == 2) 98 | pop(); 99 | else 100 | return 0; 101 | } 102 | } 103 | if(isEmpty()) 104 | return 1; 105 | else 106 | return 0; 107 | } 108 | 109 | // @return inside-precedence of the stack 110 | 111 | int inStack(char exp){ 112 | if(exp == '+' || exp == '-') 113 | return 2; 114 | else if(exp == '*' || exp == '/') 115 | return 4; 116 | else if(exp == '^') 117 | return 5; 118 | else if(exp == '(') 119 | return 0; 120 | return 0; 121 | } 122 | 123 | // @return outside-presedence of expression 124 | 125 | int outStack(char exp){ 126 | if(exp == '+' || exp == '-') 127 | return 1; 128 | else if(exp == '*' || exp == '/') 129 | return 3; 130 | else if(exp == '^') 131 | return 6; 132 | else if(exp == '(') 133 | return 7; 134 | else if(exp == ')') 135 | return 0; 136 | } 137 | 138 | /* 139 | * checks whether expression is operand or not 140 | * @param exp pointer to the given expression 141 | */ 142 | 143 | int isOperand(char exp){ 144 | if(exp == '+') 145 | return 0; 146 | else if(exp == '-') 147 | return 0; 148 | else if(exp == '*') 149 | return 0; 150 | else if(exp == '/') 151 | return 0; 152 | else if(exp == ')') 153 | return 0; 154 | else if(exp == '(') 155 | return 0; 156 | else if(exp == '^') 157 | return 0; 158 | else 159 | return 1; 160 | } 161 | 162 | // @return precedence order 163 | 164 | int precedence(char exp){ 165 | if(exp == '+' || exp == '-') 166 | return 1; 167 | else if(exp == '*' || exp == '/') 168 | return 2; 169 | else return 0; 170 | } 171 | 172 | /* 173 | * converts infix to postfix configuration 174 | * @param infix pointer to expression to be converted 175 | * @return postfix config 176 | */ 177 | 178 | char * makePostfix(char * infix){ 179 | char * postfix = (char *)malloc(strlen(infix)*sizeof(char)); 180 | int i ,j; 181 | i = j = 0; 182 | while(infix[i] != '\0'){ 183 | if(isOperand(infix[i])) 184 | postfix[j++] = infix[i++]; 185 | else{ 186 | if(inStack(stackTop()) < outStack(infix[i])) 187 | push(infix[i++]); 188 | else if(inStack(stackTop()) > outStack(infix[i])) 189 | postfix[j++] = pop(); 190 | else{ 191 | pop(); 192 | i++; 193 | } 194 | } 195 | } 196 | while(!isEmpty()){ 197 | if(infix[i] != '(') 198 | postfix[j++] = pop(); 199 | else 200 | pop(); 201 | } 202 | postfix[j] = '\0'; 203 | return postfix; 204 | } 205 | 206 | int evaluate(char * postfix){ 207 | int first, second, result; 208 | for (int i = 0; postfix[i] != '\0'; ++i){ 209 | if(isOperand(postfix[i])) 210 | push(postfix[i]-'0'); 211 | else{ 212 | first = pop(); 213 | second = pop(); 214 | switch(postfix[i]){ 215 | case '+' : result = second + first ; break; 216 | case '-' : result = second - first ; break; 217 | case '/' : result = second / first ; break; 218 | case '*' : result = second * first ; break; 219 | } 220 | push(result); 221 | } 222 | } 223 | return stackTop(); 224 | } 225 | 226 | int main(){ 227 | char *infix = "3*5+6/2-4"; 228 | if(checkmatch(infix)) 229 | printf("Balanced\n"); 230 | else 231 | printf("unbalanced\n"); 232 | char * postfix = makePostfix(infix); 233 | printf("%s\n",postfix ); 234 | printf("%d\n",evaluate(postfix) ); 235 | return 0; 236 | } -------------------------------------------------------------------------------- /Strings/permutation.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Topic : Permutation of strings 3 | Logic : swapping using recursion 4 | */ 5 | 6 | #include 7 | #include 8 | using namespace std; 9 | 10 | void permutation(char str[], int low, int high){ 11 | 12 | if(low == high) cout << str << endl; 13 | 14 | else { 15 | for(int i = low; i <= high; ++i){ 16 | 17 | swap(str[i], str[low]); 18 | 19 | permutation(str, low + 1, high); 20 | } 21 | 22 | } 23 | 24 | } 25 | 26 | int main(){ 27 | 28 | char str[100]; 29 | 30 | cout << "Enter String" << endl; 31 | cin >> str; 32 | 33 | int length = strlen(str); 34 | 35 | permutation(str, 0, length - 1); 36 | 37 | return 0; 38 | } -------------------------------------------------------------------------------- /binarytree/C/Queue.h: -------------------------------------------------------------------------------- 1 | //header file for creating tree using queue. 2 | 3 | #ifndef Queue_h 4 | #define Queue_h 5 | 6 | struct Node 7 | { 8 | struct Node *left_child; 9 | int data; 10 | struct Node *right_child; 11 | }; 12 | 13 | struct Queue 14 | { 15 | int size; 16 | int front; 17 | int rear; 18 | struct Node **items; 19 | }; 20 | 21 | void createQ(struct Queue *q, int size){ 22 | q->size = size; 23 | q->front = q->rear = 0; 24 | q->items = ( struct Node **)malloc(q->size*sizeof( struct Node *)); 25 | } 26 | 27 | void enqueue(struct Queue *q, struct Node *value){ 28 | if((q->rear+1)%q->size == q->front) 29 | printf("Queue is full\n"); 30 | else{ 31 | q->rear = (q->rear+1)%q->size; 32 | q->items[q->rear] = value; 33 | } 34 | } 35 | 36 | struct Node * dequeue(struct Queue *q){ 37 | struct Node * value = NULL; 38 | if(q->front == q->rear) 39 | printf("Queue is empty\n"); 40 | else{ 41 | q->front = (q->front+1)%q->size; 42 | value = q->items[q->front]; 43 | } 44 | return value; 45 | } 46 | 47 | int isEmpty(struct Queue queue){ 48 | return queue.front == queue.rear; 49 | } 50 | 51 | #endif -------------------------------------------------------------------------------- /binarytree/C/create_tree.c: -------------------------------------------------------------------------------- 1 | /* 2 | Name : Fakhra Najm 3 | Email : fnajm09@gmail.com 4 | code for creating Binary-tree with the help of queue. 5 | */ 6 | 7 | #include 8 | #include 9 | #include "Queue.h" 10 | 11 | struct Node *root = NULL; 12 | 13 | void createTree(){ 14 | struct Node *holder, *node; 15 | int value; 16 | struct Queue q; 17 | createQ(&q,100); 18 | printf("Enter root value : "); 19 | scanf("%d", &value); 20 | root = (struct Node *)malloc(sizeof(struct Node)); 21 | root->data = value; 22 | root->left_child = root->right_child = NULL; 23 | enqueue(&q, root); 24 | 25 | while(! isEmpty(q)){ 26 | holder = dequeue(&q); 27 | printf("Enter left child of %d : ", holder->data); 28 | scanf("%d", &value); 29 | if( value != -1){ 30 | node = (struct Node *)malloc(sizeof(struct Node)); 31 | node->data = value; 32 | node->left_child = node->right_child = NULL; 33 | holder->left_child = node; 34 | enqueue(&q, node); 35 | } 36 | printf("Enter right child of %d : ", holder->data); 37 | scanf("%d", &value); 38 | if( value != -1){ 39 | node = (struct Node *)malloc(sizeof(struct Node)); 40 | node->data = value; 41 | node->left_child = node->right_child = NULL; 42 | holder->right_child = node; 43 | enqueue(&q, node); 44 | } 45 | } 46 | } 47 | 48 | void preorder(struct Node *holder){ 49 | if(holder){ 50 | printf("%d ", holder->data); 51 | preorder(holder->left_child); 52 | preorder(holder->right_child); 53 | } 54 | } 55 | 56 | void postorder(struct Node *holder){ 57 | if(holder){ 58 | postorder(holder->left_child); 59 | postorder(holder->right_child); 60 | printf("%d ", holder->data); 61 | } 62 | } 63 | 64 | void Inorder(struct Node *holder){ 65 | if(holder){ 66 | postorder(holder->left_child); 67 | printf("%d ", holder->data); 68 | postorder(holder->right_child); 69 | } 70 | } 71 | 72 | int main(){ 73 | createTree(); 74 | printf("Preorder tree\n"); 75 | preorder(root); 76 | printf("\npostorder tree\n"); 77 | postorder(root); 78 | printf("\nInorder tree\n"); 79 | Inorder(root); 80 | return 0; 81 | 82 | } -------------------------------------------------------------------------------- /binarytree/C/iterativeOrder.c: -------------------------------------------------------------------------------- 1 | /* 2 | Name : Fakhra Najm 3 | email : fnajm09@gmail.com 4 | Iterative function for tree traversal 5 | */ 6 | 7 | #include 8 | #include 9 | #include"Queue.h" 10 | #include"stack.h" 11 | 12 | 13 | struct Node *root = NULL; 14 | 15 | void createTree(){ 16 | struct Node *holder, *node; 17 | struct Queue q; 18 | createQ(&q, 100); 19 | int value; 20 | printf("Enter root value : "); 21 | scanf("%d", &value); 22 | root = (struct Node *)malloc(sizeof(struct Node)); 23 | root->data = value; 24 | root->left_child = root->right_child = NULL; 25 | enqueue(&q, root); 26 | 27 | while(! isEmpty(q)){ 28 | holder = dequeue(&q); 29 | printf("Enter leftChild of %d :", holder->data); 30 | scanf("%d", &value); 31 | if(value != -1){ 32 | node = (struct Node *)malloc(sizeof(struct Node)); 33 | node->data = value; 34 | node->left_child = node->right_child = NULL; 35 | holder->left_child = node; 36 | enqueue(&q, node); 37 | } 38 | 39 | printf("Enter RightChild of %d :", holder->data); 40 | scanf("%d", &value); 41 | if(value != -1){ 42 | node = (struct Node *)malloc(sizeof(struct Node)); 43 | node->data = value; 44 | node->left_child = node->right_child = NULL; 45 | holder->right_child = node; 46 | enqueue(&q, node); 47 | } 48 | } 49 | } 50 | 51 | void preorder(struct Node *node){ 52 | struct stack st; 53 | createStack(&st, 100); 54 | while(node != NULL || !isEmptyStack(st)){ 55 | if(node != NULL){ 56 | printf("%d ", node->data); 57 | push(&st, node); 58 | node = node->left_child; 59 | } 60 | else{ 61 | node = pop(&st); 62 | node = node->right_child; 63 | } 64 | } 65 | printf("\n"); 66 | } 67 | 68 | void postorder(struct Node *node){ 69 | struct stack st1, st2; 70 | struct Node *value; 71 | 72 | createStack(&st1, 100); 73 | createStack(&st2, 100); 74 | 75 | while(node != NULL || !isEmptyStack(st2)){ 76 | if(node != NULL){ 77 | push(&st1, node); 78 | push(&st2, node); 79 | node = node->left_child; 80 | } 81 | else{ 82 | if(!isEmptyStack(st1)){ 83 | node = pop(&st1); 84 | node = node->right_child; 85 | } 86 | else{ 87 | printf("%d ", pop(&st2)->data); 88 | } 89 | } 90 | } 91 | printf("\n"); 92 | } 93 | 94 | void Inorder(struct Node *node){ 95 | struct stack st; 96 | createStack(&st, 100); 97 | while(node != NULL || !isEmptyStack(st)){ 98 | if(node != NULL){ 99 | push(&st, node); 100 | node = node->left_child; 101 | } 102 | else{ 103 | node = pop(&st); 104 | printf("%d ", node->data); 105 | node = node->right_child; 106 | } 107 | } 108 | printf("\n"); 109 | } 110 | 111 | int main(){ 112 | 113 | createTree(); 114 | printf("Preorder: "); 115 | preorder(root); 116 | printf("Inorder: "); 117 | Inorder(root); 118 | printf("Postorder: "); 119 | postorder(root); 120 | return 0; 121 | } -------------------------------------------------------------------------------- /binarytree/C/levelorder.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Name : Fakhra Najm 3 | * Email : fnajm09@gmail.com 4 | * Topic : Level order tree traversal using queue 5 | */ 6 | 7 | #include 8 | #include 9 | 10 | #include"Queue.h" 11 | 12 | struct Node * root = NULL; 13 | struct Queue q; 14 | 15 | void createTree(){ 16 | createQ(&q, 100); 17 | struct Node * add, *node; 18 | int value; 19 | printf("Enter root Value: "); 20 | scanf("%d", &value); 21 | root = (struct Node *)malloc(sizeof(struct Node)); 22 | root->data = value; 23 | root->left_child = root->right_child = NULL; 24 | enqueue(&q, root); 25 | while(! isEmpty(q)){ 26 | add = dequeue(&q); 27 | printf("Enter left child of %d: ", add->data); 28 | scanf("%d", &value); 29 | if(value != -1){ 30 | node = (struct Node *)malloc(sizeof(struct Node)); 31 | node->data = value; 32 | node->left_child = node->right_child = NULL; 33 | add->left_child = node; 34 | enqueue(&q, node); 35 | } 36 | printf("Enter rightt child of %d: ", add->data); 37 | scanf("%d", &value); 38 | if(value != -1){ 39 | node = (struct Node *)malloc(sizeof(struct Node)); 40 | node->data = value; 41 | node->left_child = node->right_child = NULL; 42 | add->right_child = node; 43 | enqueue(&q, node); 44 | } 45 | } 46 | } 47 | 48 | void levelorder(struct Node *root){ 49 | createQ(&q, 100); 50 | printf("%d ", root->data); 51 | enqueue(&q, root); 52 | while(! isEmpty(q)){ 53 | root = dequeue(&q); 54 | if(root->left_child){ 55 | printf("%d ", root->left_child->data); 56 | enqueue(&q, root->left_child); 57 | } 58 | if(root->right_child){ 59 | printf("%d ", root->right_child->data); 60 | enqueue(&q, root->right_child); 61 | } 62 | } 63 | } 64 | 65 | int main(){ 66 | createTree(); 67 | levelorder(root); 68 | 69 | } 70 | -------------------------------------------------------------------------------- /binarytree/C/nodes.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Name : Fakhra Najm 3 | * Eamil : fnajm09@gmail.com 4 | * Topic : Count number of nodes of a binary tree 5 | * Total number of nodes 6 | * Leaf nodes 7 | * Nodes with degree 1 8 | * Nodes with degree 2 9 | * Nodes with either degree 1 or 2 10 | */ 11 | 12 | #include 13 | #include 14 | 15 | #include"tree.h" 16 | 17 | 18 | // returns the total count of nodes in the binarytree 19 | 20 | int nodes(struct Node * root){ 21 | if(root){ 22 | return nodes(root->left_child) + nodes(root->right_child) + 1; 23 | } 24 | return 0; 25 | } 26 | 27 | // returns the number of leaf nodes i.e. nodes having zero child nodes 28 | 29 | int leafNodes(struct Node *root){ 30 | if(root){ 31 | if(! root->left_child && !root->right_child){ 32 | return leafNodes(root->left_child) + leafNodes(root->right_child) + 1; 33 | } 34 | else{ 35 | return leafNodes(root->left_child) + leafNodes(root->right_child); 36 | } 37 | } 38 | return 0; 39 | } 40 | 41 | // returns the number of nodes having both left child and right child 42 | 43 | int binaryNodes(struct Node *root){ 44 | if(root){ 45 | if(root->left_child && root->right_child){ 46 | return binaryNodes(root->left_child) + binaryNodes(root->right_child) + 1; 47 | } 48 | return binaryNodes(root->left_child) + binaryNodes(root->right_child); 49 | } 50 | return 0; 51 | } 52 | 53 | // returns the number of nodes only one child 54 | 55 | int end_vertex(struct Node *root){ 56 | if(root){ 57 | if(!root->left_child ^ !root->right_child){ 58 | return end_vertex(root->left_child) + end_vertex(root->right_child) + 1; 59 | } 60 | return end_vertex(root->left_child) + end_vertex(root->right_child); 61 | } 62 | return 0; 63 | } 64 | 65 | // Returns the number of nodes having either or one of left and right child 66 | 67 | int nonLeaf(struct Node *root){ 68 | if(root){ 69 | if(root->left_child || root->right_child) 70 | return nonLeaf(root->left_child) + nonLeaf(root->right_child) + 1; 71 | return nonLeaf(root->left_child) + nonLeaf(root->right_child); 72 | } 73 | return 0; 74 | } 75 | 76 | int main(){ 77 | createTree(); 78 | printf("Number of nodes: %d\n", nodes(root)); 79 | printf("Number of leaf nodes: %d\n", leafNodes(root)); 80 | printf("Number of binary nodes: %d\n", binaryNodes(root)); 81 | printf("Number of single nodes: %d\n", end_vertex(root)); 82 | printf("Number of non leaf nodes : %d", nonLeaf(root)); 83 | return 0; 84 | } -------------------------------------------------------------------------------- /binarytree/C/postorder.c: -------------------------------------------------------------------------------- 1 | /* 2 | Name : Fakhra Najm 3 | Email : fnajm09@gmail.com 4 | Postorder traversal with one stack without using recursion 5 | */ 6 | 7 | #include 8 | #include 9 | #include"Queue.h" 10 | #include"stack.h" 11 | 12 | struct Node *root = NULL; 13 | struct Queue queue; 14 | struct stack stk; 15 | 16 | void createTree(){ 17 | createQ(&queue, 100); 18 | struct Node *node, *place_holder; 19 | int value; 20 | printf("Enter root value : "); 21 | scanf("%d", &value); 22 | root = (struct Node *)malloc(sizeof(struct Node)); 23 | root->data = value; 24 | root->left_child = root->right_child = NULL; 25 | enqueue(&queue, root); 26 | 27 | while ( ! isEmpty(queue)) 28 | { 29 | place_holder = dequeue(&queue); 30 | 31 | printf("Enter left child of %d: ", place_holder->data); 32 | scanf("%d", &value); 33 | if(value != -1){ 34 | node = (struct Node *)malloc(sizeof(struct Node)); 35 | node->data = value; 36 | node->left_child = node->right_child = NULL; 37 | place_holder->left_child = node; 38 | enqueue(&queue, node); 39 | } 40 | 41 | printf("Enter right child of %d: ", place_holder->data); 42 | scanf("%d", &value); 43 | if(value != -1){ 44 | node = (struct Node *)malloc(sizeof(struct Node)); 45 | node->data = value; 46 | node->left_child = node->right_child = NULL; 47 | place_holder->right_child = node; 48 | enqueue(&queue, node); 49 | } 50 | } 51 | } 52 | 53 | void postorder(struct Node *root){ 54 | createStack(&stk, 100); 55 | do{ 56 | if(root){ 57 | push(&stk, root); 58 | root = root->left_child; 59 | } 60 | else{ 61 | root = stackTop(stk)->right_child; 62 | if(! root){ 63 | struct Node *last = NULL; 64 | while(!isEmptyStack(stk) && stackTop(stk)->right_child == last){ 65 | last = pop(&stk); 66 | printf("%d ", last->data); 67 | } 68 | } 69 | } 70 | }while(! isEmptyStack(stk)); 71 | } 72 | 73 | int main(){ 74 | createTree(); 75 | postorder(root); 76 | return 0; 77 | } -------------------------------------------------------------------------------- /binarytree/C/stack.h: -------------------------------------------------------------------------------- 1 | #ifndef stack_h 2 | #define stack_h 3 | 4 | #include"Queue.h" 5 | 6 | struct stack{ 7 | int size; 8 | int top; 9 | struct Node **items; 10 | }; 11 | 12 | void createStack(struct stack *st, int sz){ 13 | st->items = (struct Node **)malloc(sizeof(struct Node)); 14 | st->size = sz; 15 | st->top = -1; 16 | } 17 | 18 | void push(struct stack *st, struct Node *value){ 19 | if(st->top == st->size-1) 20 | printf("stack overflow\n"); 21 | else{ 22 | st->top++; 23 | st->items[st->top] = value; 24 | } 25 | } 26 | 27 | /* 28 | * deletes the top value of the stack 29 | * @param st pointer to the top pointer of stack 30 | * @return removed value 31 | */ 32 | 33 | struct Node * pop(struct stack *st){ 34 | struct Node * removed = NULL; 35 | if(st->top == -1) 36 | printf("stack underflow\n"); 37 | else{ 38 | removed = st->items[st->top]; 39 | st->top--; 40 | } 41 | return removed; 42 | } 43 | 44 | 45 | /* 46 | * checks whether stack is full or not 47 | * @return true or false 48 | */ 49 | 50 | int isFull(struct stack st){ 51 | if(st.top == st.size-1) 52 | return 1; 53 | else 54 | return 0; 55 | } 56 | 57 | /* 58 | * checks whether stack is empty or not 59 | * @return true or false 60 | */ 61 | 62 | int isEmptyStack(struct stack st){ 63 | if(st.top == -1) 64 | return 1; 65 | else 66 | return 0; 67 | } 68 | 69 | struct Node * stackTop(struct stack st){ 70 | if (st.top == -1){ 71 | return NULL; 72 | } 73 | else{ 74 | return st.items[st.top]; 75 | } 76 | } 77 | 78 | struct Node * peek(struct stack st, int index){ 79 | struct Node *value = NULL; 80 | if(st.top-index+1 < 0) 81 | printf("invalid index\n"); 82 | else{ 83 | value = st.items[st.top-index+1]; 84 | } 85 | return value; 86 | } 87 | #endif -------------------------------------------------------------------------------- /binarytree/C/tree.h: -------------------------------------------------------------------------------- 1 | #ifndef tree_h 2 | #define tree_h 3 | 4 | #include "Queue.h" 5 | 6 | struct Node *root = NULL; 7 | 8 | void createTree(){ 9 | struct Node *holder, *node; 10 | int value; 11 | struct Queue q; 12 | createQ(&q, 100); 13 | printf("Enter root value : "); 14 | scanf("%d", &value); 15 | root = (struct Node *)malloc(sizeof(struct Node)); 16 | root->data = value; 17 | root->left_child = root->right_child = NULL; 18 | enqueue(&q, root); 19 | 20 | while(! isEmpty(q)){ 21 | holder = dequeue(&q); 22 | printf("Enter left child of %d : ", holder->data); 23 | scanf("%d", &value); 24 | if( value != -1){ 25 | node = (struct Node *)malloc(sizeof(struct Node)); 26 | node->data = value; 27 | node->left_child = node->right_child = NULL; 28 | holder->left_child = node; 29 | enqueue(&q, node); 30 | } 31 | printf("Enter right child of %d : ", holder->data); 32 | scanf("%d", &value); 33 | if( value != -1){ 34 | node = (struct Node *)malloc(sizeof(struct Node)); 35 | node->data = value; 36 | node->left_child = node->right_child = NULL; 37 | holder->right_child = node; 38 | enqueue(&q, node); 39 | } 40 | } 41 | } 42 | 43 | void preorder(struct Node *holder){ 44 | if(holder){ 45 | printf("%d ", holder->data); 46 | preorder(holder->left_child); 47 | preorder(holder->right_child); 48 | } 49 | } 50 | 51 | void postorder(struct Node *holder){ 52 | if(holder){ 53 | postorder(holder->left_child); 54 | postorder(holder->right_child); 55 | printf("%d ", holder->data); 56 | } 57 | } 58 | 59 | void Inorder(struct Node *holder){ 60 | if(holder){ 61 | postorder(holder->left_child); 62 | printf("%d ", holder->data); 63 | postorder(holder->right_child); 64 | } 65 | } 66 | 67 | #endif -------------------------------------------------------------------------------- /binarytree/CPP/binaryTree.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class BinaryTree{ 6 | 7 | class TreeNode{ 8 | public: 9 | int val; 10 | TreeNode *left; 11 | TreeNode *right; 12 | }; 13 | 14 | 15 | public: 16 | 17 | TreeNode *root; 18 | 19 | BinaryTree(); 20 | 21 | void preorder(TreeNode *root); 22 | void inorder(TreeNode *root); 23 | void postorder(TreeNode *root); 24 | 25 | TreeNode *getRoot(){return root;} 26 | int getHeight(TreeNode *root); 27 | int getTotalNodes(TreeNode *root); 28 | int getTotalLeafNodes(TreeNode *root); 29 | int getSingleDegreeNodes(TreeNode *root); 30 | int getSecondDegreeNodes(TreeNode *root); 31 | int getNonLeafNodes(TreeNode *root); 32 | }; 33 | 34 | int main(){ 35 | 36 | BinaryTree binarytree; 37 | cout << "Tree created ! " << endl; 38 | cout << "inorder : "; 39 | binarytree.inorder(binarytree.getRoot()); 40 | cout << endl; 41 | cout << "preorder : "; 42 | binarytree.preorder(binarytree.getRoot()); 43 | cout << endl; 44 | cout << "postorder : "; 45 | binarytree.postorder(binarytree.getRoot()); 46 | cout << endl; 47 | cout << "levelorder : "; 48 | binarytree.levelorder(); 49 | cout << endl; 50 | cout << "getHeight : " ; 51 | cout << binarytree.getHeight(binarytree.getRoot()); 52 | cout << endl; 53 | cout << "Total Nodes : " ; 54 | cout << binarytree.getTotalNodes(binarytree.getRoot()); 55 | cout << endl; 56 | cout << "Total Leaf Nodes : " ; 57 | cout << binarytree.getTotalLeafNodes(binarytree.getRoot()); 58 | cout << endl; 59 | cout << "One degree Nodes : " ; 60 | cout << binarytree.getSingleDegreeNodes(binarytree.getRoot()); 61 | cout << endl; 62 | cout << "second degree Nodes : " ; 63 | cout << binarytree.getSecondDegreeNodes(binarytree.getRoot()); 64 | cout << endl; 65 | cout << "Non Leaf Nodes : " ; 66 | cout << binarytree.getNonLeafNodes(binarytree.getRoot()); 67 | return 0; 68 | } 69 | 70 | BinaryTree :: BinaryTree(){ 71 | queueTreeNodes; 72 | int value; 73 | root = new TreeNode; 74 | 75 | cout << "Enter value of root"; 76 | cin >> value; 77 | 78 | root -> val = value; 79 | TreeNodes.push(root); 80 | 81 | while(!TreeNodes.empty()){ 82 | int left_value, right_value; 83 | TreeNode *currNode = TreeNodes.front(); 84 | TreeNodes.pop(); 85 | 86 | cout << "Enter Left child of " << currNode -> val << " : " << endl; 87 | cin >> left_value; 88 | cout << "Enter Right child of " << currNode -> val << " : " << endl; 89 | cin >> right_value; 90 | 91 | if(left_value != -1){ 92 | TreeNode *curr = new TreeNode; 93 | curr -> val = left_value; 94 | currNode -> left = curr; 95 | currNode -> right = NULL; 96 | TreeNodes.push(curr); 97 | } 98 | 99 | if(right_value != -1){ 100 | TreeNode *curr = new TreeNode; 101 | curr -> val = right_value; 102 | if(!currNode->left) currNode -> left = NULL; 103 | currNode -> right = curr; 104 | TreeNodes.push(curr); 105 | } 106 | } 107 | } 108 | 109 | void BinaryTree :: inorder(TreeNode *root){ 110 | if(!root) return; 111 | inorder(root -> left); 112 | cout << root -> val << " "; 113 | inorder(root -> right); 114 | } 115 | 116 | void BinaryTree :: postorder(TreeNode *root){ 117 | if(!root) return; 118 | postorder(root -> left); 119 | postorder(root -> right); 120 | cout << root -> val << " "; 121 | } 122 | 123 | void BinaryTree :: preorder(TreeNode *root){ 124 | if(!root) return; 125 | cout << root -> val << " "; 126 | preorder(root -> left); 127 | preorder(root -> right); 128 | } 129 | 130 | 131 | 132 | int BinaryTree :: getHeight(TreeNode *root){ 133 | if(!root || (!root -> left && !root -> right)) return 0; 134 | return max(getHeight(root -> left), getHeight(root -> right)) + 1; 135 | } 136 | 137 | int BinaryTree :: getTotalNodes(TreeNode *root){ 138 | if(!root) return 0; 139 | return getTotalNodes(root -> left) + getTotalNodes(root -> right) + 1; 140 | } 141 | 142 | int BinaryTree :: getTotalLeafNodes(TreeNode *root){ 143 | if(!root) return 0; 144 | if(!root -> left && !root -> right) return 1; 145 | return getTotalLeafNodes(root -> left) + getTotalLeafNodes(root -> right); 146 | } 147 | 148 | int BinaryTree :: getSingleDegreeNodes(TreeNode *root ){ 149 | if(!root || (!root -> left && !root -> right)) return 0; 150 | if(!root -> left || !root -> right) return 1; 151 | return getSingleDegreeNodes(root -> left) + getSingleDegreeNodes(root -> right); 152 | } 153 | 154 | int BinaryTree :: getSecondDegreeNodes(TreeNode *root){ 155 | if(!root) return 0; 156 | if(root -> left && root -> right) 157 | return getSecondDegreeNodes(root -> left) + getSecondDegreeNodes(root -> right) + 1; 158 | return getSecondDegreeNodes(root -> left) + getSecondDegreeNodes(root -> right); 159 | } 160 | 161 | int BinaryTree :: getNonLeafNodes(TreeNode *root){ 162 | if(!root || (!root -> left && !root -> right)) return 0; 163 | 164 | if(root -> left || root -> right) 165 | return getNonLeafNodes(root -> left ) + getNonLeafNodes(root -> right) + 1; 166 | return getNonLeafNodes(root -> left ) + getNonLeafNodes(root -> right); 167 | } 168 | -------------------------------------------------------------------------------- /binarytree/CPP/generateTree.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Topic : generating tree from preorder and inorder traversals 3 | Link : "https://ideone.com/GD10kh" 4 | */ 5 | 6 | #include 7 | #include 8 | #include 9 | using namespace std; 10 | 11 | class TreeNode{ 12 | public : 13 | int val; 14 | TreeNode *left; 15 | TreeNode *right; 16 | TreeNode(); 17 | TreeNode(int val){this -> val = val;} 18 | 19 | ~TreeNode(); 20 | }; 21 | 22 | 23 | class Tree{ 24 | TreeNode *root; 25 | public: 26 | 27 | Tree(){this -> root = NULL;} 28 | TreeNode * getRoot(){return root;} 29 | int search(int arr[], int begin, int end, int val); 30 | TreeNode * generateTreeFromTraversal(int inorder[], int preorder[], int begin, int end); 31 | void preorder(TreeNode *root); 32 | ~Tree(){}; 33 | 34 | }; 35 | 36 | 37 | int Tree :: search(int arr[], int begin, int end, int val){ 38 | for(int i = begin; i <= end; ++i){ 39 | if(arr[i] == val) return i; 40 | } 41 | return -1; 42 | } 43 | 44 | TreeNode * Tree :: generateTreeFromTraversal(int inorder[], int preorder[], int begin, int end){ 45 | static int index = 0; 46 | 47 | if(index > end || begin > end) return NULL; 48 | 49 | TreeNode *node = new TreeNode(preorder[index++]); 50 | 51 | if(begin == end) return node; 52 | 53 | int splitIndex = search(inorder, begin, end, node -> val); 54 | node -> left = generateTreeFromTraversal(inorder, preorder, begin, splitIndex - 1); 55 | node -> right = generateTreeFromTraversal(inorder, preorder, splitIndex + 1, end); 56 | 57 | return node; 58 | } 59 | 60 | 61 | void Tree :: preorder(TreeNode *root){ 62 | if(!root) return; 63 | cout << root -> val << " "; 64 | preorder(root -> left); 65 | preorder(root -> right); 66 | } 67 | 68 | int main(){ 69 | int preorder[] = {4, 7, 9, 6, 3, 2, 5, 8, 1}; 70 | int inorder[] = {7, 6, 9, 3, 4, 5, 8, 2, 1}; 71 | Tree binarytree; 72 | TreeNode *root = binarytree.generateTreeFromTraversal(inorder, preorder, 0, 8); 73 | binarytree.preorder(root); 74 | cout << endl; 75 | return 0; 76 | } -------------------------------------------------------------------------------- /binarytree/CPP/traversals.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Topic : Iterative binary tree traversal 3 | 1. Inorder 4 | 2. Preorder 5 | 3. Postorder 6 | 4. Leveloreder 7 | 5. PostOrder using one stack 8 | */ 9 | 10 | #include 11 | #include 12 | #include 13 | using namespace std; 14 | 15 | class BinaryTree{ 16 | 17 | class TreeNode{ 18 | public: 19 | int val; 20 | TreeNode *left; 21 | TreeNode *right; 22 | }; 23 | TreeNode *root; 24 | public: 25 | 26 | BinaryTree(); 27 | 28 | TreeNode *getRoot(){return root;} 29 | 30 | void inorderTraversal(TreeNode *root); 31 | void preorderTraversal(TreeNode *root); 32 | void postorderTraversal(TreeNode *root); 33 | void levelorderTraversal(TreeNode *root); 34 | void postorder(TreeNode *root); 35 | 36 | }; 37 | 38 | int main(){ 39 | BinaryTree tree; 40 | tree.postorder(tree.getRoot()); 41 | return 0; 42 | } 43 | 44 | BinaryTree :: BinaryTree(){ 45 | queueTreeNodes; 46 | int value; 47 | root = new TreeNode; 48 | 49 | cout << "Enter value of root"; 50 | cin >> value; 51 | 52 | root -> val = value; 53 | TreeNodes.push(root); 54 | 55 | while(!TreeNodes.empty()){ 56 | int left_value, right_value; 57 | TreeNode *currNode = TreeNodes.front(); 58 | TreeNodes.pop(); 59 | 60 | cout << "Enter Left child of " << currNode -> val << " : " << endl; 61 | cin >> left_value; 62 | cout << "Enter Right child of " << currNode -> val << " : " << endl; 63 | cin >> right_value; 64 | 65 | if(left_value != -1){ 66 | TreeNode *curr = new TreeNode; 67 | curr -> val = left_value; 68 | currNode -> left = curr; 69 | currNode -> right = NULL; 70 | TreeNodes.push(curr); 71 | } 72 | 73 | if(right_value != -1){ 74 | TreeNode *curr = new TreeNode; 75 | curr -> val = right_value; 76 | if(!currNode->left) currNode -> left = NULL; 77 | currNode -> right = curr; 78 | TreeNodes.push(curr); 79 | } 80 | } 81 | } 82 | 83 | /* Recursive Inorder Traversal 84 | 85 | 1. if root is Not NULL 86 | push into stack 87 | move to root's Left 88 | 2. else 89 | move to top's right 90 | print top 91 | pop top 92 | */ 93 | 94 | void BinaryTree :: inorderTraversal(TreeNode *root){ 95 | stacknodes; 96 | 97 | if(!root ) return; 98 | 99 | nodes.push(root); 100 | root = root -> left; 101 | 102 | while(!nodes.empty() || root){ 103 | if(root){ 104 | nodes.push(root); 105 | root = root -> left; 106 | } 107 | else{ 108 | root = nodes.top() -> right; 109 | cout << nodes.top() -> val << " "; 110 | nodes.pop(); 111 | } 112 | } 113 | } 114 | 115 | void BinaryTree :: preorderTraversal(TreeNode *root){ 116 | stacknodes; 117 | 118 | if(! root) return; 119 | 120 | cout << root -> val << " "; 121 | nodes.push(root); 122 | root = root -> left; 123 | 124 | while(!nodes.empty() || root){ 125 | if(root){ 126 | cout << root -> val; 127 | nodes.push(root); 128 | root = root -> left; 129 | } 130 | else{ 131 | root = nodes.top() -> right; 132 | nodes.pop(); 133 | } 134 | } 135 | } 136 | 137 | void BinaryTree :: levelorderTraversal(TreeNode *root){ 138 | queuenodes; 139 | 140 | nodes.push(root); 141 | 142 | while(!nodes.empty()){ 143 | 144 | TreeNode *curr = nodes.front(); 145 | nodes.pop(); 146 | 147 | if(curr){ 148 | cout << curr -> val << " "; 149 | nodes.push(curr -> left); 150 | nodes.push(curr -> right); 151 | } 152 | 153 | } 154 | } 155 | 156 | void BinaryTree :: postorderTraversal(TreeNode *root){ 157 | stackchilderen; 158 | stacknodes; 159 | 160 | childeren.push(root); 161 | 162 | while(!childeren.empty()){ 163 | TreeNode *node = childeren.top(); 164 | childeren.pop(); 165 | nodes.push(node); 166 | if(node -> left) childeren.push(node -> left); 167 | if(node -> right) childeren.push(node -> right); 168 | } 169 | 170 | while(!nodes.empty()){ 171 | cout << nodes.top() -> val << " "; 172 | nodes.pop(); 173 | } 174 | 175 | cout << endl; 176 | } 177 | 178 | void BinaryTree :: postorder(TreeNode *root){ 179 | if(!root) return; 180 | 181 | stacknodes; 182 | 183 | nodes.push(root); 184 | root = root -> left; 185 | 186 | while(!nodes.empty() || root){ 187 | if(root){ 188 | nodes.push(root); 189 | root = root -> left; 190 | } 191 | else{ 192 | root = nodes.top() -> right; 193 | if(!root){ 194 | TreeNode *last_visited_node = root; 195 | while(!nodes.empty() && nodes.top() -> right == last_visited_node){ 196 | last_visited_node = nodes.top(); 197 | nodes.pop(); 198 | cout << last_visited_node -> val << " "; 199 | } 200 | } 201 | } 202 | } 203 | } --------------------------------------------------------------------------------