├── README.md ├── Removing_duplicates_from_linked_list.c ├── algorithms └── searching and sorting │ ├── Cocktail_sort_c++.cpp │ ├── Insertion sort │ ├── README.md │ └── insertion_sort.cpp │ ├── MergeSort │ ├── Code.cpp │ └── Explanation-and-Algorithm.md │ ├── Quick Sort │ └── Quick Sort Code │ ├── Radix Sort.cpp │ ├── Selection Sort.cpp │ ├── Shell Sort.cpp │ ├── binary search │ ├── BinarySearch.cpp │ ├── README.md │ └── binary_search.cpp │ ├── bubble sort │ ├── README.md │ └── bubble_sort.cpp │ ├── bucketSort.cpp │ ├── counting_sort.cpp │ ├── heap_sort.cpp │ ├── linear search │ ├── LinearSearch.cpp │ └── linear_search.cpp │ └── merge sort │ ├── README.md │ └── merge sort.cpp ├── data structures ├── graphs │ ├── BFS_DFS_traversal.cpp │ ├── BellmanFord.cpp │ ├── Dijkstras_algo.cpp │ ├── FloydWarshall_APSP.cpp │ ├── ReadMe.md │ ├── kruskals_algo.cpp │ └── prims_algo.cpp ├── linked lists │ ├── README.md │ ├── SinglyLinkedList.cpp │ ├── linked_lists.cpp │ ├── reverseLL.cpp │ └── searching.cpp ├── queues │ ├── README.md │ ├── circular_queue.cpp │ ├── queue_using_array.cpp │ ├── queue_using_ll.cpp │ └── queue_using_stacks.cpp ├── stacks │ ├── README.md │ ├── stack_using_arrays.cpp │ ├── stack_using_ll.cpp │ └── string_reverse_stack.cpp └── trees │ ├── README.md │ ├── binary trees │ └── binary search trees │ │ ├── binary_search_tree.cpp │ │ └── threaded_bst.cpp │ └── expression_tree.cpp └── other programs ├── Count Inversion Program ├── DecimalToBinary.cpp ├── FibonacciSequence.cpp ├── GCD.cpp ├── LargeNumberFactorial.cpp ├── N-Queens Problem ├── No_of_divisors_with_sum.cpp ├── Restoring division ├── readme.md └── restoring_division.cpp └── Sieve_of_Eratosthenes.cpp /README.md: -------------------------------------------------------------------------------- 1 | # CPP 2 | ## What does this repository contain? 3 | This repository features programs in C++. It is divided into 3 folders (data structures, algorithms, and other programs) in which you can find code implementations in C++, along with an explanation of the concept. 4 | 5 | ## Can I contribute? 6 | Yes! :smile: you can definitely contribute! 7 | The following are some of the things you can do - 8 | 1. If you have a program written in C++ that is not in the repository you can open up a PR. You can also open up a PR if you have another way of implementing a concept in the repo. 9 | 2. Also, if you can see something wrong (maybe like an error or something), you can open up a PR. 10 | 3. Another suggestion is if you can think of a creative way to explain any concept using markdown, you are welcome to contribute! 11 | 12 | ## How can I contribute? 13 | It is very easy to contribute, you may follow these steps - 14 | 1. Fork this repository 15 | 2. Make changes/ add things 16 | 3. Open up a PR. It will be merged after review. 17 | 18 | 19 | Do ⭐ the repo if you find it useful!! 😇😀😇 20 | 21 | ## What to keep in mind while contributing? 22 | - Please make sure that your contribution is entirely your own, and not copied from some other source. 23 | 24 | -------------------------------------------------------------------------------- /Removing_duplicates_from_linked_list.c: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | #include 4 | 5 | struct node 6 | { 7 | int num; 8 | struct node *next; 9 | }; 10 | 11 | void create(struct node **); 12 | void dup_delete(struct node **); 13 | void release(struct node **); 14 | void display(struct node *); 15 | 16 | int main() 17 | { 18 | struct node *p = NULL; 19 | struct node_occur *head = NULL; 20 | int n; 21 | 22 | printf("Enter data into the list\n"); 23 | create(&p); 24 | printf("Displaying the nodes in the list:\n"); 25 | display(p); 26 | printf("Deleting duplicate elements in the list...\n"); 27 | dup_delete(&p); 28 | printf("Displaying non-deleted nodes in the list:\n"); 29 | display(p); 30 | release(&p); 31 | 32 | return 0; 33 | } 34 | 35 | void dup_delete(struct node **head) 36 | { 37 | struct node *p, *q, *prev, *temp; 38 | 39 | p = q = prev = *head; 40 | q = q->next; 41 | while (p != NULL) 42 | { 43 | while (q != NULL && q->num != p->num) 44 | { 45 | prev = q; 46 | q = q->next; 47 | } 48 | if (q == NULL) 49 | { 50 | p = p->next; 51 | if (p != NULL) 52 | { 53 | q = p->next; 54 | } 55 | } 56 | else if (q->num == p->num) 57 | { 58 | prev->next = q->next; 59 | temp = q; 60 | q = q->next; 61 | free(temp); 62 | } 63 | } 64 | } 65 | 66 | void create(struct node **head) 67 | { 68 | int c, ch; 69 | struct node *temp, *rear; 70 | 71 | do 72 | { 73 | printf("Enter number: "); 74 | scanf("%d", &c); 75 | temp = (struct node *)malloc(sizeof(struct node)); 76 | temp->num = c; 77 | temp->next = NULL; 78 | if (*head == NULL) 79 | { 80 | *head = temp; 81 | } 82 | else 83 | { 84 | rear->next = temp; 85 | } 86 | rear = temp; 87 | printf("Do you wish to continue [1/0]: "); 88 | scanf("%d", &ch); 89 | } while (ch != 0); 90 | printf("\n"); 91 | } 92 | 93 | void display(struct node *p) 94 | { 95 | while (p != NULL) 96 | { 97 | printf("%d\t", p->num); 98 | p = p->next; 99 | } 100 | printf("\n"); 101 | } 102 | 103 | void release(struct node **head) 104 | { 105 | struct node *temp = *head; 106 | *head = (*head)->next; 107 | while ((*head) != NULL) 108 | { 109 | free(temp); 110 | temp = *head; 111 | (*head) = (*head)->next; 112 | } 113 | } 114 | -------------------------------------------------------------------------------- /algorithms/searching and sorting/Cocktail_sort_c++.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | void cocktailSort(int arr[], int n){ 4 | bool flag = true; 5 | int start = 0, end = n-1; 6 | while(flag){ 7 | flag = false; 8 | for(int i = start; i arr[i+1]){ 10 | swap(arr[i], arr[i+1]); 11 | flag = true; 12 | } 13 | } 14 | if(!flag){ //if nothing has changed simply break the loop 15 | break; 16 | } 17 | flag = false; 18 | end--; //decrease the end pointer 19 | for(int i = end - 1; i >= start; i--){ //scan from right to left 20 | if(arr[i] > arr[i+1]){ 21 | swap(arr[i], arr[i+1]); 22 | flag = true; 23 | } 24 | } 25 | start++; 26 | } 27 | } 28 | main() { 29 | int data[] = {54, 74, 98, 154, 98, 32, 20, 13, 35, 40}; 30 | int n = sizeof(data)/sizeof(data[0]); 31 | cout << "Sorted Sequence "; 32 | cocktailSort(data, n); 33 | for(int i = 0; i 3 | using namespace std; 4 | 5 | /* Function to sort an array using insertion sort*/ 6 | void insertionSort(int arr[], int n) 7 | { 8 | int i, key, j; 9 | for (i = 1; i < n; i++) 10 | { 11 | key = arr[i]; 12 | j = i - 1; 13 | 14 | /* Move elements of arr[0..i-1], that are 15 | greater than key, to one position ahead 16 | of their current position */ 17 | while (j >= 0 && arr[j] > key) 18 | { 19 | arr[j + 1] = arr[j]; 20 | j = j - 1; 21 | } 22 | arr[j + 1] = key; 23 | } 24 | } 25 | 26 | // A utility function to print an array of size n 27 | void printArray(int arr[], int n) 28 | { 29 | int i; 30 | for (i = 0; i < n; i++) 31 | cout << arr[i] << " "; 32 | cout << endl; 33 | } 34 | 35 | /* Driver code */ 36 | int main() 37 | { 38 | int arr[] = { 12, 11, 13, 5, 6 }; 39 | int n = sizeof(arr) / sizeof(arr[0]); 40 | 41 | insertionSort(arr, n); 42 | printArray(arr, n); 43 | 44 | return 0; 45 | } -------------------------------------------------------------------------------- /algorithms/searching and sorting/MergeSort/Code.cpp: -------------------------------------------------------------------------------- 1 | #Merge Sort 2 | 3 | #include 4 | using namespace std; 5 | void swapping(int &a, int &b) { //swap the content of a and b 6 | int temp; 7 | temp = a; 8 | a = b; 9 | b = temp; 10 | } 11 | void display(int *array, int size) { 12 | for(int i = 0; i> n; 61 | int arr[n]; //create an array with given number of elements 62 | cout << "Enter elements:" << endl; 63 | for(int i = 0; i> arr[i]; 65 | } 66 | cout << "Array before Sorting: "; 67 | display(arr, n); 68 | mergeSort(arr, 0, n-1); //(n-1) for last index 69 | cout << "Array after Sorting: "; 70 | display(arr, n); 71 | } 72 | 73 | /* Output 74 | Enter the number of elements: 6 75 | Enter elements: 76 | 14 20 78 98 20 45 77 | Array before Sorting: 14 20 78 98 20 45 78 | Array after Sorting: 14 20 20 45 78 98 79 | */ 80 | -------------------------------------------------------------------------------- /algorithms/searching and sorting/MergeSort/Explanation-and-Algorithm.md: -------------------------------------------------------------------------------- 1 | The merge sort technique is based on divide and conquer technique. We divide the while data set into smaller parts and merge them into a larger piece in sorted order. It is also very effective for worst cases because this algorithm has lower time complexity for worst case also. 2 | 3 | The complexity of Merge Sort Technique 4 | Time Complexity: O(n log n) for all cases 5 | 6 | Space Complexity: O(n) 7 | 8 | 9 | Algorithm 10 | merge(array, left, middle, right) 11 | Input: The data set array, left, middle and right index 12 | 13 | Output: The merged list 14 | 15 | Begin 16 | nLeft := m - left+1 17 | nRight := right – m 18 | define arrays leftArr and rightArr of size nLeft and nRight respectively 19 | for i := 0 to nLeft do 20 | leftArr[i] := array[left +1] 21 | done 22 | for j := 0 to nRight do 23 | rightArr[j] := array[middle + j +1] 24 | done 25 | i := 0, j := 0, k := left 26 | while i < nLeft AND j < nRight do 27 | if leftArr[i] <= rightArr[j] then 28 | array[k] = leftArr[i] 29 | i := i+1 30 | else 31 | array[k] = rightArr[j] 32 | j := j+1 33 | k := k+1 34 | done 35 | while i < nLeft do 36 | array[k] := leftArr[i] 37 | i := i+1 38 | k := k+1 39 | done 40 | while j < nRight do 41 | array[k] := rightArr[j] 42 | j := j+1 43 | k := k+1 44 | done 45 | End 46 | -------------------------------------------------------------------------------- /algorithms/searching and sorting/Quick Sort/Quick Sort Code: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | void swap(int *a, int *b) { 7 | int temp; 8 | temp = *a; 9 | *a = *b; 10 | *b = temp; 11 | } 12 | 13 | int Partition(int a[], int l, int h) { 14 | int pivot, index, i; 15 | index = l; 16 | pivot = h; 17 | for(i = l; i < h; i++) { 18 | if(a[i] < a[pivot]) { 19 | swap(&a[i], &a[index]); 20 | index++; 21 | } 22 | } 23 | swap(&a[pivot], &a[index]); 24 | return index; 25 | } 26 | int PiviotPartition(int a[], int l, int h) { 27 | int pvt, n, temp; 28 | n = rand(); 29 | pvt = l + n%(h-l+1); 30 | swap(&a[h], &a[pvt]); 31 | return Partition(a, l, h); 32 | } 33 | int QuickSort(int a[], int l, int h) { 34 | int pindex; 35 | if(l < h) { 36 | pindex = PiviotPartition(a, l, h); 37 | QuickSort(a, l, pindex-1); 38 | QuickSort(a, pindex+1, h); 39 | } 40 | return 0; 41 | } 42 | int main() { 43 | int n, i; 44 | cout<<"\nEnter the number of elements: "; 45 | cin>>n; 46 | int arr[n]; 47 | cout<<"Enter elements: "; 48 | for(i = 0; i < n; i++) { 49 | cin>>arr[i]; 50 | } 51 | QuickSort(arr, 0, n-1); 52 | cout<<"\nSorted Data "; 53 | for (i = 0; i < n; i++) 54 | cout<<" "< 2 | #include 3 | #include 4 | #include 5 | using namespace std; 6 | void radixsort(int a[], int n) 7 | { 8 | int count[10]; 9 | int output[n]; 10 | memset(output, 0, sizeof(output)); 11 | memset(count, 0, sizeof(count)); 12 | int max = 0; 13 | for (int i = 0; i < n; ++i) 14 | { 15 | if (a[i] > max) 16 | { 17 | max = a[i]; 18 | } 19 | } 20 | int maxdigits = 0; 21 | while (max) 22 | { 23 | maxdigits++; 24 | max /= 10; 25 | } 26 | for (int j = 0; j < maxdigits; j++) 27 | { 28 | for (int i = 0; i < n; i++) 29 | { 30 | int t = pow(10, j); 31 | count[(a[i] % (10 * t)) / t]++; 32 | } 33 | int k = 0; 34 | for (int p = 0; p < 10; p++) 35 | { 36 | for (int i = 0; i < n; i++) 37 | { 38 | int t = pow(10, j); 39 | if ((a[i] % (10 * t)) / t == p) 40 | { 41 | output[k] = a[i]; 42 | k++; 43 | } 44 | } 45 | } 46 | memset(count, 0, sizeof(count)); 47 | for (int i = 0; i < n; ++i) 48 | { 49 | a[i] = output[i]; 50 | } 51 | } 52 | } 53 | void print(int a[], int n) 54 | { 55 | for (int i = 0; i < n; ++i) 56 | { 57 | cout << a[i] << " "; 58 | } 59 | cout << endl; 60 | } 61 | int main(int argc, char const *argv[]) 62 | { 63 | int a[] = {170, 45, 75, 90, 802, 24, 2, 66}; 64 | int n = sizeof(a) / sizeof(a[0]); 65 | radixsort(a, n); 66 | print(a, n); 67 | return 0; 68 | } -------------------------------------------------------------------------------- /algorithms/searching and sorting/Selection Sort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | void selectionSort(int n ,int array[]){ 4 | for(int i=0;iarray[max]){ 8 | max=j; 9 | } 10 | } 11 | int temp = array[max]; 12 | array[max]=array[n-1-i]; 13 | array[n-1-i]=temp; 14 | } 15 | } 16 | void display(int n,int array []){ 17 | cout<<"The sorted array is "; 18 | for(int i = 0 ; i>size; //taking size of the array 26 | int array[size]; 27 | cout<<"Enter elements of the array"<>array[i]; 30 | } 31 | selectionSort(size,array); 32 | display(size,array); 33 | return 0; 34 | } 35 | -------------------------------------------------------------------------------- /algorithms/searching and sorting/Shell Sort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | int size = 10; 7 | int array[size]; 8 | // Input 9 | cout << "\nHow many numbers do want to enter in unsorted array : "; 10 | cin >> size; 11 | cout << "\nEnter the numbers for unsorted array : "; 12 | for (int i = 0; i < size; i++) 13 | { 14 | cin >> array[i]; 15 | } 16 | 17 | // Sorting 18 | for (int i = size / 2; i > 0; i = i / 2) 19 | { 20 | for (int j = i; j < size; j++) 21 | { 22 | for (int k = j - i; k >= 0; k = k - i) 23 | { 24 | if (array[k] < array[k + i]) 25 | { 26 | break; 27 | } 28 | else 29 | { 30 | int temp = array[k + i]; 31 | array[k + i] = array[k]; 32 | array[k] = temp; 33 | } 34 | } 35 | } 36 | } 37 | 38 | // Output 39 | cout << "\nSorted array : "; 40 | for (int i = 0; i < size; ++i) 41 | { 42 | cout << array[i] << "\t"; 43 | } 44 | return 0; 45 | } 46 | -------------------------------------------------------------------------------- /algorithms/searching and sorting/binary search/BinarySearch.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int BinarySearch(int a[],int n,int data){ 6 | int l,r; 7 | int mid=0; 8 | l = 0; 9 | r = n -1; 10 | while(l < r){ 11 | mid = (l + r)/2; 12 | if(data == a[mid]) 13 | return mid; 14 | else if(data < a[mid]) 15 | r = mid - 1; 16 | else 17 | l = mid + 1; 18 | } 19 | return -1; 20 | } 21 | 22 | int main(){ 23 | int arraySize, data, result; 24 | cout<<"\nEnter Array Size :- "; 25 | cin>>arraySize; 26 | int a[arraySize]; 27 | cout<<"\nEnter Array Elements :- "; 28 | for(int i = 0; i < arraySize; i++){ 29 | cin>>a[i]; 30 | } 31 | cout<<"\nYour Array elements are :- \n"; 32 | for(int i = 0; i < arraySize; i++){ 33 | cout<<" "<>data; 38 | result = BinarySearch(a,arraySize,data); 39 | cout<<"\n"< 3 | using namespace std; 4 | 5 | // class for storing functions and variables for performing binary search operations - 6 | class binarySearch { 7 | public: 8 | int arr[50], i, n, left, right, mid, key; 9 | // function to get elements from the user - 10 | void get_element() { 11 | cout << "Enter the number of elements: "; 12 | cin >> n; 13 | for (i = 0; i < n; i++) { 14 | cout << "Enter number: "; 15 | cin >> arr[i]; 16 | } 17 | cout << "Enter the element that you want to search: "; 18 | cin >> key; 19 | } 20 | // function to find element using binary search - 21 | void find() { 22 | left = 0; // position of leftmost element initially 23 | right = n - 1; // position of rightmost element initially 24 | mid = (left + right)/2; // position of middle element initially 25 | while (left <= right) { 26 | if (arr[mid] < key) { 27 | left = mid + 1; 28 | } 29 | else if (arr[mid] == key) { 30 | cout << "Number found at index: " << mid << endl; 31 | break; 32 | } 33 | else { 34 | right = mid - 1; 35 | } 36 | mid = (left + right)/2; 37 | } 38 | if (left > right) { 39 | cout << "Number not found in array."; 40 | } 41 | } 42 | }; 43 | 44 | int main() { 45 | binarySearch b; 46 | b.get_element(); 47 | b.find(); 48 | } -------------------------------------------------------------------------------- /algorithms/searching and sorting/bubble sort/README.md: -------------------------------------------------------------------------------- 1 | # Bubble Sort (aka Sinking Sort) 2 | 3 | ## What is bubble sort? 4 | Bubble sort is the easiest way of sorting elements in an array. It traverses the array, compares the adjacent elements, and swaps them if they are in the wrong order. 5 | 6 | ## What is the algorithm for bubble sort? 7 | Let's consider that we want to sort some elements in an array in ascending order. 8 | - Step 1: Start with the element at the first position (0th index). Compare it with the element at the second position (1st index). If first element is greater than the second element, swap them. 9 | - Step 2: Repeat step 1 until end of the array is encountered. 10 | - Step 3: Repeat the same procedure for the remaining iterations until the array is sorted. 11 | 12 | ## Features of bubble sort 13 | - Very simple 14 | - Not very efficient on a large group of elements -------------------------------------------------------------------------------- /algorithms/searching and sorting/bubble sort/bubble_sort.cpp: -------------------------------------------------------------------------------- 1 | // Program to implement bubble sort in C++ 2 | #include 3 | using namespace std; 4 | 5 | // class to store functions and variables for performing bubble sort - 6 | class bubbleSort { 7 | public: 8 | int i, j, n, temp, arr[20]; 9 | void get_elements(); // function to get elements from the user 10 | void sort(); // function to sort elements using bubble sort 11 | void display(); // function to display sorted elements 12 | }; 13 | 14 | void bubbleSort :: get_elements() { 15 | cout << "Enter the number of elements: "; 16 | cin >> n; 17 | for (i = 0; i < n; i++) { 18 | cout << "Enter number: "; 19 | cin >> arr[i]; 20 | } 21 | } 22 | 23 | void bubbleSort :: sort() { 24 | for (i = 0; i < n; i++) { 25 | for (j = i + 1; j < n; j++) { 26 | if (arr[j] < arr[i]) { 27 | temp = arr[i]; 28 | arr[i] = arr[j]; 29 | arr[j] = temp; 30 | } 31 | } 32 | } 33 | } 34 | 35 | void bubbleSort :: display() { 36 | cout << "Displaying sorted elements: " << endl; 37 | for (i = 0; i < n; i++) { 38 | cout << arr[i] << " "; 39 | } 40 | } 41 | 42 | int main() { 43 | bubbleSort b; 44 | b.get_elements(); 45 | b.sort(); 46 | b.display(); 47 | } -------------------------------------------------------------------------------- /algorithms/searching and sorting/bucketSort.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to sort an array using bucket sort 2 | #include 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | // Function to sort arr[] of size n using bucket sort 8 | void bucketSort(float arr[], int n) 9 | { 10 | // 1) Create n empty buckets 11 | vector b[n]; 12 | 13 | // 2) Put array elements in different buckets 14 | for (int i = 0; i < n; i++) 15 | { 16 | int bi = n * arr[i]; // Index in bucket 17 | b[bi].push_back(arr[i]); 18 | } 19 | 20 | // 3) Sort individual buckets 21 | for (int i = 0; i < n; i++) 22 | sort(b[i].begin(), b[i].end()); 23 | 24 | // 4) Concatenate all buckets into arr[] 25 | int index = 0; 26 | for (int i = 0; i < n; i++) 27 | for (int j = 0; j < b[i].size(); j++) 28 | arr[index++] = b[i][j]; 29 | } 30 | 31 | /* Driver program to test above funtion */ 32 | int main() 33 | { 34 | float arr[] = {0.897, 0.565, 0.656, 0.1234, 0.665, 0.3434}; 35 | int n = sizeof(arr) / sizeof(arr[0]); 36 | bucketSort(arr, n); 37 | 38 | cout << "Sorted array is \n"; 39 | for (int i = 0; i < n; i++) 40 | cout << arr[i] << " "; 41 | return 0; 42 | } 43 | -------------------------------------------------------------------------------- /algorithms/searching and sorting/counting_sort.cpp: -------------------------------------------------------------------------------- 1 | // COUNTING SORT ALGORITHM 2 | //Contribued by : Pooja Singh 3 | 4 | #include 5 | using namespace std; 6 | typedef long long int ll; 7 | #define FAST ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL); 8 | #define t_ime auto end = chrono::steady_clock::now(); auto diff = end - start; 9 | #define t_time cout << chrono::duration (diff).count() << " ms" << endl; 10 | #define clk auto start = chrono::steady_clock::now(); 11 | #define MOD 1000000007 12 | #define mp make_pair 13 | #define pb push_back 14 | #define f first 15 | #define s second 16 | #define ln "\n" 17 | #define min_heap priority_queue,greater> //min top 18 | #define max_heap priority_queue //max top 19 | #define vpair vector> 20 | const ll dx[4] = {1, 0, -1, 0}; 21 | const ll dy[4] = {0, 1, 0, -1}; 22 | 23 | int main() 24 | { 25 | FAST; 26 | 27 | ll t; 28 | t=1; 29 | clk; 30 | ll count[1001]={0}; 31 | 32 | ll n; 33 | cin>>n; //number of elements 34 | ll a[n]; 35 | ll b[n]; 36 | cout<<"Enter array elements between 1 to 1000"<>a[i]; 40 | b[i]=a[i]; //copy of array 41 | count[a[i]]++; //store frequency of elements 42 | } 43 | sort(b,b+n); //sort copied array to get maximum elemnet of array 44 | 45 | ll max=b[n-1]; //maximum among all the given elements 46 | 47 | ll output[n] ; //create temp array to store output 48 | 49 | // Store the cummulative count of each array 50 | for (ll i = 1; i <= max; i++) 51 | { 52 | count[i] += count[i - 1]; 53 | } 54 | 55 | 56 | for (ll i =n- 1;i >= 0;i--) 57 | { 58 | output[count[a[i]] - 1] = a[i]; 59 | count[a[i]]--; 60 | } 61 | 62 | cout<<"ARRYA AFTER SORTING"< 2 | #include 3 | 4 | void heapify(int *a, int i, int n) { 5 | int largest = i; 6 | const int l = 2 * i + 1; 7 | const int r = 2 * i + 2; 8 | 9 | if (l < n && a[l] > a[largest]) 10 | largest = l; 11 | 12 | if (r < n && a[r] > a[largest]) 13 | largest = r; 14 | 15 | if (largest != i) { 16 | std::swap(a[i], a[largest]); 17 | heapify(a, n, largest); 18 | } 19 | } 20 | 21 | void heapsort(int *a, int n) { 22 | for (int i = n - 1; i >= 0; --i) { 23 | std::swap(a[0], a[i]); 24 | heapify(a, 0, i); 25 | } 26 | } 27 | 28 | void build_maxheap(int *a, int n) { 29 | for (int i = n / 2 - 1; i >= 0; --i) { 30 | heapify(a, i, n); 31 | } 32 | } 33 | 34 | int main() { 35 | int n; 36 | std::cout << "Enter number of elements of array\n"; 37 | std::cin >> n; 38 | int a[20]; 39 | for (int i = 0; i < n; ++i) { 40 | std::cout << "Enter Element " << i << std::endl; 41 | std::cin >> a[i]; 42 | } 43 | 44 | build_maxheap(a, n); 45 | heapsort(a, n); 46 | std::cout << "Sorted Output\n"; 47 | for (int i = 0; i < n; ++i) { 48 | std::cout << a[i] << std::endl; 49 | } 50 | 51 | std::getchar(); 52 | } 53 | -------------------------------------------------------------------------------- /algorithms/searching and sorting/linear search/LinearSearch.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int main(){ 6 | int arraySize, data,j; 7 | cout<<"\nEnter Array Size :- "; 8 | cin>>arraySize; 9 | int a[arraySize]; 10 | cout<<"\nEnter Array Elements :- "; 11 | for(int i = 0; i < arraySize; i++){ 12 | cin>>a[i]; 13 | } 14 | cout<<"\nYour Array elements are :- \n"; 15 | for(int i = 0; i < arraySize; i++){ 16 | cout<<" "<>data; 21 | for(j = 0; j < arraySize; j++){ 22 | if(a[j] == data){ 23 | cout<<"\nElement found at index :- "< 3 | using namespace std; 4 | 5 | // class for storing functions and variables to perform linear search - 6 | class linearSearch { 7 | public: 8 | int arr[50], i, key, n; 9 | // function to get elements - 10 | void get_element() { 11 | cout << "Enter number of elements: "; 12 | cin >> n; 13 | for (i = 0; i < n; i++) { 14 | cout << "Enter element: "; 15 | cin >> arr[i]; 16 | } 17 | } 18 | // function to find element from the array using linear search - 19 | void find() { 20 | cout << "Enter the number which is to be searched: "; 21 | cin >> key; 22 | for (i = 0; i < n; i++) { 23 | // check if element in the array is equal to the element which the user wants to search for - 24 | if (arr[i] == key) { 25 | cout << "Number found at index: " << i << endl; 26 | break; 27 | } 28 | } 29 | // if array is completely done traversing through - 30 | if (i == n) { 31 | cout << "Number not found in array." << endl; 32 | } 33 | } 34 | }; 35 | 36 | int main() { 37 | linearSearch l; 38 | l.get_element(); 39 | l.find(); 40 | } 41 | -------------------------------------------------------------------------------- /algorithms/searching and sorting/merge sort/README.md: -------------------------------------------------------------------------------- 1 | # Merge Sort 2 | 3 | ## What is merge sort? 4 | Merge sort is a sorting algorithm based on the Divide and conquer strategy. It works by recursively dividing the array into two equal halves, then sort them and combine them. 5 | It takes a time of (n logn) in the worst case. 6 | 7 | ## Features of binary search 8 | -Merge Sort is useful for sorting linked lists. 9 | -Merge Sort is a stable sort which means that the same element in an array maintain their original positions with respect to each other. 10 | -Overall time complexity of Merge sort is O(nLogn). It is more efficient as it is in worst case also the runtime is O(nlogn) 11 | -The space complexity of Merge sort is O(n). This means that this algorithm takes a lot of space and may slower down operations for the last data sets. 12 | -------------------------------------------------------------------------------- /algorithms/searching and sorting/merge sort/merge sort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | void swapping(int &a, int &b) { //swap the content of a and b 4 | int temp; 5 | temp = a; 6 | a = b; 7 | b = temp; 8 | } 9 | void display(int *array, int size) { 10 | for(int i = 0; i> n; 59 | int arr[n]; //create an array with given number of elements 60 | cout << "Enter elements:" << endl; 61 | for(int i = 0; i> arr[i]; 63 | } 64 | cout << "Array before Sorting: "; 65 | display(arr, n); 66 | mergeSort(arr, 0, n-1); //(n-1) for last index 67 | cout << "Array after Sorting: "; 68 | display(arr, n); 69 | } 70 | 71 | 72 | -------------------------------------------------------------------------------- /data structures/graphs/BFS_DFS_traversal.cpp: -------------------------------------------------------------------------------- 1 | //BFS traversal:Breadth-first search also reffered as level order traversal. 2 | //BFS is a traversal technique in which all the nodes of the same level are explored first, and then we move to the next level. 3 | 4 | //DFS traversal: Depth first search. 5 | //DFS is also a traversal technique in which traversal is started from the root node and explore the nodes as far as possible 6 | //until we reach the node that has no unvisited adjacent nodes. 7 | 8 | 9 | #include 10 | #include 11 | using namespace std; 12 | 13 | void printdfs(int **edges,int n, int sv, bool*visited) 14 | { 15 | cout<vertices; 40 | vertices.push(sv); 41 | visited[sv]=true; 42 | while(vertices.size()!=0) 43 | { 44 | int front=vertices.front(); 45 | cout<>n>>e; 77 | 78 | int **edges =new int* [n]; 79 | for(int i=0; i>f >> s; 91 | edges[f][s]=1; 92 | edges[s][f]=1; 93 | 94 | } 95 | 96 | bool *visited=new bool[n]; 97 | for(int i=0;i 3 | 4 | // Struct for the edges of the graph 5 | struct Edge { 6 | int u; //start vertex of the edge 7 | int v; //end vertex of the edge 8 | int w; //w of the edge (u,v) 9 | }; 10 | 11 | // Graph - it consists of edges 12 | struct Graph { 13 | int V; // Total number of vertices in the graph 14 | int E; // Total number of edges in the graph 15 | struct Edge* edge; // Array of edges 16 | }; 17 | 18 | // Creates a graph with V vertices and E edges 19 | struct Graph* createGraph(int V, int E) { 20 | struct Graph* graph = new Graph; 21 | graph->V = V; // Total Vertices 22 | graph->E = E; // Total edges 23 | 24 | // Array of edges for graph 25 | graph->edge = new Edge[E]; 26 | return graph; 27 | } 28 | 29 | // Printing the solution 30 | void printArr(int arr[], int size) { 31 | int i; 32 | for (i = 0; i < size; i++) { 33 | printf("%d ", arr[i]); 34 | } 35 | printf("\n"); 36 | } 37 | 38 | void BellmanFord(struct Graph* graph, int u) { 39 | int V = graph->V; 40 | int E = graph->E; 41 | int dist[V]; 42 | 43 | // Step 1: fill the distance array and predecessor array 44 | for (int i = 0; i < V; i++) 45 | dist[i] = INT_MAX; 46 | 47 | // Mark the source vertex 48 | dist[u] = 0; 49 | 50 | // Step 2: relax edges |V| - 1 times 51 | for (int i = 1; i <= V - 1; i++) { 52 | for (int j = 0; j < E; j++) { 53 | // Get the edge data 54 | int u = graph->edge[j].u; 55 | int v = graph->edge[j].v; 56 | int w = graph->edge[j].w; 57 | if (dist[u] != INT_MAX && dist[u] + w < dist[v]) 58 | dist[v] = dist[u] + w; 59 | } 60 | } 61 | 62 | // Step 3: detect negative cycle 63 | // if value changes then we have a negative cycle in the graph 64 | // and we cannot find the shortest distances 65 | for (int i = 0; i < E; i++) { 66 | int u = graph->edge[i].u; 67 | int v = graph->edge[i].v; 68 | int w = graph->edge[i].w; 69 | if (dist[u] != INT_MAX && dist[u] + w < dist[v]) { 70 | printf("Graph contains negative w cycle"); 71 | return; 72 | } 73 | } 74 | 75 | // No negative weight cycle found! 76 | // Print the distance and predecessor array 77 | printArr(dist, V); 78 | 79 | return; 80 | } 81 | 82 | int main() { 83 | // Create a graph 84 | int V = 5; // Total vertices 85 | int E = 8; // Total edges 86 | 87 | // Array of edges for graph 88 | struct Graph* graph = createGraph(V, E); 89 | 90 | //------- adding the edges of the graph 91 | /* 92 | edge(u, v) 93 | where u = start vertex of the edge (u,v) 94 | v = end vertex of the edge (u,v) 95 | 96 | w is the weight of the edge (u,v) 97 | */ 98 | 99 | //edge 0 --> 1 100 | graph->edge[0].u = 0; 101 | graph->edge[0].v = 1; 102 | graph->edge[0].w = 5; 103 | 104 | //edge 0 --> 2 105 | graph->edge[1].u = 0; 106 | graph->edge[1].v = 2; 107 | graph->edge[1].w = 4; 108 | 109 | //edge 1 --> 3 110 | graph->edge[2].u = 1; 111 | graph->edge[2].v = 3; 112 | graph->edge[2].w = 3; 113 | 114 | //edge 2 --> 1 115 | graph->edge[3].u = 2; 116 | graph->edge[3].v = 1; 117 | graph->edge[3].w = 6; 118 | 119 | //edge 3 --> 2 120 | graph->edge[4].u = 3; 121 | graph->edge[4].v = 2; 122 | graph->edge[4].w = 2; 123 | 124 | BellmanFord(graph, 0); //0 is the source vertex 125 | 126 | return 0; 127 | } 128 | -------------------------------------------------------------------------------- /data structures/graphs/Dijkstras_algo.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | The graph is a non-linear data structure that involves nodes and edges 3 | Dijkstra’s algorithm is also known as the shortest path algorithm. It is an algorithm used to find the shortest path between nodes of the graph. 4 | The algorithm creates the tree of the shortest paths from the starting source vertex from all other points in the graph. 5 | It differs from the minimum spanning tree as the shortest distance between two vertices may not be included in all the vertices of the graph. 6 | The algorithm works by building a set of nodes that have a minimum distance from the source. 7 | Here, Dijkstra's algorithm uses a greedy approach. 8 | 9 | */ 10 | 11 | 12 | #include 13 | #include 14 | using namespace std; 15 | 16 | int miniDist(int distance[], bool Tset[]) // finding minimum distance 17 | { 18 | int minimum=INT_MAX,ind; 19 | 20 | for(int k=0;k<6;k++) 21 | { 22 | if(Tset[k]==false && distance[k]<=minimum) 23 | { 24 | minimum=distance[k]; 25 | ind=k; 26 | } 27 | } 28 | return ind; 29 | } 30 | 31 | void DijkstraAlgo(int graph[6][6],int src) // adjacency matrix 32 | { 33 | int distance[6]; // // array to calculate the minimum distance for each node 34 | bool Tset[6];// boolean array to mark visited and unvisited for each node 35 | 36 | 37 | for(int k = 0; k<6; k++) 38 | { 39 | distance[k] = INT_MAX; 40 | Tset[k] = false; 41 | } 42 | 43 | distance[src] = 0; // Source vertex distance is set 0 44 | 45 | for(int k = 0; k<6; k++) 46 | { 47 | int m=miniDist(distance,Tset); 48 | Tset[m]=true; 49 | for(int k = 0; k<6; k++) 50 | { 51 | // updating the distance of neighbouring vertex 52 | if(!Tset[k] && graph[m][k] && distance[m]!=INT_MAX && distance[m]+graph[m][k] 3 | using namespace std; 4 | 5 | // defining the number of vertices 6 | #define nV 4 7 | 8 | #define INF 999 9 | 10 | void printMatrix(int matrix[][nV]); 11 | 12 | // Implementing floyd warshall algorithm 13 | void floydWarshall(int graph[][nV]) { 14 | int matrix[nV][nV], i, j, k; 15 | 16 | for (i = 0; i < nV; i++) 17 | for (j = 0; j < nV; j++) 18 | matrix[i][j] = graph[i][j]; 19 | 20 | // Adding vertices individually 21 | for (k = 0; k < nV; k++) { 22 | for (i = 0; i < nV; i++) { 23 | for (j = 0; j < nV; j++) { 24 | if (matrix[i][k] + matrix[k][j] < matrix[i][j]) 25 | matrix[i][j] = matrix[i][k] + matrix[k][j]; 26 | } 27 | } 28 | } 29 | printMatrix(matrix); 30 | } 31 | 32 | void printMatrix(int matrix[][nV]) { 33 | for (int i = 0; i < nV; i++) { 34 | for (int j = 0; j < nV; j++) { 35 | if (matrix[i][j] == INF) 36 | printf("%4s", "INF"); 37 | else 38 | printf("%4d", matrix[i][j]); 39 | } 40 | printf("\n"); 41 | } 42 | } 43 | 44 | int main() { 45 | int graph[nV][nV] = {{0, 3, INF, 5}, 46 | {2, 0, INF, 4}, 47 | {INF, 1, 0, INF}, 48 | {INF, INF, 2, 0}}; 49 | floydWarshall(graph); 50 | } 51 | -------------------------------------------------------------------------------- /data structures/graphs/ReadMe.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PrajaktaSathe/CPP/314882bf55fe1eb7c34c97359391f08273135cca/data structures/graphs/ReadMe.md -------------------------------------------------------------------------------- /data structures/graphs/kruskals_algo.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | A spanning tree is a tree that connects all the vertices of a graph with the minimum possible number of edges. 3 | The cost of the spanning tree is the sum of the weights of all the edges in the tree.Of all the possible spanning trees 4 | the one with the minimum cost is said to be minimum cost spanning tree. 5 | The main objective of using Kruskal’s algorithm is for getting the minimum cost spanning tree for a graph. 6 | 7 | */ 8 | 9 | 10 | #include 11 | #include 12 | #include 13 | 14 | using namespace std; 15 | const int MAX = 1e6-1; 16 | int root[MAX]; 17 | const int nodes = 4, edges = 5; 18 | pair > p[MAX]; 19 | 20 | int parent(int a) //find the parent of the given node 21 | { 22 | while(root[a] != a) 23 | { 24 | root[a] = root[root[a]]; 25 | a = root[a]; 26 | } 27 | return a; 28 | } 29 | 30 | void union_find(int a, int b) //check if the given two vertices are in the same “union” or not 31 | { 32 | int d = parent(a); 33 | int e = parent(b); 34 | root[d] = root[e]; 35 | } 36 | 37 | long long kruskal() 38 | { 39 | int a, b; 40 | long long cost, minCost = 0; 41 | for(int i = 0 ; i < edges ; ++i) 42 | { 43 | a = p[i].second.first; 44 | b = p[i].second.second; 45 | cost = p[i].first; 46 | if(parent(a) != parent(b)) //only select edge if it does not create a cycle (ie the two nodes forming it have different root nodes) 47 | { 48 | minCost += cost; 49 | union_find(a, b); 50 | } 51 | } 52 | return minCost; 53 | } 54 | 55 | int main() 56 | { 57 | int x, y; 58 | long long weight, cost, minCost; 59 | for(int i = 0;i < MAX;++i) //initialize the array groups 60 | { 61 | root[i] = i; 62 | } 63 | p[0] = make_pair(10, make_pair(0, 1)); 64 | p[1] = make_pair(18, make_pair(1, 2)); 65 | p[2] = make_pair(13, make_pair(2, 3)); 66 | p[3] = make_pair(21, make_pair(0, 2)); 67 | p[4] = make_pair(22, make_pair(1, 3)); 68 | sort(p, p + edges); //sort the array of edges 69 | minCost = kruskal(); 70 | cout << "Minimum cost is: "<< minCost << endl; 71 | return 0; 72 | } -------------------------------------------------------------------------------- /data structures/graphs/prims_algo.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Prim’s algorithm is a minimum spanning tree algorithm which helps to find out the 3 | edges of the graph to form the tree including every node with the minimum sum of weights 4 | to form the minimum spanning tree. 5 | 6 | */ 7 | #include 8 | using namespace std; 9 | 10 | // Number of vertices in the graph 11 | #define V 5 12 | 13 | 14 | int minKey(int key[], bool mstSet[]) 15 | { 16 | // Initialize min value 17 | int min = INT_MAX, min_index; 18 | 19 | for (int v = 0; v < V; v++) 20 | if (mstSet[v] == false && key[v] < min) 21 | min = key[v], min_index = v; 22 | 23 | return min_index; 24 | } 25 | 26 | 27 | void printMST(int parent[], int graph[V][V]) 28 | { 29 | cout<<"Edge \tWeight\n"; 30 | for (int i = 1; i < V; i++) 31 | cout< 2 | #include 3 | using namespace std; 4 | struct node 5 | { 6 | int data; 7 | struct node *link; 8 | }; 9 | struct node* root = NULL; 10 | void append() 11 | { 12 | int ele; 13 | struct node *temp; 14 | temp = (struct node*)malloc(sizeof(struct node)); 15 | cout<<"Enter element :- "; 16 | cin>>ele; 17 | temp -> data = ele; 18 | temp ->link = NULL; 19 | if(root == NULL) 20 | { 21 | root = temp; 22 | } 23 | else 24 | { 25 | struct node *p; 26 | p = root; 27 | while(p->link != NULL) 28 | { 29 | p = p -> link; 30 | } 31 | p -> link = temp; 32 | } 33 | } 34 | void length() 35 | { 36 | int count = 0; 37 | struct node *temp; 38 | temp = root; 39 | while(temp != NULL) 40 | { 41 | count = count + 1; 42 | temp = temp -> link; 43 | } 44 | cout<<"Length is :- "<>ele; 53 | temp -> data = ele; 54 | temp -> link = root; 55 | root = temp; 56 | } 57 | void display() 58 | { 59 | struct node* p; 60 | p = root; 61 | if(root == NULL) 62 | { 63 | cout<<"No elements"; 64 | } 65 | else 66 | { 67 | while(p != NULL) 68 | { 69 | cout<

data<<" "; 70 | p = p -> link; 71 | } 72 | } 73 | } 74 | void atMiddle() 75 | { 76 | int data, findEle; 77 | struct node *temp, *p, *q;; 78 | temp = (struct node*)malloc(sizeof(struct node)); 79 | cout<<"Enter data :- "; 80 | cin>>data; 81 | temp -> data = data; 82 | p = root; 83 | cout<<"Enter element after which you want to insert :- "; 84 | cin>>findEle; 85 | while(p -> data != findEle) 86 | { 87 | p = p -> link; 88 | } 89 | q = p -> link; 90 | temp -> link = q; 91 | p -> link = temp; 92 | cout<>choice; 102 | switch(choice) 103 | { 104 | case 1: append(); break; 105 | case 2: length(); break; 106 | case 3: inFirst(); break; 107 | case 4: display(); break; 108 | case 5: atMiddle(); break; 109 | case 6: exit(0); 110 | default: cout<<"Wrong input"; 111 | } 112 | }while(choice != 6); 113 | getch(); 114 | } 115 | -------------------------------------------------------------------------------- /data structures/linked lists/linked_lists.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // class for individual node (you can also use struct) 5 | class node { 6 | public: 7 | int data; // to store information/element 8 | node *next; // points to the location of the next element 9 | }; 10 | 11 | // class for performing operations on linked list - 12 | class linked_list { 13 | public: 14 | node *head, *tail; // creating head and tail nodes 15 | // constructor which initializes an empty linked list 16 | linked_list() { 17 | // both head and tail are initialized to null pointer, since both lead to nowhere 18 | head = nullptr; 19 | tail = nullptr; 20 | } 21 | void add_node(int); // function to add node 22 | void display(); // function to display linked list elements 23 | void delete_node(int); // function to delete elements of the linked list 24 | }; 25 | 26 | void linked_list :: add_node(int key) { 27 | node *temp = new node; // create temp node 28 | temp -> data = key; 29 | temp -> next = nullptr; 30 | if (head == nullptr) { 31 | head = temp; 32 | tail = temp; 33 | } 34 | else { 35 | tail -> next = temp; 36 | tail = tail -> next; 37 | } 38 | cout << key << " added to linked list!" << endl; 39 | } 40 | 41 | void linked_list :: display() { 42 | struct node *n; 43 | if (head == nullptr) { 44 | cout << "Linked list is empty!" << endl; 45 | } 46 | else { 47 | n = head; 48 | while (n != nullptr) { 49 | cout << n -> data << " "; 50 | n = n -> next; 51 | } 52 | } 53 | } 54 | 55 | void linked_list :: delete_node(int d) { 56 | if (head == nullptr) { 57 | cout << "Linked list is empty!" << endl; 58 | } 59 | else { 60 | node *temp = head; 61 | if (temp -> data == d) { 62 | temp = temp -> next; 63 | head = temp; 64 | return; 65 | } 66 | while (temp) { 67 | if (temp -> data == d) { 68 | temp -> data = temp -> next -> data; 69 | temp -> next = temp -> next -> next; 70 | break; 71 | } 72 | temp = temp -> next; 73 | } 74 | cout << endl << d << " is deleted from the linked list!" << endl; 75 | } 76 | } 77 | 78 | int main() 79 | { 80 | linked_list l; 81 | l.add_node(3); 82 | l.add_node(10); 83 | l.add_node(20); 84 | l.add_node(30); 85 | l.display(); 86 | l.delete_node(20); 87 | l.display(); 88 | return 0; 89 | } 90 | -------------------------------------------------------------------------------- /data structures/linked lists/reverseLL.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | struct Node 5 | { 6 | int data; 7 | struct Node* next; 8 | Node (int data) 9 | { 10 | this->data = data; 11 | next = NULL; 12 | } 13 | }; 14 | 15 | struct LinkedList 16 | { 17 | Node *head; 18 | LinkedList() 19 | { 20 | head = NULL; 21 | } 22 | 23 | 24 | /* reverse the linked list */ 25 | void reverse() 26 | { 27 | // Initialize current, previous and 28 | // next pointers 29 | Node *current = head; 30 | Node *prev = NULL, *next = NULL; 31 | 32 | 33 | while (current != NULL) 34 | { 35 | // Store next 36 | next = current->next; 37 | 38 | // Reverse current node's pointer 39 | current->next = prev; 40 | 41 | // Move pointers one position ahead. 42 | prev = current; 43 | current = next; 44 | } 45 | head = prev; 46 | } 47 | 48 | /* print linked list */ 49 | void print() 50 | { 51 | struct Node *temp = head; 52 | while (temp != NULL) 53 | { 54 | cout << temp->data << " "; 55 | temp = temp->next; 56 | } 57 | } 58 | 59 | void push(int data) 60 | { 61 | Node *temp = new Node(data); 62 | temp->next = head; 63 | head = temp; 64 | } 65 | }; 66 | 67 | int main() 68 | { 69 | 70 | LinkedList ll; 71 | ll.push(20); 72 | ll.push(4); 73 | ll.push(15); 74 | ll.push(85); 75 | 76 | cout << "Given linked list 77 | "; 78 | ll.print(); 79 | 80 | ll.reverse(); 81 | 82 | cout << " 83 | Reversed Linked list 84 | "; 85 | ll.print(); 86 | return 0; 87 | } -------------------------------------------------------------------------------- /data structures/linked lists/searching.cpp: -------------------------------------------------------------------------------- 1 | //this program searches a linked list 2 | // by traversing the whole linked list through iteration 3 | 4 | #include 5 | using namespace std; 6 | class node 7 | { 8 | public: 9 | int data; 10 | node *next; 11 | }; 12 | 13 | // Utility function 14 | // it inserts nodes at the back of the linked list 15 | 16 | void push_back(node *&head, int val) 17 | { 18 | node* newnode=new node; 19 | node* temp=head; 20 | newnode->data= val; 21 | newnode->next=NULL; 22 | if(head==NULL) 23 | { 24 | head=newnode; 25 | return; 26 | } 27 | while(temp->next!=NULL) 28 | { 29 | temp=temp->next; 30 | } 31 | temp->next=newnode; 32 | return; 33 | } 34 | 35 | // display the linked list 36 | 37 | void display(node *& head) 38 | { 39 | node* temp=head; 40 | while(temp->next!=NULL) 41 | { 42 | cout<data<<"->"; 43 | temp=temp->next; 44 | } 45 | if(temp->next==NULL) 46 | cout<data<<"->NULL"; 47 | } 48 | 49 | // search function to search val 50 | 51 | void searching(node *&head , int val) 52 | { 53 | node* temp=head; 54 | bool flag=1; 55 | while(temp->data!=val) 56 | { 57 | temp=temp->next; 58 | if(temp==NULL) 59 | { 60 | flag=0; 61 | break; 62 | } 63 | } 64 | if(flag==1) 65 | cout<<"ELEMENT FOUND"; 66 | else 67 | cout<<"ELEMENT NOT FOUND"; 68 | } 69 | 70 | //Driver code 71 | 72 | int main() 73 | { 74 | node * llist=NULL; 75 | int n; 76 | cout<<"Enter size:"; 77 | cin>>n; 78 | cout<<"Enter elements:"; 79 | for(int i=0;i>v; 83 | push_back(llist, v); 84 | } 85 | display(llist); 86 | int k; 87 | cout<<"\nEnter number to search:"; 88 | cin>>k; 89 | searching(llist,k); 90 | } 91 | 92 | 93 | 94 | -------------------------------------------------------------------------------- /data structures/queues/README.md: -------------------------------------------------------------------------------- 1 | # Queues 2 | 3 | ## What are queues? 4 | - A queue is a data structure which follows the FIFO rule (i.e. First In First Out). The first element that goes into the queue is the first element to come out. The last element to go into the queue is also the last element to come out. 5 | - It is just as the name suggests. It is a collection of elements in the form of a queue/line. The rear end is where elements are inserted. The front end is from where the elements are removed. 6 | - We can compare this queue to the queue outside any ticket counter. The first person to stand in line is the first person to get the ticket. The last person in line gets the ticket last. So, people get removed from the queue from the front end, and new people join the queue at the rear end. 7 | 8 | ## Applications - 9 | - Used whenever we want the output to be in the same order as the input. 10 | - Task scheduling in shared resources (like printers). 11 | 12 | ## Video - 13 | https://www.youtube.com/watch?v=WEkXizP0Q44 - Check out this video to learn more about queues! 14 | -------------------------------------------------------------------------------- /data structures/queues/circular_queue.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | #define SIZE 6 5 | 6 | // Class for circular queue - 7 | class CQueue { 8 | public: 9 | // Structure Student for storing student details - 10 | struct Student { 11 | int rno; // To store serial number 12 | string name; // To store name 13 | double sgpa; // To store sgpa 14 | }; 15 | Student temp; 16 | Student arr[SIZE]; // Array for storing student details 17 | int front, rear; 18 | // Constructor used for initializing front and rear pointers to -1 - 19 | CQueue() { 20 | front = -1; 21 | rear = -1; 22 | } 23 | int isFull(); // Function to check if queue is full 24 | int isEmpty(); // Function to check if queue is empty 25 | void enqueue(); // Function to perform enqueue operation 26 | int dequeue(); // Function to perform dequeue operaton 27 | void display(); // Function to display elements 28 | void display_rev(); // Function to display elements from last node 29 | void display_inter(); // Function to display elements from any intermediate node 30 | }; 31 | 32 | int CQueue :: isFull() { 33 | if ((front == rear + 1) || (front == 0 && rear == SIZE - 1)) { 34 | return 1; 35 | } 36 | return 0; 37 | } 38 | 39 | int CQueue :: isEmpty() { 40 | if (front == -1) { 41 | return 1; 42 | } 43 | return 0; 44 | } 45 | 46 | void CQueue :: enqueue() { 47 | string value; 48 | int roll; 49 | double sgpaval; 50 | // Check if queue is full - 51 | if (isFull()) 52 | cout << "Queue is full. No more admissions can be allocated!\n" << endl; 53 | 54 | else { 55 | cout << "Enter name: "; 56 | cin >> value; 57 | cout << "Enter serial no.: "; 58 | cin >> roll; 59 | cout << "Enter SGPA: "; 60 | cin >> sgpaval; 61 | if (front == -1) 62 | front = 0; 63 | 64 | rear = (rear + 1) % SIZE; 65 | arr[rear].name = value; 66 | arr[rear].rno = roll; 67 | arr[rear].sgpa = sgpaval; 68 | cout << "\nStudent inserted in queue is: "<< value << endl; 69 | } 70 | } 71 | 72 | int CQueue :: dequeue() { 73 | string variable; 74 | // Check if queue is empty - 75 | if (isEmpty()) { 76 | cout<<"Queue is empty!"<> temp; 131 | cout << "Sr.No." << "\t" << "Name" << "\t\t" << "SGPA" << endl; 132 | for (i = temp; i != temp - 1; i = (i + 1) % SIZE) { 133 | cout << arr[i].rno << "\t" << arr[i].name << "\t" << arr[i].sgpa << endl; 134 | } 135 | cout << arr[i].rno << "\t" << arr[i].name << "\t" << arr[i].sgpa << endl; 136 | } 137 | } 138 | 139 | int main() { 140 | CQueue obj; 141 | int choice; 142 | cout << "Welcome to the student admission portal!" << endl; 143 | do { 144 | cout << "\nEnter 1 to enqueue" << endl; 145 | cout << "Enter 2 to dequeue" << endl; 146 | cout << "Enter 3 to display from last node" << endl; 147 | cout << "Enter 4 to display from intermediate node" << endl; 148 | cout << "Enter 5 to stop: "; 149 | cin >> choice; 150 | switch (choice) { 151 | case 1: 152 | obj.enqueue(); 153 | obj.display(); 154 | break; 155 | case 2: 156 | obj.dequeue(); 157 | obj.display(); 158 | break; 159 | case 3: 160 | obj.display_rev(); 161 | break; 162 | case 4: 163 | obj.display_inter(); 164 | break; 165 | default: 166 | if (choice != 5) { 167 | cout << "Invalid Input!" << endl; 168 | } 169 | } 170 | } while (choice != 5); 171 | cout << "End of program!" << endl; 172 | return 0; 173 | } 174 | -------------------------------------------------------------------------------- /data structures/queues/queue_using_array.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | struct queue1 { 5 | int front, rear, cap, size, arr[]; 6 | queue1(int c) { 7 | arr[c]; 8 | cap = c; 9 | front = -1; 10 | rear=-1; 11 | size = 0; 12 | } 13 | void enqueue() { 14 | if (isFull()) { 15 | printf("\nThe queue is full\n"); 16 | return; 17 | } 18 | if (front == -1 && rear == -1) { 19 | front = 0; 20 | rear = 0; 21 | } else { 22 | rear = rear + 1; 23 | } 24 | int x; 25 | printf("Enter the element\n"); 26 | scanf("%d", &x); 27 | arr[rear] = x; 28 | size++; 29 | } 30 | 31 | void dequeue() { 32 | if (isEmpty()) { 33 | printf("The queue is empty"); 34 | return; 35 | } 36 | if (front == rear) { 37 | front = -1; 38 | rear = -1; 39 | } else { 40 | front = front + 1; 41 | } 42 | size--; 43 | } 44 | void getFront() { 45 | if (isEmpty()) 46 | printf("Empty"); 47 | else { 48 | printf("the ele at front is: %d", arr[front]); 49 | } 50 | } 51 | void getRear() { 52 | if (isEmpty()) 53 | printf("Empty"); 54 | else { 55 | printf("the ele at rear is: %d", arr[rear]); 56 | } 57 | } 58 | bool isEmpty() { return size == 0; } 59 | bool isFull() { return size == cap; } 60 | int qsize() { return size; } 61 | }; 62 | 63 | main() { 64 | int c; 65 | printf("Enter the capacity\n"); 66 | scanf("%d", &c); 67 | struct queue1 q(c); 68 | int ch; 69 | while (1) { 70 | printf("\n1.Enqueue\n"); 71 | printf("2.Dequeue\n"); 72 | printf("3.Display size\n"); 73 | printf("4.Display Front\n"); 74 | printf("5.Display Rear\n"); 75 | printf("6.Exit\n"); 76 | scanf("%d", &ch); 77 | switch (ch) { 78 | case 1: 79 | q.enqueue(); 80 | break; 81 | case 2: 82 | q.dequeue(); 83 | break; 84 | case 3: 85 | printf("\nThe current size of queue is: %d", q.qsize()); 86 | break; 87 | case 4: 88 | q.getFront(); 89 | break; 90 | case 5: 91 | q.getRear(); 92 | break; 93 | case 6: 94 | exit(0); 95 | default: 96 | printf("Incorrect choice \n"); 97 | } 98 | } 99 | } -------------------------------------------------------------------------------- /data structures/queues/queue_using_ll.cpp: -------------------------------------------------------------------------------- 1 | // program to demonstrate implementation of queues using linked lists - 2 | #include 3 | using namespace std; 4 | 5 | // structure for storing information of node of queue - 6 | struct node { 7 | int data; 8 | node *next; 9 | }; 10 | 11 | // class for performing operations on the queue - 12 | class queue { 13 | public: 14 | node *front; // front node 15 | node *rear; // rear node 16 | node *temp; // temp node 17 | void enqueue(); // function to enqueue/insert an element into the queue 18 | void dequeue(); // function to dequeue/remove the element from the front 19 | void display(); // function to display elements of the queue 20 | // constructor for initializing front and rear pointers to NULL 21 | queue() { 22 | front = rear = NULL; 23 | } 24 | }; 25 | 26 | void queue :: enqueue() { 27 | int num; 28 | cout << "Enter the number you want to enqueue: "; 29 | cin >> num; 30 | // case where queue is empty 31 | if (rear == NULL) { 32 | rear = new node; 33 | rear -> data = num; 34 | rear -> next = NULL; 35 | front = rear; 36 | } 37 | // case where queue is not empty - 38 | else { 39 | temp = new node; 40 | temp -> data = num; 41 | rear -> next = temp; 42 | if (front == NULL) { 43 | front = temp; 44 | rear = temp; 45 | front -> next = NULL; 46 | rear -> next = NULL; 47 | } 48 | else { 49 | rear -> next = temp; 50 | rear = temp; 51 | rear -> next = NULL; 52 | } 53 | } 54 | } 55 | 56 | void queue :: dequeue() { 57 | struct node *ptr; // temporary pointer 58 | if (front == NULL) { 59 | if (front == rear) { 60 | cout << "Queue is empty!" << endl; 61 | } 62 | else { 63 | cout << "Underflow condition!" << endl; 64 | return; 65 | } 66 | } 67 | else { 68 | ptr = front; 69 | cout << "Deleted element: " << front -> data << endl; 70 | front = front -> next; 71 | free(ptr); 72 | } 73 | } 74 | 75 | void queue :: display() { 76 | node *temp = new node; 77 | temp = front; 78 | if (front == NULL) { 79 | cout << "Queue is empty!" << endl; 80 | } 81 | else { 82 | while (temp != NULL) { 83 | cout << temp -> data << " "; 84 | temp = temp -> next; 85 | } 86 | cout << endl; 87 | } 88 | } 89 | 90 | int main() { 91 | queue q; 92 | int ch; 93 | do { 94 | cout << "Enter 1 to emqueue, 2 to dequeue, 3 to display, 4 to exit: "; 95 | cin >> ch; 96 | switch (ch) { 97 | case 1: 98 | q.enqueue(); 99 | break; 100 | case 2: 101 | q.dequeue(); 102 | break; 103 | case 3: 104 | q.display(); 105 | break; 106 | case 4: 107 | cout << "End of program!" << endl; 108 | break; 109 | default: 110 | cout << "Invalid Input!" << endl; 111 | } 112 | } while (ch != 4); 113 | return 0; 114 | } 115 | -------------------------------------------------------------------------------- /data structures/queues/queue_using_stacks.cpp: -------------------------------------------------------------------------------- 1 | // Program to Demonstrate Implementation of Queue using Stacks 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | // A Class which uses 2 stacks to act as Queue. 7 | class Queue { 8 | public: 9 | stack Stack1, Stack2; 10 | Queue() { 11 | // Initializing the stacks to be empty when the constructor gets called during Instantiation 12 | while (!Stack1.empty()) Stack1.pop(); 13 | while (!Stack2.empty()) Stack2.pop(); 14 | } 15 | 16 | // Push the element to back of the Queue 17 | void push(int x) { 18 | if (Stack1.empty() && !Stack2.empty()) { 19 | while (!Stack2.empty()) { 20 | Stack1.push(Stack2.top()); 21 | Stack2.pop(); 22 | } 23 | } 24 | Stack1.push(x); 25 | } 26 | 27 | // Pop the element from front of the Queue 28 | int pop() { 29 | while (!Stack1.empty()) { 30 | Stack2.push(Stack1.top()); 31 | Stack1.pop(); 32 | } 33 | int t = Stack2.top(); 34 | Stack2.pop(); 35 | return t; 36 | } 37 | 38 | // Get the Front/Peek element of the Queue 39 | int peek() { 40 | int t = this -> pop(); 41 | Stack2.push(t); 42 | return t; 43 | } 44 | 45 | // A Function to check if the Queue is empty 46 | bool empty() { 47 | return (Stack1.empty() && Stack2.empty()); 48 | } 49 | }; 50 | 51 | int main() { 52 | 53 | Queue Q; 54 | 55 | // Adding two elements to the Queue 56 | Q.push(1); 57 | Q.push(2); 58 | Q.push(3); 59 | 60 | // Front element in the Queue 61 | cout << "Front element in the Queue = " << Q.peek() << "\n"; 62 | 63 | // Popping an Element from the Queue 64 | Q.pop(); 65 | 66 | // Front element in the Queue 67 | cout << "Front element in the Queue = " << Q.peek() << "\n"; 68 | 69 | // Checking if Queue is Empty 70 | if (Q.empty()) { 71 | cout << "Queue is Empty\n"; 72 | } else { 73 | cout << "Queue is Not Empty\n"; 74 | } 75 | 76 | } -------------------------------------------------------------------------------- /data structures/stacks/README.md: -------------------------------------------------------------------------------- 1 | # Stacks 2 | 3 | ## What are stacks? 4 | - A stack is a data structure which is basically a single-ended collection of elements. The two operations of stack are - push (to insert/push elements into the stack) and pop (to remove/pop elements from the stack). Both these operations take place from the same end. 5 | - A stack follows the LIFO (Last In First Out) or FILO (First In Last Out) structure. That just means that the first elenent to go in is the last element to come out, and, the last element to go in is the first to come out. 6 | - We can compare this stack to the pile of plates in the kitchen sink. The first plate to go into the sink is the last one to get washed; the last plate to go into the sink is the first on to get washed. 7 | 8 | ## Applications of stack - 9 | - Used wherever a reverse output is desired. 10 | - Used for evaluating expressions. 11 | - Used in backtracking algorithms. 12 | 13 | ## Video for reference - 14 | If you want a more detailed explanation of stacks, do check out the following video - 15 | 16 | https://youtu.be/JO0F0zWaCYQ -------------------------------------------------------------------------------- /data structures/stacks/stack_using_arrays.cpp: -------------------------------------------------------------------------------- 1 | // Implementation of stack using arrays - 2 | #include 3 | #define MAX 25 4 | using namespace std; 5 | 6 | class stacks{ 7 | int top; // to store the position of the topmost element 8 | public: 9 | int numbers[MAX]; // stack array 10 | void push(int); // function to push elements into the stack 11 | int pop(); // function to pop the last element 12 | void display(); // function to display the elements 13 | // constructor for initializing the position of topmost element - 14 | stacks() { 15 | top = -1; 16 | } 17 | }; 18 | 19 | void stacks :: push(int x) { 20 | // check if capacity of stack is full - 21 | if (top >= MAX) { 22 | cout << "Stack overflow!" << endl; 23 | } 24 | else { 25 | numbers[++top] = x; 26 | cout << "Inserted element: " << x << endl; 27 | } 28 | } 29 | 30 | int stacks :: pop() { 31 | // check if stack is empty - 32 | if (top < 0) { 33 | cout << "Stack underflow!" << endl; 34 | } 35 | else { 36 | int d = numbers[top--]; 37 | cout << "Popped element: " << d << endl; 38 | return d; 39 | } 40 | } 41 | 42 | void stacks :: display() { 43 | if (top < 0) { 44 | cout << "Stack is empty!" << endl; 45 | return; 46 | } 47 | else { 48 | for (int i = top; i >= 0; i--) { 49 | cout << numbers[i] << " "; 50 | } 51 | cout << endl; 52 | } 53 | } 54 | 55 | int main() 56 | { 57 | stacks s; 58 | int ch; 59 | // menu-driven program - 60 | do { 61 | cout << "Enter 1 to push, 2 to pop, 3 to display, 4 to exit: "; 62 | cin >> ch; 63 | switch (ch) { 64 | case 1: 65 | int n; 66 | cout << "Enter the number that you want to push into the stack: "; 67 | cin >> n; 68 | s.push(n); 69 | break; 70 | case 2: 71 | s.pop(); 72 | break; 73 | case 3: 74 | s.display(); 75 | break; 76 | case 4: 77 | cout << "End of program!" << endl; 78 | break; 79 | default: 80 | cout << "Invalid Input!" << endl; 81 | } 82 | } while (ch != 4); 83 | return 0; 84 | } 85 | -------------------------------------------------------------------------------- /data structures/stacks/stack_using_ll.cpp: -------------------------------------------------------------------------------- 1 | // Following program demonstrates the implementation of stack using linked lists - 2 | #include 3 | using namespace std; 4 | 5 | // structure for storing node of stack 6 | struct node { 7 | int data; 8 | node *next; 9 | }; 10 | 11 | // class for performing operations on the stack - 12 | class stack { 13 | public: 14 | struct node *head = NULL; // initializing head node to null 15 | void push(); // function to push an element into the stack 16 | void pop(); // function to pop the topmost element from the stack 17 | void display(); // function to display elements of the stack 18 | }; 19 | 20 | void stack :: push() { 21 | int num; 22 | cout << "Enter number to push element into stack: "; 23 | cin >> num; 24 | node *temp = new node; // creating a new temporary node 25 | temp -> data = num; // assigning num value to data field of temp node 26 | temp -> next = head; 27 | head = temp; 28 | } 29 | 30 | void stack :: pop() { 31 | // check if stack is empty - 32 | if (head == NULL) { 33 | cout << "Stack underflow!" << endl; 34 | } 35 | else { 36 | cout << "Popped element: " << head -> data << endl; 37 | head = head -> next; 38 | } 39 | } 40 | 41 | void stack :: display() { 42 | node *temp = new node; 43 | if (head == NULL) { 44 | cout << "Stack is empty!" << endl; 45 | return; 46 | } 47 | else { 48 | temp = head; 49 | while (temp != NULL) { 50 | cout << temp -> data << " "; 51 | temp = temp -> next; 52 | } 53 | cout << endl; 54 | } 55 | } 56 | 57 | int main() { 58 | stack s; 59 | int ch; 60 | // implementing menu-driven program - 61 | do { 62 | cout << "Enter 1 to push, 2 to pop, 3 to display, 4 to exit: "; 63 | cin >> ch; 64 | switch (ch) { 65 | case 1: 66 | s.push(); 67 | break; 68 | case 2: 69 | s.pop(); 70 | break; 71 | case 3: 72 | s.display(); 73 | break; 74 | case 4: 75 | cout << "End of program!" << endl; 76 | break; 77 | default: 78 | cout << "Invalid input!" << endl; 79 | } 80 | } while (ch != 4); 81 | return 0; 82 | } 83 | -------------------------------------------------------------------------------- /data structures/stacks/string_reverse_stack.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include // Standard library for creating stack 4 | 5 | using namespace std; 6 | 7 | void reverse(char *str, int len) 8 | { 9 | stack s; 10 | int i; 11 | 12 | // Push into a stack 13 | for(i = 0; i < len; i++) 14 | s.push(str[i]); 15 | 16 | // Pop from a stack 17 | for(i= 0; i < len; i++) 18 | { 19 | str[i] = s.top(); 20 | s.pop(); 21 | } 22 | 23 | } 24 | 25 | int main() 26 | { 27 | 28 | char str[]="Hello World"; 29 | int len = strlen(str); 30 | 31 | reverse(str, len); 32 | 33 | cout <<"After reversing : \n" << str; 34 | 35 | return 0; 36 | } 37 | -------------------------------------------------------------------------------- /data structures/trees/README.md: -------------------------------------------------------------------------------- 1 | # Trees 2 | 3 | ## What are trees? 4 | - Trees are a non-linear type of data structure. They generally represent a normal tree (only inverted, i.e. with the root at the top!). 5 | - According to Wikipedia, in computer science, a tree is a widely used abstract data type that simulates a hierarchical tree structure, with a root value and subtrees of children with a parent node, represented as a set of linked nodes. 6 | 7 | ## Tree Terminology 8 | - **Node** - A structure which contains a value. 9 | - **Root node** - A root node is the topmost node of the tree. 10 | - **Child node** - A node which is linked to a parent node is called a child node. 11 | - **Parent node** - Consider a node that has two child nodes. The top node is the parent of these two child nodes. 12 | - **Ancestor node** - The nodes above the parent nodes of a child node are called the ancestor nodes of the child node. 13 | - **Leaf node** - A node which has no child node. 14 | - **Internal node** - A node that has child nodes. 15 | - **External node** - A node that does not have child nodes (i.e. leaf node). 16 | - **Degree of a node** - A degree of a node is the total number of its children. 17 | - **Degree of a tree** - The highest degree of any node in the tree. 18 | - **Width** - The number of nodes in a level. 19 | - **Breadth** - The number of leaves of the tree. 20 | - **Size of a tree** - Total number of all the nodes in the tree. 21 | 22 | ## Types of trees - 23 | 1. Binary Trees 24 | 2. Binary Search Trees 25 | 3. Red-Black Trees 26 | 4. Expression Trees 27 | 5. B-Trees 28 | 6. AVL Trees .......etc. 29 | 30 | -------------------------------------------------------------------------------- /data structures/trees/binary trees/binary search trees/binary_search_tree.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Lab Assignment 5 : Binary Search Tree: 3 | Implement binary search tree and perform following operations: 4 | a) Insert (Handle insertion of duplicate entry) (DONE) 5 | b) Delete (DONE) 6 | c) Search (DONE) 7 | d) Display tree (Traversal) - 3 Recursive; Implement only 1 Non-recursive (DONE) 8 | e) Display - Depth of tree (DONE) 9 | f) Display - Mirror image (DONE) 10 | g) Create a copy 11 | h) Display all parent nodes with their child nodes 12 | i) Display leaf nodes (DONE) 13 | j) Display tree level wise 14 | (Note: Insertion, Deletion, Search and Traversal are compulsory, from rest of operations, perform 15 | Any three) 16 | */ 17 | 18 | #include 19 | #include 20 | #include 21 | using namespace std; 22 | 23 | class node { 24 | public: 25 | int data; 26 | node *left; 27 | node *right; 28 | node () { 29 | data = 0; 30 | left = right = NULL; 31 | } 32 | }; 33 | 34 | class binarySearchTree { 35 | public: 36 | node *root = NULL; 37 | void insert_node(int); // to insert element in binary search tree 38 | bool search_node(int, node*); // to search for a particular element 39 | bool search_node(); // helper function to search for node 40 | class node *delete_node(node *, int); // to delete node 41 | void delete_node_1(); // helper function to delete node 42 | void inorder(node *); // for inorder traversal of tree 43 | void preorder(node *); // for preorder traversal of tree 44 | void postorder(node *); // for postorder traversal of tree 45 | void display(); // to display elements of bst 46 | void display_leaf_nodes(node *); // to display leaf nodes 47 | void display_leaf_nodes_1(); // helper function for displaying leaf nodes 48 | void mirror_img(node *); // to display mirror image of tree 49 | void mirror_img_1(); // helper function to display mirror image of tree 50 | int display_depth(node *); // to display depth of bst 51 | void display_depth_1(); // helper function to display depth of bst 52 | class node *minKey(node *curr) { 53 | while (curr -> left != nullptr) { 54 | curr = curr -> left; 55 | } 56 | return curr; 57 | } 58 | }; 59 | 60 | void binarySearchTree :: insert_node(int key) { 61 | // to insert an element if the tree is empty - 62 | if (root == NULL) { 63 | node *temp = new node(); // create new temporary node 64 | temp -> data = key; // assign key to data field of temp node 65 | temp -> left = temp -> right = NULL; // make right and left fields as null 66 | cout << "\nElement " << key << " is inserted!" << endl; 67 | cout << temp -> data << endl; 68 | root = temp; // assign temp node as root 69 | return; 70 | } 71 | node *temp1 = new node(); 72 | temp1 = root; 73 | while(true) { 74 | // to insert element as left child of parent node - 75 | // check if key is less than or equal to element in data field - 76 | if (key < temp1 -> data || key == temp1 -> data) { 77 | // check if left child is present or not 78 | if (temp1 -> left == NULL) { 79 | temp1 -> left = new node; // create new node as left child of temp node 80 | temp1 = temp1 -> left; // assign the newly created node as temp 81 | temp1 -> data = key; // assign key to data field of temp node 82 | temp1 -> left = NULL; // assign left as NULL 83 | temp1 -> right = NULL; // assign right as NULL 84 | cout << "\nElement " << key << " inserted!" << endl; 85 | break; 86 | } 87 | // check if left child is present or not 88 | else if (temp1 -> left != NULL) { 89 | temp1 = temp1 -> left; 90 | } 91 | } 92 | // to insert element as right child of parent node - 93 | // check if key is greater than element in data field - 94 | else if (key > temp1 -> data) { 95 | // check if right child is present - 96 | if (temp1 -> right == NULL) { 97 | temp1 -> right = new node; 98 | temp1 = temp1 -> right; 99 | temp1 -> data = key; 100 | temp1 -> left = NULL; 101 | temp1 -> right = NULL; 102 | cout << "\nElement " << key << " inserted!" << endl; 103 | break; 104 | } 105 | // check if right child is present - 106 | else if (temp1 -> right != NULL) { 107 | temp1 = temp1 -> right; 108 | } 109 | } 110 | } 111 | inorder(root); // to display elements 112 | cout << endl; 113 | } 114 | 115 | void binarySearchTree :: inorder(node *p) { 116 | // check if p is null 117 | if (p != nullptr) { 118 | inorder(p -> left); // function on left child 119 | cout << p -> data << " "; // print data 120 | inorder(p -> right); // function on right child 121 | } 122 | } 123 | 124 | void binarySearchTree :: preorder(node *p) { 125 | // check if p is null 126 | if (p != nullptr) { 127 | cout << p -> data << " "; // print data 128 | preorder(p -> left); // function on left child 129 | preorder(p -> right); // function on right child 130 | } 131 | } 132 | 133 | void binarySearchTree :: postorder(node *p) { 134 | // check if p is null 135 | if (p != nullptr) { 136 | postorder(p -> left); // function on left child 137 | postorder(p -> right); // function on right child 138 | cout << p -> data << " "; // print data 139 | } 140 | } 141 | 142 | void binarySearchTree :: display() { 143 | int ch; 144 | do { 145 | cout << "\nEnter 1 for inorder traversal, 2 for preorder traversal, 3 for postorder traversal, 4 to exit: "; 146 | cin >> ch; 147 | switch (ch) { 148 | case 1: 149 | if (root == nullptr) { 150 | cout << "BST is empty!" << endl; 151 | return; 152 | } 153 | inorder(root); // for inorder traversal of tree 154 | break; 155 | case 2: 156 | if (root == nullptr) { 157 | cout << "BST is empty!" << endl; 158 | return; 159 | } 160 | preorder(root); // for preorder traversal of tree 161 | break; 162 | case 3: 163 | if (root == nullptr) { 164 | cout << "BST is empty!" << endl; 165 | return; 166 | } 167 | postorder(root); // for postorder traversal of tree 168 | break; 169 | default: 170 | if (ch != 4) { 171 | cout << "Invalid Input!" << endl; 172 | } 173 | } 174 | } while (ch != 4); 175 | } 176 | 177 | void binarySearchTree :: display_leaf_nodes(node *root) { 178 | if (!root) { 179 | cout << "BST is empty!" << endl; 180 | return; 181 | } 182 | // if left child and right child both are null, it means that the node is a leaf node 183 | if (!root -> left && !root -> right) { 184 | cout << root -> data << " "; // print element in the data field 185 | return; 186 | } 187 | // check if left child is present 188 | if (root -> left) { 189 | display_leaf_nodes(root -> left); 190 | } 191 | // check if right child is present 192 | if (root -> right) { 193 | display_leaf_nodes(root -> right); 194 | } 195 | } 196 | 197 | void binarySearchTree :: display_leaf_nodes_1() { 198 | if (root != nullptr) { 199 | cout << "Displaying leaf nodes of bst: "; 200 | } 201 | display_leaf_nodes(root); 202 | 203 | } 204 | 205 | void binarySearchTree :: mirror_img(node *root) { 206 | // check if root is null/bst is empty 207 | if (root == nullptr) { 208 | return; 209 | } 210 | mirror_img(root -> left); // repeat on left child 211 | mirror_img(root -> right); // repeat on right child 212 | swap(root -> left, root -> right); // swap left and right 213 | } 214 | 215 | void binarySearchTree :: mirror_img_1() { 216 | // check if bst is empty 217 | if (root == nullptr) { 218 | cout << "BST is empty!" << endl; 219 | return; 220 | } 221 | cout << "Displaying mirror image of bst: " << endl; 222 | mirror_img(root); // to perform operation 223 | inorder(root); // to display elements inorder 224 | } 225 | 226 | class node *binarySearchTree :: delete_node(node *root, int key) { 227 | // check if binary search tree is present - 228 | if (root == nullptr) { 229 | return root; 230 | } 231 | // check if data field is less than key 232 | if (root -> data < key) { 233 | root -> right = delete_node(root -> right, key); 234 | } 235 | // check if data field is greater than key 236 | else if (root ->data > key) { 237 | root ->left = delete_node(root ->left, key); 238 | } 239 | // otherwise do the following 240 | else { 241 | // check if pointers to left and right children are null 242 | if (root -> left == nullptr && root ->right == nullptr) { 243 | free(root); // free the memory allocated to root node 244 | return nullptr; 245 | } 246 | // check if only left child is null 247 | else if (root -> left == nullptr) { 248 | class node *temp = root -> right; 249 | free(root); // free the memory 250 | return temp; 251 | } 252 | // check if only right child is null 253 | else if (root -> right == nullptr) { 254 | class node *temp = root -> left; 255 | free(root); // free the memory 256 | return temp; 257 | } 258 | else { 259 | class node* minimumKey = minKey(root -> right); 260 | root -> data = minimumKey -> data; 261 | root -> right = delete_node(root -> right, minimumKey -> data); 262 | } 263 | } 264 | return root; 265 | } 266 | 267 | void binarySearchTree :: delete_node_1() { 268 | int val1; 269 | cout << "Enter the element that you want to delete: "; 270 | cin >> val1; 271 | int pre = search_node(val1, root); 272 | if (pre == 1) { 273 | delete_node(root, val1); 274 | cout << val1 << " is deleted!" << endl; 275 | } 276 | else { 277 | cout << "Element not present to delete!" << endl; 278 | } 279 | } 280 | 281 | bool binarySearchTree :: search_node(int key, node *curr) { 282 | bool ans = false; 283 | if (curr == nullptr) { 284 | cout << "Element not found!" << endl; 285 | return false; 286 | } 287 | // if key is equal to the element in the data field, element is found 288 | if (key == curr -> data) { 289 | cout << "Element found!" << endl; 290 | return true; 291 | } 292 | // if key is less than element in the data field, repeat process on left child 293 | else if (key < curr -> data) { 294 | ans = search_node(key, curr -> left); 295 | } 296 | // if key is greater than element in the data field, repeat process on right child 297 | else { 298 | ans = search_node(key, curr -> right); 299 | } 300 | return ans; 301 | } 302 | 303 | bool binarySearchTree :: search_node() { 304 | int key; 305 | cout << "Enter element to search for: "; 306 | cin >> key; 307 | // check if root is null 308 | if (root == nullptr) { 309 | cout << "BST is empty!" << endl; 310 | return false; 311 | } 312 | else { 313 | return search_node(key, root); 314 | } 315 | } 316 | 317 | int binarySearchTree :: display_depth(node *root) { 318 | if (root == nullptr) { 319 | return 0; 320 | } 321 | else { 322 | // l_depth is the depth of the left child 323 | int l_depth = display_depth(root -> left); 324 | // r_depth is the depth of the right child 325 | int r_depth = display_depth(root -> right); 326 | // check if l_depth is greater than r_depth 327 | if (l_depth > r_depth) { 328 | // if yes, return l_depth + 1 329 | return (l_depth + 1); 330 | } 331 | // if r_depth is greater than or equal to l_depth 332 | else { 333 | return (r_depth + 1); 334 | } 335 | } 336 | } 337 | 338 | void binarySearchTree :: display_depth_1() { 339 | int d = display_depth(root); 340 | if (d == 0) { 341 | cout << "BST is empty!" << endl; 342 | } 343 | else { 344 | cout << "Depth of binary search tree is: " << d - 1 << endl; 345 | } 346 | } 347 | 348 | int main() { 349 | int choice, val, key; 350 | binarySearchTree obj; 351 | do { 352 | cout << "\nWHAT WOULD YOU LIKE TO DO? \n1: Insert node, \n2: Display element(s), \n3: Search for an element, \n4: Delete an element, \n5: Display leaf node(s), \n6: Display mirror image of tree, \n7: Display depth of tree, \n8: Exit: "; 353 | cin >> choice; 354 | switch (choice) { 355 | case 1: 356 | cout << "Enter element: "; 357 | cin >> val; 358 | obj.insert_node(val); 359 | break; 360 | case 2: 361 | obj.display(); 362 | cout << endl; 363 | break; 364 | case 3: 365 | obj.search_node(); 366 | break; 367 | case 4: 368 | obj.delete_node_1(); 369 | break; 370 | case 5: 371 | obj.display_leaf_nodes_1(); 372 | break; 373 | case 6: 374 | obj.mirror_img_1(); 375 | break; 376 | case 7: 377 | obj.display_depth_1(); 378 | break; 379 | default: 380 | if (choice != 8) { 381 | cout << "Invalid Input!" << endl; 382 | } 383 | } 384 | } while (choice != 8); 385 | return 0; 386 | } 387 | -------------------------------------------------------------------------------- /data structures/trees/binary trees/binary search trees/threaded_bst.cpp: -------------------------------------------------------------------------------- 1 | // DSA Lab Assignment 6 - 2 | #include 3 | using namespace std; 4 | 5 | // class created for storing contents of node - 6 | class Node { 7 | public: 8 | int data; // to store data 9 | Node *left, *right; // pointers to left and right children nodes 10 | int l_flag, r_flag; // left and right flags 11 | // constructor for initializing variables - 12 | Node() { 13 | data = 0; 14 | left = right = nullptr; 15 | l_flag = r_flag = 0; 16 | } 17 | }; 18 | 19 | // class for threaded binary search tree - 20 | class tbst { 21 | public: 22 | Node *root; // create a new pointer to node as root 23 | // constructor for initializing variables - 24 | tbst() { 25 | root = new Node(); 26 | root -> data = 0; 27 | root -> left = root; 28 | root -> right = root; 29 | root -> l_flag = 0; 30 | root -> r_flag = 1; 31 | } 32 | void insert(int); // function to insert an element into the tbst 33 | void inorder(); // function to traverse the tree inorder 34 | void preorder(); // function to traverse the tree preorder 35 | Node *inorder_ele(Node *); 36 | Node *preorder_ele(Node *); 37 | }; 38 | 39 | void tbst :: insert(int n) { 40 | // check if root is the only node - 41 | if (root -> left == root && root -> right == root) { 42 | Node *temp = new Node(); // create new temporary node 43 | temp -> data = n; // assign n to data value of temp node 44 | temp -> left = root -> left; 45 | temp -> right = root -> right; 46 | temp -> l_flag = root -> l_flag; 47 | temp -> r_flag = 0; // flag will be 0 as there is no successor 48 | root -> left = temp; // temp node will take the place of left child of root 49 | root -> l_flag = 1; // flag will be 1 as predecessor is present 50 | return; 51 | } 52 | // if above condition is false, then do the following - 53 | Node *node = new Node; 54 | node = root -> left; 55 | while (true) { 56 | // check if element in the data field is less than n - 57 | if (node -> data < n) { 58 | Node *temp = new Node(); // create temp node 59 | temp -> data = n; 60 | if (node -> r_flag == 0) { 61 | temp -> left = node; 62 | temp -> l_flag = 0; 63 | temp -> right = node -> right; 64 | temp -> r_flag = node -> r_flag; 65 | node -> right = temp; 66 | node -> r_flag = 1; 67 | return; 68 | } 69 | // else go to the right child of node - 70 | else { 71 | node = node -> right; 72 | } 73 | } 74 | // check if element in the data field is greater than n - 75 | else if (node -> data >= n) { 76 | Node *temp = new Node(); // create a temp node 77 | temp -> data = n; 78 | if (node -> l_flag == 0) { 79 | temp -> left = node -> left; 80 | temp -> right = node; 81 | temp -> l_flag = node -> l_flag; 82 | temp -> r_flag = 0; 83 | node -> left = temp; 84 | node -> l_flag = 1; 85 | return; 86 | } 87 | // else go to the left child of node - 88 | else { 89 | node = node -> left; 90 | } 91 | } 92 | } 93 | } 94 | 95 | void tbst :: inorder() { 96 | Node *node_1; 97 | node_1 = root -> left; 98 | // continue until left flag is 1 99 | while (node_1 -> l_flag == 1) { 100 | node_1 = node_1 -> left; // go to left child 101 | } 102 | // continue until node is not the same as root - 103 | while (node_1 != root) { 104 | cout << " " << node_1 -> data; // display element 105 | node_1 = inorder_ele(node_1); 106 | } 107 | } 108 | 109 | Node *tbst :: inorder_ele(Node *n) { 110 | if (n -> r_flag == 0) { 111 | return (n -> right); 112 | } 113 | else { 114 | n = n -> right; 115 | } 116 | while (n -> l_flag == 1) { 117 | n = n -> left; 118 | } 119 | return (n); 120 | } 121 | 122 | void tbst :: preorder() { 123 | Node *node_2; 124 | node_2 = root -> left; 125 | while (node_2 != root) { 126 | cout << " " << node_2 -> data; 127 | node_2 = preorder_ele(node_2); 128 | } 129 | } 130 | 131 | Node *tbst :: preorder_ele(Node *n) { 132 | if (n -> l_flag == 1) { 133 | return (n -> left); 134 | } 135 | while (n -> r_flag == 0) { 136 | n = n -> right; 137 | } 138 | return (n -> right); 139 | } 140 | 141 | int main() { 142 | tbst tree; 143 | int num, i, val; 144 | cout << "How many elements do you want to insert: "; 145 | cin >> num; 146 | for (i = 0; i < num; i++) { 147 | cout << "Enter element: "; 148 | cin >> val; 149 | tree.insert(val); 150 | } 151 | int choice; 152 | do { 153 | cout << "Enter 1 for inorder traversal, 2 for preorder traversal, 3 to exit: "; 154 | cin >> choice; 155 | switch (choice) { 156 | case 1: 157 | cout << "\nInorder Traversal of tbt: " << endl; 158 | tree.inorder(); 159 | cout << endl; 160 | break; 161 | case 2: 162 | cout << "\nPreorder Traversal of tbt: " << endl; 163 | tree.preorder(); 164 | cout << endl; 165 | break; 166 | default: 167 | if (choice != 3) { 168 | cout << "Invalid input!" << endl; 169 | } 170 | } 171 | } while (choice != 3); 172 | return 0; 173 | } 174 | -------------------------------------------------------------------------------- /data structures/trees/expression_tree.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | // class created for storing information of tree node - 8 | class tnode { 9 | public: 10 | tnode *left; // stores left node location 11 | char data; // stores data 12 | tnode *right; // stores right node location 13 | }; 14 | 15 | // class created for storing information of stack node - 16 | class stacknode { 17 | public: 18 | tnode *data; 19 | int flag; 20 | }; 21 | 22 | // class created for stack operations - 23 | class my_stack { 24 | public: 25 | int top; // stored top location 26 | // constructor for initializing top to -1 - 27 | my_stack() { 28 | top = -1; 29 | } 30 | tnode *data1[100]; // array for storing elements of tree node 31 | stacknode data2[100]; 32 | // function to push element of tree node into stack - 33 | void push(tnode *x) { 34 | data1[++top] = x; 35 | } 36 | // function to push element of stack node into stack - 37 | void push(stacknode x) { 38 | data2[++top] = x; 39 | } 40 | // function to pop element of tree - 41 | tnode *pop() { 42 | return data1[top--]; 43 | } 44 | // function to pop element of stack node - 45 | stacknode pop1() { 46 | return data2[top--]; 47 | } 48 | // function to check if empty - 49 | int isEmpty() { 50 | if (top == 0) { 51 | return 1; 52 | } 53 | return 0; 54 | } 55 | }; 56 | 57 | class expressionTree { 58 | public: 59 | tnode *root = new tnode; 60 | my_stack s; // object of stack class created 61 | void createExpTreePost(); // function to create expression tree from postfix expression 62 | void createExpTreePre(); // function to create expression tree from prefix expression 63 | int validatePost(char exp[]); // function to validate postfix expression 64 | int validatePre(char exp[]); // function to validate prefix expression 65 | void traverseInorder(tnode *); // function to traverse tree inorder (without recursion) 66 | void recursiveInorder(tnode *); // function to traverse tree inorder (recursively) 67 | void inorder(); 68 | void traversePreorder(tnode *); // function to traverse tree preorder (without recursion) 69 | void recursivePreorder(tnode *); // function to traverse tree preorder (recursively) 70 | void preorder(); 71 | void traversePostorder(tnode *); // function to traverse tree postorder (without recursion) 72 | void recursivePostorder(tnode *); // function to traverse tree postorder (recursively) 73 | void postorder(); 74 | }; 75 | 76 | void expressionTree :: createExpTreePost() { 77 | char exp[100]; // array to store expression 78 | int validation; 79 | do { 80 | cout << "Enter postfix expression: "; 81 | cin >> exp; 82 | validation = validatePost(exp); 83 | if (validation != 1) { 84 | cout << "Invalid postfix expression!" << endl; 85 | } 86 | } while(validation != 1); 87 | 88 | for (int i = 0; exp[i] != '\0'; i++) { 89 | // check if it is a number or alphabet (operand) - 90 | if (isalnum(exp[i])) { 91 | tnode *temp1 = new tnode; // create new temporary node 92 | temp1 -> data = exp[i]; // assign element to data field of temp node 93 | temp1 -> right = temp1 -> left = NULL; // assign left and right values of node to NULL 94 | s.push(temp1); // push temp node into stack 95 | } 96 | else { 97 | // check if it is an operator - 98 | if (exp[i] == '+' || exp[i] == '-' || exp[i] == '*' || exp[i] == '/' || exp[i] == '^') { 99 | tnode *temp2 = new tnode; // create new temp node 100 | temp2 -> data = exp[i]; // assign operator to data field of temp node 101 | temp2 -> right = s.pop(); // pop element from stack and assign to right child of temp node 102 | temp2 -> left = s.pop(); // pop element from stack and assign to left child of temp node 103 | s.push(temp2); // push temp node into stack 104 | root = temp2; // make temp root as root 105 | } 106 | } 107 | } 108 | cout << "Expression tree created from postfix expression." << endl; 109 | } 110 | 111 | void expressionTree :: createExpTreePre() { 112 | char exp[100]; // array for storing expression 113 | char e[100]; 114 | int validation; 115 | do { 116 | cout << "Enter prefix expression: "; 117 | cin >> exp; 118 | validation = validatePre(exp); 119 | if (validation != 1) { 120 | cout << "Invalid prefix expression." << endl; 121 | } 122 | } while (validation != 1); 123 | 124 | int i, j, l = strlen(exp); 125 | for (i = 0, j = l - 1; j >= 0; i++, j--) 126 | e[i] = exp[j]; 127 | e[i] = '\0'; 128 | for (i = 0; e[i] != '\0'; i++) { 129 | // to check if operand - 130 | if (isalnum(e[i])) { 131 | tnode *temp1 = new tnode; 132 | temp1 -> data = e[i]; 133 | temp1 -> left = temp1 -> right = NULL; 134 | s.push(temp1); 135 | } 136 | // for operators - 137 | else { 138 | if (e[i] == '+' || e[i] == '-' || e[i] == '*' || e[i] == '/' || e[i] == '^') { 139 | tnode *temp2 = new tnode; 140 | temp2 -> data = e[i]; 141 | temp2 -> left = s.pop(); 142 | temp2 -> right = s.pop(); 143 | s.push(temp2); 144 | root = temp2; 145 | } 146 | } 147 | } 148 | cout << "Expression tree created from prefix expression." << endl; 149 | } 150 | 151 | int expressionTree :: validatePost(char exp[]) { 152 | int counter = 0; 153 | int i; 154 | for (i = 0; exp[i] != '\0'; i++) { 155 | if (isalnum(exp[i])) { 156 | counter++; 157 | } 158 | else { 159 | counter--; 160 | counter--; 161 | counter++; 162 | } 163 | } 164 | if (counter == 1) { 165 | return 1; 166 | } 167 | else { 168 | return 0; 169 | } 170 | } 171 | 172 | int expressionTree :: validatePre(char exp[]) { 173 | int counter = 1, flag = 0; 174 | int i; 175 | for (i = 0; exp[i] != '\0'; i++) { 176 | if (isalnum(exp[i])) { 177 | counter--; 178 | if (counter < 0) { 179 | flag = 1; 180 | break; 181 | } 182 | } 183 | else { 184 | counter++; 185 | if (counter < 0) { 186 | flag = 1; 187 | break; 188 | } 189 | } 190 | } 191 | if (counter == 0) { 192 | return 1; 193 | } 194 | else { 195 | return 0; 196 | } 197 | } 198 | 199 | void expressionTree :: traverseInorder(tnode *root) { 200 | stack stack; 201 | 202 | // start from root node (set current node to root node) 203 | tnode *curr = root; 204 | 205 | // if current node is null and stack is also empty, we're done 206 | while (!stack.empty() || curr != nullptr) { 207 | // if current node is not null, push it to the stack (defer it) 208 | // and move to its left child 209 | if (curr != nullptr) { 210 | stack.push(curr); 211 | curr = curr -> left; 212 | } 213 | // else if current node is null, we pop an element from the stack, 214 | // print it and finally set current node to its right child 215 | else { 216 | curr = stack.top(); 217 | stack.pop(); 218 | cout << curr -> data; 219 | 220 | curr = curr -> right; 221 | } 222 | } 223 | } 224 | 225 | void expressionTree :: recursiveInorder(tnode *root) { 226 | if (root == NULL) { 227 | return; 228 | } 229 | recursiveInorder(root -> left); 230 | cout << root -> data; 231 | recursiveInorder(root -> right); 232 | } 233 | 234 | void expressionTree :: inorder() { 235 | int choice; 236 | do { 237 | cout << "\nEnter 1 for non-recursive, 2 for recursive, 3 to exit: "; 238 | cin >> choice; 239 | switch (choice) { 240 | case 1: 241 | cout << "Non-recursive inorder tree traversal: "; 242 | traverseInorder(root); 243 | cout << endl; 244 | break; 245 | case 2: 246 | cout << "Recursive inorder tree traversal: "; 247 | recursiveInorder(root); 248 | cout << endl; 249 | break; 250 | default: 251 | if (choice != 3) 252 | cout << "Invalid Input!" << endl; 253 | } 254 | } while (choice != 3); 255 | cout << endl; 256 | } 257 | 258 | void expressionTree :: traversePreorder(tnode *root) { 259 | // check if root is null - 260 | if (root == NULL) 261 | return; 262 | stack stack; 263 | stack.push(root); 264 | while (!stack.empty()) { 265 | tnode *curr = stack.top(); 266 | stack.pop(); 267 | cout << curr -> data; 268 | if (curr -> right) { 269 | stack.push(curr -> right); 270 | } 271 | if (curr -> left) { 272 | stack.push(curr -> left); 273 | } 274 | } 275 | } 276 | 277 | void expressionTree :: recursivePreorder(tnode *root) { 278 | if (root == NULL) 279 | return; 280 | cout << root -> data; 281 | recursivePreorder(root -> left); 282 | recursivePreorder(root -> right); 283 | } 284 | 285 | void expressionTree :: preorder() { 286 | int choice; 287 | do { 288 | cout << "\nEnter 1 for non-recursive, 2 for recursive, 3 to exit: "; 289 | cin >> choice; 290 | switch (choice) { 291 | case 1: 292 | cout << "Non-recursive preorder tree traversal: "; 293 | traversePreorder(root); 294 | cout << endl; 295 | break; 296 | case 2: 297 | cout << "Recursive preorder tree traversal: "; 298 | recursivePreorder(root); 299 | cout << endl; 300 | break; 301 | default: 302 | if (choice != 3) 303 | cout << "Invalid Input!" << endl; 304 | } 305 | } while (choice != 3); 306 | cout << endl; 307 | } 308 | 309 | void expressionTree :: traversePostorder(tnode *root) { 310 | stacknode st; 311 | tnode *p; 312 | while (root != NULL) { 313 | st.data = root; 314 | st.flag = 0; 315 | s.push(st); 316 | root = root -> left; 317 | } 318 | while (!s.isEmpty()) { 319 | st = s.pop1(); 320 | if (st.flag == 0) { 321 | st.flag = 1; 322 | s.push(st); 323 | root = st.data; 324 | root = root -> right; 325 | while (root != NULL) { 326 | st.data = root; 327 | st.flag = 0; 328 | s.push(st); 329 | root = root -> left; 330 | } 331 | } 332 | else { 333 | p = st.data; 334 | cout << p -> data; 335 | } 336 | } 337 | } 338 | 339 | void expressionTree :: recursivePostorder(tnode *root) { 340 | if (root != NULL) { 341 | recursivePostorder(root -> left); 342 | recursivePostorder(root -> right); 343 | cout << root -> data; 344 | } 345 | } 346 | 347 | void expressionTree :: postorder() { 348 | int choice; 349 | do { 350 | cout << "\nEnter 1 for non-recursive, 2 for recursive, 3 to exit: "; 351 | cin >> choice; 352 | switch (choice) { 353 | case 1: 354 | cout << "Non-recursive postorder tree traversal: "; 355 | traversePostorder(root); 356 | cout << endl; 357 | break; 358 | case 2: 359 | cout << "Recursive postorder tree traversal: "; 360 | recursivePostorder(root); 361 | cout << endl; 362 | break; 363 | default: 364 | if (choice != 3) 365 | cout << "Invalid Input!" << endl; 366 | } 367 | } while (choice != 3); 368 | cout << endl; 369 | } 370 | 371 | int main() { 372 | expressionTree obj; 373 | int ch; 374 | char ch1; 375 | do { 376 | cout << "Enter 1 to enter postfix expression, 2 to enter prefix expression, 3 to quit: "; 377 | cin >> ch; 378 | switch (ch) { 379 | case 1: 380 | obj.createExpTreePost(); 381 | do { 382 | cout << "Enter a for postorder traversal, b for preorder traversal, c for inorder traversal, d to exit: "; 383 | cin >> ch1; 384 | switch (ch1) { 385 | case 'a': 386 | obj.postorder(); 387 | break; 388 | case 'b': 389 | obj.preorder(); 390 | break; 391 | case 'c': 392 | obj.inorder(); 393 | break; 394 | default: 395 | if (ch1 != 'd') { 396 | cout << "Invalid Input!" << endl; 397 | } 398 | } 399 | } while (ch1 != 'd'); 400 | break; 401 | case 2: 402 | obj.createExpTreePre(); 403 | do { 404 | cout << "Enter a for postorder traversal, b for preorder traversal, c for inorder traversal, d to exit: "; 405 | cin >> ch1; 406 | switch (ch1) { 407 | case 'a': 408 | obj.postorder(); 409 | break; 410 | case 'b': 411 | obj.preorder(); 412 | break; 413 | case 'c': 414 | obj.inorder(); 415 | break; 416 | default: 417 | if (ch1 != 'd') { 418 | cout << "Invalid Input!" << endl; 419 | } 420 | } 421 | } while (ch1 != 'd'); 422 | break; 423 | default: 424 | if (ch != 3) { 425 | cout << "Invalid Input!" << endl; 426 | } 427 | } 428 | } while (ch != 3); 429 | } 430 | -------------------------------------------------------------------------------- /other programs/Count Inversion Program: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int getInvCount(int arr[], int n) 5 | { 6 | int count = 0; 7 | for (int i = 0; i < n - 1; i++) 8 | for (int j = i + 1; j < n; j++) 9 | if (arr[i] > arr[j]) 10 | count++; 11 | 12 | return count; 13 | } 14 | 15 | int main() 16 | { 17 | int arr[] = { 1, 20, 6, 4, 5 }; 18 | int n = sizeof(arr) / sizeof(arr[0]); 19 | cout << " Number of inversions are " 20 | << getInvCount(arr, n); 21 | return 0; 22 | } -------------------------------------------------------------------------------- /other programs/DecimalToBinary.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int main() 4 | { 5 | int a[10], n, i; 6 | cout<<"Enter the number to convert: "; 7 | cin>>n; 8 | for(i=0; n>0; i++) 9 | { 10 | a[i]=n%2; 11 | n= n/2; 12 | } 13 | cout<<"Binary of the given number= "; 14 | for(i=i-1 ;i>=0 ;i--) 15 | { 16 | cout< 2 | using namespace std; 3 | int fibonacciTerm(int n) 4 | { 5 | if (n <= 1) 6 | return n; //returns 0 for n=0 and 1 for n=1 7 | return fibonacciTerm(n-1) + fibonacciTerm(n-2); 8 | } 9 | int main(){ 10 | int n; 11 | cout<<"Enter the term of the fibonacci sequence whose value you want to find : "; 12 | cin>>n; 13 | int term = fibonacciTerm(n); 14 | cout<<"The "< 2 | #include 3 | using namespace std; 4 | int gcd(int a,int b) 5 | { 6 | int c; 7 | for(int i=1;i<=(a>b?b:a);i++) // To execute the loop x times where x is the smaller number 8 | { 9 | if(a%i==0 && b%i==0) 10 | { 11 | c=i; // Assigning the given factor to c 12 | } 13 | } 14 | return c; 15 | } 16 | int main() 17 | { 18 | int a,b; 19 | cout<<"Enter the values whose GCD you wish to find-"; 20 | cin>>a>>b; 21 | cout<<"GCD is "< 2 | using namespace std; 3 | int main() 4 | { 5 | int num; 6 | cin>>num; 7 | int arr[100000] = {0}; //array to store digits of factorial 8 | 9 | arr[0] = 1; //initializing 0th element as 1 because it is going to store unit digit 10 | 11 | int remainingNum = 0; //variable to store carry or other/remaining digit after storing unit digit in array at 0th position after multiplying it with number 12 | 13 | int lengthOfFactorial = 1; 14 | 15 | int number = 2; //factorial will start by 2 onwards and from 3,4,5,6......to N 16 | 17 | int position = 0; //variable to store position of digits which are to be stored in array 18 | 19 | while(number<=num){ 20 | 21 | position = 0; 22 | remainingNum = 0; 23 | while(position=0) 60 | { 61 | cout< 2 | 3 | using namespace std; 4 | int chess[11][11]; 5 | 6 | bool isPossible(int n,int row,int col){ 7 | // same column 8 | for(int i=row-1;i>=0;i--) 9 | { if(chess[i][col]==1) 10 | { 11 | return false; 12 | } 13 | } 14 | //upper left diagonal 15 | for(int i=row-1,j=col-1;i>=0 && j>=0; i--,j-- ){ 16 | if(chess[i][j]==1){ 17 | return false; 18 | } 19 | } 20 | //Upper right Diagonal 21 | for(int i=row-1,j=col+1;i>=0&&j 3 | #include 4 | using namespace std; 5 | int main() 6 | { 7 | int n,b=1,sum=0; // For each number is divisor to itself 8 | cout<<"Enter the number whose divisors you wish to find- "; 9 | cin>>n; 10 | sum=n; // For each number is divisor to itself 11 | for(int i=1;i<=n/2;i++) 12 | { 13 | if(n%i==0) 14 | { 15 | cout< 2 | 3 | using namespace std; 4 | void add(int a[], int x[]); 5 | void complement(int a[])// function to take 2s complement of a binary number 6 | { 7 | int i; 8 | int x[5] = {0}; 9 | x[4] = 1; 10 | for (i = 0; i <5; i++) 11 | { 12 | a[i] = (a[i] + 1) % 2; 13 | } 14 | add(a, x); 15 | } 16 | void add(int ac[], int x[])// function to add two binary numbers 17 | { 18 | int i, carry = 0; 19 | for (i = 4; i>=0; --i) 20 | { 21 | ac[i] = ac[i] + x[i] + carry; 22 | if (ac[i] > 1) 23 | { 24 | ac[i] = ac[i] % 2; 25 | carry = 1; 26 | } 27 | else 28 | carry = 0; 29 | } 30 | 31 | } 32 | 33 | void ashr(int ac[], int Q[])// function to left shift A and Q 34 | { 35 | // int temp, i; 36 | 37 | // temp = ac[0]; 38 | // qn = Q[0]; 39 | int t=Q[0]; 40 | for (int i =0; i<3;i++) 41 | { 42 | Q[i] =Q[i+1]; 43 | } 44 | for (int i =0; i<4;i++) 45 | { 46 | ac[i]=ac[i+1]; 47 | } 48 | ac[4]=t; 49 | 50 | } 51 | 52 | void display(int ac[], int Q[])// Function to display the quotient and remainder 53 | { 54 | int i; 55 | cout <<"Remainder: "; 56 | for (i = 0; i<5;i++){ 57 | cout <>q; 74 | cout<<"Enter Divisor"<>m; 76 | int k = 4; 77 | while(k>=0){ 78 | M[k]=m%2; 79 | m= m/2; 80 | k--; 81 | } 82 | int j=3; 83 | while(j>=0){ 84 | Q[j]=q%2; 85 | q= q/2; 86 | j--; 87 | } 88 | 89 | for (i =4;i>=0;i--){ 90 | mt[i] = M[i]; 91 | } 92 | complement(mt); 93 | c = 4; 94 | 95 | while (c != 0) 96 | { 97 | ashr(ac,Q); 98 | add(ac,mt); 99 | if(ac[0]==1){ 100 | Q[3]=0; 101 | add(ac,M); 102 | } 103 | else{ 104 | Q[3]=1; 105 | } 106 | c--; 107 | } 108 | display(ac,Q); 109 | } 110 | -------------------------------------------------------------------------------- /other programs/Sieve_of_Eratosthenes.cpp: -------------------------------------------------------------------------------- 1 | /*the sieve of Eratosthenes is an ancient algorithm for finding all prime numbers up to any given limit.*/ 2 | #include 3 | #include 4 | using namespace std; 5 | int prime(int n) // To check if a number is prime 6 | { 7 | int i=2; 8 | while(i<=n/2) 9 | { 10 | if(n%i==0) 11 | { 12 | return 1; 13 | } 14 | i++; 15 | } 16 | return 0; 17 | } 18 | int main() 19 | { 20 | int n; 21 | cout<<"Enter the max value(n)-"; 22 | cin>>n; 23 | for(int i=2;i<=n;i++) 24 | { 25 | if(prime(i)==0) 26 | { 27 | cout<