├── .vscode └── tasks.json ├── Array ├── ArrayDataStructure.cpp ├── ArrayDataStructure1.cpp ├── ArrayOperations.cpp ├── MultiDimensionalArrays.cpp └── README.md ├── Data Structure Basics ├── README.md └── Types_of_DSA.md ├── Graph Data Structure ├── GraphSearch ├── GraphSearch.cpp ├── Graph_search.cpp ├── README.md ├── graph1.cpp └── graph_traversal_example.cpp ├── Linked Lists ├── CircularLinkedList.cpp ├── CuricularLinkedList1 ├── CuricularLinkedList1.cpp ├── DoublyLinkedList.cpp ├── DoublyLinkedList1 ├── DoublyLinkedList1.cpp ├── LinkList1.cpp ├── LinkedListExample.cpp └── README.md ├── Queue ├── FIFO ├── FIFO.cpp ├── Queue_01 └── Queue_01.cpp ├── README.md ├── Recursion ├── Example.cpp ├── README.md ├── Recursion1 ├── Recursion1.cpp └── calculates_sum_digits.cpp ├── Sorting techniques ├── BubbleSort ├── BubbleSort.cpp ├── QuickSort.cpp └── SelectionSort.cpp ├── Stack ├── LIFO ├── LIFO.cpp ├── ParsingExpressions.cpp ├── README.md └── StackExample.cpp └── Tree Data Structure ├── README.md ├── Table Heap ├── Heap_01.cpp ├── Table_heap ├── Table_heap.cpp └── Table_with_Heap.cpp ├── Tree Hash ├── Tree_hash.cpp └── TreewithHashing.cpp └── simple_binary_tree.cpp /.vscode/tasks.json: -------------------------------------------------------------------------------- 1 | { 2 | "tasks": [ 3 | { 4 | "type": "cppbuild", 5 | "label": "C/C++: clang build active file", 6 | "command": "/usr/bin/clang", 7 | "args": [ 8 | "-fcolor-diagnostics", 9 | "-fansi-escape-codes", 10 | "-g", 11 | "${file}", 12 | "-o", 13 | "${fileDirname}/${fileBasenameNoExtension}" 14 | ], 15 | "options": { 16 | "cwd": "${fileDirname}" 17 | }, 18 | "problemMatcher": [ 19 | "$gcc" 20 | ], 21 | "group": { 22 | "kind": "build", 23 | "isDefault": true 24 | }, 25 | "detail": "Task generated by Debugger." 26 | } 27 | ], 28 | "version": "2.0.0" 29 | } -------------------------------------------------------------------------------- /Array/ArrayDataStructure.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() { 4 | // Declare and initialize an integer array 5 | int numbers[] = {12, 7, 23, 45, 9, 15, 30}; 6 | 7 | // Calculate the length of the array 8 | int length = sizeof(numbers) / sizeof(numbers[0]); 9 | 10 | // Print the array elements 11 | std::cout << "Array elements: "; 12 | for (int i = 0; i < length; i++) { 13 | std::cout << numbers[i] << " "; 14 | } 15 | std::cout << std::endl; 16 | 17 | // Accessing elements 18 | int thirdElement = numbers[2]; 19 | std::cout << "Third element: " << thirdElement << std::endl; 20 | 21 | // Find the maximum element 22 | int max = numbers[0]; 23 | for (int i = 1; i < length; i++) { 24 | if (numbers[i] > max) { 25 | max = numbers[i]; 26 | } 27 | } 28 | std::cout << "Maximum element: " << max << std::endl; 29 | 30 | return 0; 31 | } 32 | -------------------------------------------------------------------------------- /Array/ArrayDataStructure1.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | struct Student { 5 | std::string name; 6 | int score; 7 | }; 8 | 9 | int main() { 10 | const int MAX_STUDENTS = 5; 11 | Student students[MAX_STUDENTS]; 12 | 13 | // Input student records 14 | for (int i = 0; i < MAX_STUDENTS; i++) { 15 | std::cout << "Enter student #" << i + 1 << " name: "; 16 | std::cin >> students[i].name; 17 | std::cout << "Enter " << students[i].name << "'s score: "; 18 | std::cin >> students[i].score; 19 | } 20 | 21 | // Display all student records 22 | std::cout << "\nStudent Records:\n"; 23 | for (int i = 0; i < MAX_STUDENTS; i++) { 24 | std::cout << "Name: " << students[i].name << ", Score: " << students[i].score << std::endl; 25 | } 26 | 27 | // Find the highest-scoring student 28 | int highestScore = students[0].score; 29 | std::string highestScorer = students[0].name; 30 | 31 | for (int i = 1; i < MAX_STUDENTS; i++) { 32 | if (students[i].score > highestScore) { 33 | highestScore = students[i].score; 34 | highestScorer = students[i].name; 35 | } 36 | } 37 | 38 | std::cout << "\nHighest Scoring Student: " << highestScorer << " with a score of " << highestScore << std::endl; 39 | 40 | return 0; 41 | } 42 | -------------------------------------------------------------------------------- /Array/ArrayOperations.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include // for sorting 3 | 4 | int main() { 5 | // Declare and initialize an integer array 6 | int numbers[] = {12, 7, 23, 45, 9, 15, 30}; 7 | int length = sizeof(numbers) / sizeof(numbers[0]); 8 | 9 | // Print the original array 10 | std::cout << "Original array: "; 11 | for (int i = 0; i < length; i++) { 12 | std::cout << numbers[i] << " "; 13 | } 14 | std::cout << std::endl; 15 | 16 | // Insert an element (e.g., 20) at a specific position (index 2) 17 | int insertValue = 20; 18 | int insertPosition = 2; 19 | for (int i = length; i > insertPosition; i--) { 20 | numbers[i] = numbers[i - 1]; 21 | } 22 | numbers[insertPosition] = insertValue; 23 | 24 | // Print the updated array after insertion 25 | std::cout << "Array after insertion: "; 26 | for (int i = 0; i < length + 1; i++) { 27 | std::cout << numbers[i] << " "; 28 | } 29 | std::cout << std::endl; 30 | 31 | // Delete an element from a specific position (index 4) 32 | int deletePosition = 4; 33 | for (int i = deletePosition; i < length; i++) { 34 | numbers[i] = numbers[i + 1]; 35 | } 36 | length--; 37 | 38 | // Print the array after deletion 39 | std::cout << "Array after deletion: "; 40 | for (int i = 0; i < length; i++) { 41 | std::cout << numbers[i] << " "; 42 | } 43 | std::cout << std::endl; 44 | 45 | // Search for an element (e.g., 23) 46 | int searchValue = 23; 47 | int foundIndex = -1; 48 | for (int i = 0; i < length; i++) { 49 | if (numbers[i] == searchValue) { 50 | foundIndex = i; 51 | break; 52 | } 53 | } 54 | if (foundIndex != -1) { 55 | std::cout << "Element " << searchValue << " found at index " << foundIndex << std::endl; 56 | } else { 57 | std::cout << "Element " << searchValue << " not found in the array" << std::endl; 58 | } 59 | 60 | // Sort the array in ascending order 61 | std::sort(numbers, numbers + length); 62 | 63 | // Print the sorted array 64 | std::cout << "Sorted array: "; 65 | for (int i = 0; i < length; i++) { 66 | std::cout << numbers[i] << " "; 67 | } 68 | std::cout << std::endl; 69 | 70 | return 0; 71 | } 72 | -------------------------------------------------------------------------------- /Array/MultiDimensionalArrays.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() { 4 | // Declare and initialize two 2D arrays 5 | int matrix1[2][2] = { 6 | {1, 2}, 7 | {3, 4} 8 | }; 9 | 10 | int matrix2[2][2] = { 11 | {5, 6}, 12 | {7, 8} 13 | }; 14 | 15 | // Perform matrix addition 16 | int resultMatrix[2][2]; 17 | 18 | for (int i = 0; i < 2; i++) { 19 | for (int j = 0; j < 2; j++) { 20 | resultMatrix[i][j] = matrix1[i][j] + matrix2[i][j]; 21 | } 22 | } 23 | 24 | // Display the result matrix 25 | std::cout << "Matrix1:" << std::endl; 26 | for (int i = 0; i < 2; i++) { 27 | for (int j = 0; j < 2; j++) { 28 | std::cout << matrix1[i][j] << " "; 29 | } 30 | std::cout << std::endl; 31 | } 32 | 33 | std::cout << "Matrix2:" << std::endl; 34 | for (int i = 0; i < 2; i++) { 35 | for (int j = 0; j < 2; j++) { 36 | std::cout << matrix2[i][j] << " "; 37 | } 38 | std::cout << std::endl; 39 | } 40 | 41 | std::cout << "Result Matrix (Matrix1 + Matrix2):" << std::endl; 42 | for (int i = 0; i < 2; i++) { 43 | for (int j = 0; j < 2; j++) { 44 | std::cout << resultMatrix[i][j] << " "; 45 | } 46 | std::cout << std::endl; 47 | } 48 | 49 | return 0; 50 | } 51 | -------------------------------------------------------------------------------- /Array/README.md: -------------------------------------------------------------------------------- 1 | # C++ Data Structures and Algorithms - Array 2 | 3 | ## Introduction to Arrays 4 | - Arrays are fundamental data structures in C++ used for storing a collection of elements of the same data type in contiguous memory locations. 5 | - Arrays offer efficient random access to elements through index-based referencing. 6 | - In C++, arrays have a fixed size determined at compile-time, making them suitable for scenarios where the size remains constant during program execution. 7 | 8 | ## Declaring Arrays 9 | - Arrays are declared with a specific data type and size. 10 | - The size must be a non-negative integer and is determined at compile-time. 11 | 12 | ```cpp 13 | data_type array_name[array_size]; 14 | ``` 15 | 16 | **Example:** 17 | ```cpp 18 | int numbers[5]; 19 | ``` 20 | 21 | ## Initializing Arrays 22 | - Arrays can be initialized either during declaration or afterward. 23 | 24 | During declaration: 25 | ```cpp 26 | data_type array_name[array_size] = {element1, element2, ..., elementN}; 27 | ``` 28 | 29 | After declaration: 30 | ```cpp 31 | data_type array_name[array_size]; 32 | array_name[index] = value; 33 | ``` 34 | 35 | ## Accessing Array Elements 36 | - Elements of an array are accessed using an index, starting from 0. 37 | - Array indexing provides fast, constant-time access to elements. 38 | 39 | **Example:** 40 | ```cpp 41 | int element = numbers[2]; // Accesses the third element (index 2) 42 | ``` 43 | 44 | ## Array Operations 45 | - Common array operations include insertion, deletion, searching, and sorting. 46 | 47 | ## Dynamic Arrays (std::vector) 48 | - C++ offers dynamic arrays through the `std::vector` container from the Standard Template Library (STL). 49 | - Vectors can dynamically resize during runtime, making them a flexible alternative to fixed-size arrays. 50 | 51 | **Example:** 52 | ```cpp 53 | #include 54 | std::vector dynamicArray; 55 | dynamicArray.push_back(1); 56 | dynamicArray.push_back(2); 57 | ``` 58 | 59 | ## Multi-dimensional Arrays 60 | - C++ supports multi-dimensional arrays, such as 2D arrays, which are arrays of arrays. 61 | - Elements are accessed using both row and column indices. 62 | 63 | **Example:** 64 | ```cpp 65 | int matrix[3][3] = { 66 | {1, 2, 3}, 67 | {4, 5, 6}, 68 | {7, 8, 9} 69 | }; 70 | int element = matrix[1][2]; // Accesses the element in the second row and third column (value: 6) 71 | ``` 72 | 73 | ## Common Array Algorithms 74 | - Array algorithms include traversing, finding max/min elements, reversing, searching (linear and binary search), and sorting. 75 | 76 | **Example: Linear Search** 77 | ```cpp 78 | int array[] = {3, 5, 1, 7, 2}; 79 | int target = 5; 80 | for (int i = 0; i < 5; i++) { 81 | if (array[i] == target) { 82 | // Element found at index i 83 | break; 84 | } 85 | } 86 | ``` 87 | 88 | ## Array Complexity 89 | - Time complexity for common array operations: 90 | - Access: O(1) (constant time). 91 | - Insertion/Deletion (at the end): 92 | - O(1) for dynamic arrays like `std::vector`. 93 | - O(n) for fixed-size arrays. 94 | - Search: 95 | - Linear Search: O(n). 96 | - Binary Search (for sorted arrays): O(log n). 97 | 98 | ## Best Practices 99 | - Use `std::vector` for dynamic arrays. 100 | - Consider time complexity when selecting data structures and algorithms. 101 | - Ensure array bounds are respected to prevent accessing out-of-bounds memory. 102 | -------------------------------------------------------------------------------- /Data Structure Basics/README.md: -------------------------------------------------------------------------------- 1 | # C++ Data Structures and Algorithms - Linked List Basics 2 | 3 | Introduction: 4 | Data Structures and Algorithms (DSA) are fundamental components of computer science, and linked lists are one of the foundational data structures used in DSA. In this blog post, we'll explore the basics of implementing and using linked lists in C++. We'll cover node definition, creating a linked list, insertion, deletion, traversing, memory management, and other essential operations. 5 | 6 | ### Node Definition 7 | A linked list is composed of nodes, and each node has two parts: data and a reference (or pointer) to the next node. In C++, you can define a node structure as follows: 8 | 9 | ```cpp 10 | struct Node { 11 | int data; 12 | Node* next; 13 | }; 14 | ``` 15 | 16 | ### Creating a Linked List 17 | To create a linked list, you need a pointer to the head of the list. Initially, the list is empty, so the head pointer is set to nullptr. 18 | 19 | ```cpp 20 | Node* head = nullptr; 21 | ``` 22 | 23 | ### Insertion 24 | You can insert elements into the linked list by adding nodes at the beginning, end, or anywhere in between. 25 | 26 | - Insert at the beginning: 27 | To add a node at the beginning of the list, you can create a new node, set its data and next pointer, and update the head pointer. 28 | 29 | ```cpp 30 | Node* newNode = new Node; 31 | newNode->data = value; 32 | newNode->next = head; 33 | head = newNode; 34 | ``` 35 | 36 | - Insert at the end: 37 | To add a node at the end of the list, you must traverse the list to find the last node and update its next pointer. 38 | 39 | ```cpp 40 | Node* newNode = new Node; 41 | newNode->data = value; 42 | newNode->next = nullptr; 43 | if (head == nullptr) { 44 | head = newNode; 45 | } else { 46 | Node* current = head; 47 | while (current->next != nullptr) { 48 | current = current->next; 49 | } 50 | current->next = newNode; 51 | } 52 | ``` 53 | 54 | ### Deletion 55 | Nodes can be removed from the linked list as well. 56 | 57 | - Delete from the beginning: 58 | To delete the first node, you update the head pointer and release the memory. 59 | 60 | ```cpp 61 | if (head != nullptr) { 62 | Node* temp = head; 63 | head = head->next; 64 | delete temp; 65 | } 66 | ``` 67 | 68 | - Delete a specific node: 69 | To delete a node with a specific value, you need to traverse the list and update the `next` pointers accordingly. 70 | 71 | ### Traversing 72 | To perform operations on the elements in the linked list, you need to traverse it using a loop. 73 | 74 | ```cpp 75 | Node* current = head; 76 | while (current != nullptr) { 77 | // Do something with current->data 78 | current = current->next; 79 | } 80 | ``` 81 | 82 | ### Memory Management 83 | Don't forget to release the memory allocated for nodes using the `delete` operator when you're done with the linked list. 84 | 85 | ### Error Handling 86 | Ensure that you handle edge cases, such as empty lists, when writing your linked list functions. 87 | 88 | -------------------------------------------------------------------------------- /Data Structure Basics/Types_of_DSA.md: -------------------------------------------------------------------------------- 1 | # C++ Data Structures and Types for Data Structures and Algorithms (DSA) 2 | 3 | Introduction: 4 | Data Structures and Algorithms (DSA) are the backbone of computer science, enabling efficient problem-solving and data manipulation. In C++, a versatile programming language, various data structures and types play a pivotal role in DSA. This blog post explores key data structures and types used in C++ for DSA, providing an overview of their significance and usage. 5 | 6 | ## 1. Arrays 7 | Arrays are fundamental data structures in C++. They store a fixed-size sequence of elements of the same type. Arrays provide constant-time access to elements, making them ideal for basic storage and retrieval operations. However, their size is fixed at the time of declaration, and resizing can be challenging. 8 | 9 | ```cpp 10 | int arr[5]; // Declaration of an integer array with 5 elements 11 | ``` 12 | 13 | ## 2. Vectors 14 | Vectors are a part of the C++ Standard Template Library (STL) and offer dynamic arrays. They can grow or shrink in size dynamically. Vectors provide O(1) access to elements, O(1) insertion at the end, and amortized O(1) insertion at arbitrary positions. 15 | 16 | ```cpp 17 | #include 18 | std::vector vec; // Declaration of an integer vector 19 | ``` 20 | 21 | ## 3. Linked Lists 22 | Linked lists are composed of nodes, each containing data and a reference (or pointer) to the next node. In C++, linked lists can be singly linked or doubly linked. They are dynamic and provide flexibility for insertions and deletions. 23 | 24 | ```cpp 25 | struct Node { 26 | int data; 27 | Node* next; 28 | }; 29 | ``` 30 | 31 | ## 4. Stacks and Queues 32 | Stacks and queues are abstract data types in C++ that can be implemented using arrays or linked lists. Stacks follow the Last-In-First-Out (LIFO) principle, while queues follow the First-In-First-Out (FIFO) principle. They are essential for managing data flow in algorithms. 33 | 34 | ```cpp 35 | #include 36 | std::stack stack; // Declaration of a stack 37 | #include 38 | std::queue queue; // Declaration of a queue 39 | ``` 40 | 41 | ## 5. Sets and Maps 42 | Sets and maps are part of the C++ STL and are used to store unique elements and key-value pairs, respectively. Sets use a binary search tree, and maps use a red-black tree to maintain sorted data. 43 | 44 | ```cpp 45 | #include 46 | std::set uniqueSet; // Declaration of a set 47 | #include 48 | std::map keyValueMap; // Declaration of a map 49 | ``` 50 | 51 | ## 6. Hash Tables 52 | Hash tables (unordered_map and unordered_set) provide constant-time average complexity for insertion, deletion, and retrieval of elements. They use hash functions to map keys to specific locations in the underlying array. 53 | 54 | ```cpp 55 | #include 56 | std::unordered_map unorderedMap; // Declaration of an unordered_map 57 | ``` 58 | 59 | ## 7. Strings 60 | C++ offers the `std::string` class, which simplifies string manipulation and provides various built-in functions for working with strings. They are dynamic and can be resized as needed. 61 | 62 | ```cpp 63 | std::string text = "Hello, World!"; // Declaration of a string 64 | ``` 65 | 66 | ## 8. Pointers 67 | Pointers are essential for dynamic memory allocation and managing complex data structures. They allow you to work with memory addresses directly, making them crucial in low-level data manipulation. 68 | 69 | ```cpp 70 | int* ptr = nullptr; // Declaration of an integer pointer 71 | ``` 72 | 73 | ## Conclusion 74 | C++ offers a rich set of data structures and types that are fundamental in Data Structures and Algorithms. Selecting the right data structure for a specific problem is crucial for efficient algorithm design and implementation. Mastering these data structures and understanding their advantages and limitations are essential skills for any programmer or computer scientist. 75 | -------------------------------------------------------------------------------- /Graph Data Structure/GraphSearch: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Pankaj-Str/Data-Structures-CPP/1655668903104335d240f3210cc5f2ea8bcb33d3/Graph Data Structure/GraphSearch -------------------------------------------------------------------------------- /Graph Data Structure/GraphSearch.cpp: -------------------------------------------------------------------------------- 1 | // DFS = Depth First Search 2 | // BFS = Breadth First Search 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | 9 | using namespace std; 10 | 11 | class Graph{ 12 | 13 | public : int vertices; 14 | 15 | vector< vector > adjList; 16 | 17 | Graph(int V) : vertices(V),adjList(V){} 18 | 19 | void addEdge(int u,int v){ 20 | adjList[u].push_back(v); 21 | } 22 | 23 | // depth- first search 24 | 25 | void DFS(int start){ 26 | vector visited(vertices,false); 27 | stack stk; 28 | 29 | stk.push(start); 30 | 31 | while(!stk.empty()){ 32 | int current = stk.top(); 33 | stk.pop(); 34 | 35 | if(!visited[current]){ 36 | cout< visited(vertices,false); 55 | queue q; 56 | 57 | q.push(start); 58 | visited[start] = true; 59 | 60 | while(!q.empty()){ 61 | int current = q.front(); 62 | q.pop(); 63 | 64 | cout<< current <<" "; 65 | 66 | for(int neighbor : adjList[current]){ 67 | 68 | if(!visited[neighbor]){ 69 | q.push(neighbor); 70 | visited[neighbor]= true; 71 | } 72 | 73 | } 74 | cout< 5 | #include 6 | #include 7 | #include 8 | #include 9 | 10 | class Graph { 11 | private: 12 | int vertices; 13 | std::vector> adjList; 14 | 15 | public: 16 | Graph(int v) : vertices(v), adjList(v) {} 17 | 18 | // Function to add an edge to the graph 19 | void addEdge(int v, int w) { 20 | adjList[v].push_back(w); 21 | adjList[w].push_back(v); 22 | } 23 | 24 | // Depth-First Search (DFS) 25 | void DFS(int start) { 26 | std::cout << "DFS starting from node " << start << ": "; 27 | std::vector visited(vertices, false); 28 | DFSUtil(start, visited); 29 | std::cout << std::endl; 30 | } 31 | 32 | // Breadth-First Search (BFS) 33 | void BFS(int start) { 34 | std::cout << "BFS starting from node " << start << ": "; 35 | std::vector visited(vertices, false); 36 | std::queue q; 37 | q.push(start); 38 | visited[start] = true; 39 | 40 | while (!q.empty()) { 41 | int current = q.front(); 42 | q.pop(); 43 | std::cout << current << " "; 44 | 45 | for (int neighbor : adjList[current]) { 46 | if (!visited[neighbor]) { 47 | visited[neighbor] = true; 48 | q.push(neighbor); 49 | } 50 | } 51 | } 52 | 53 | std::cout << std::endl; 54 | } 55 | 56 | private: 57 | // Recursive utility function for DFS 58 | void DFSUtil(int node, std::vector& visited) { 59 | visited[node] = true; 60 | std::cout << node << " "; 61 | 62 | for (int neighbor : adjList[node]) { 63 | if (!visited[neighbor]) { 64 | DFSUtil(neighbor, visited); 65 | } 66 | } 67 | } 68 | }; 69 | 70 | int main() { 71 | Graph graph(6); 72 | 73 | // Adding edges to the graph 74 | graph.addEdge(0, 1); 75 | graph.addEdge(0, 2); 76 | graph.addEdge(1, 3); 77 | graph.addEdge(1, 4); 78 | graph.addEdge(2, 4); 79 | graph.addEdge(3, 5); 80 | 81 | // Perform DFS starting from node 0 82 | graph.DFS(0); 83 | 84 | // Perform BFS starting from node 0 85 | graph.BFS(0); 86 | 87 | return 0; 88 | } 89 | // The Graph class represents an undirected graph using an adjacency list. 90 | // addEdge is used to add edges to the graph. 91 | // DFS and BFS are functions to perform Depth-First Search and Breadth-First Search, respectively. 92 | // The graph is then created, and DFS and BFS are performed starting from node 0. -------------------------------------------------------------------------------- /Graph Data Structure/README.md: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /Graph Data Structure/graph1.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | class WeightedGraph { 7 | private: 8 | int vertices; 9 | std::vector>> adjList; 10 | 11 | public: 12 | WeightedGraph(int v) : vertices(v), adjList(v) {} 13 | 14 | // Function to add a weighted edge to the graph 15 | void addEdge(int v, int w, int weight) { 16 | adjList[v].emplace_back(w, weight); 17 | adjList[w].emplace_back(v, weight); // For an undirected graph 18 | } 19 | 20 | // Dijkstra's Algorithm for finding the shortest path from a start node 21 | void dijkstra(int start) { 22 | std::vector dist(vertices, std::numeric_limits::max()); 23 | dist[start] = 0; 24 | 25 | std::priority_queue, std::vector>, std::greater>> pq; 26 | pq.push({0, start}); 27 | 28 | while (!pq.empty()) { 29 | int u = pq.top().second; 30 | pq.pop(); 31 | 32 | for (const auto& neighbor : adjList[u]) { 33 | int v = neighbor.first; 34 | int weight = neighbor.second; 35 | 36 | if (dist[u] + weight < dist[v]) { 37 | dist[v] = dist[u] + weight; 38 | pq.push({dist[v], v}); 39 | } 40 | } 41 | } 42 | 43 | std::cout << "Shortest distances from node " << start << ":\n"; 44 | for (int i = 0; i < vertices; ++i) { 45 | std::cout << "Node " << i << ": " << dist[i] << '\n'; 46 | } 47 | } 48 | }; 49 | 50 | int main() { 51 | WeightedGraph weightedGraph(6); 52 | 53 | // Adding weighted edges to the graph 54 | weightedGraph.addEdge(0, 1, 2); 55 | weightedGraph.addEdge(0, 2, 4); 56 | weightedGraph.addEdge(1, 2, 1); 57 | weightedGraph.addEdge(1, 3, 7); 58 | weightedGraph.addEdge(2, 4, 3); 59 | weightedGraph.addEdge(3, 4, 1); 60 | weightedGraph.addEdge(3, 5, 5); 61 | weightedGraph.addEdge(4, 5, 2); 62 | 63 | // Perform Dijkstra's Algorithm starting from node 0 64 | weightedGraph.dijkstra(0); 65 | 66 | return 0; 67 | } 68 | // The WeightedGraph class represents a weighted, undirected graph using an adjacency list. 69 | // addEdge is used to add weighted edges to the graph. 70 | // dijkstra is a function that implements Dijkstra's algorithm to find the shortest paths from a start node to all other nodes. 71 | // The graph is then created with weighted edges, and Dijkstra's algorithm is applied starting from node 0. -------------------------------------------------------------------------------- /Graph Data Structure/graph_traversal_example.cpp: -------------------------------------------------------------------------------- 1 | //this time using Depth-First Search (DFS) to find connected components in an undirected graph 2 | #include 3 | #include 4 | #include 5 | 6 | class Graph { 7 | private: 8 | int vertices; 9 | std::vector> adjList; 10 | 11 | public: 12 | Graph(int v) : vertices(v), adjList(v) {} 13 | 14 | // Function to add an edge to the graph 15 | void addEdge(int v, int w) { 16 | adjList[v].push_back(w); 17 | adjList[w].push_back(v); // For an undirected graph 18 | } 19 | 20 | // Function to find connected components using DFS 21 | void findConnectedComponents() { 22 | std::vector visited(vertices, false); 23 | int componentCount = 0; 24 | 25 | std::cout << "Connected Components:\n"; 26 | for (int i = 0; i < vertices; ++i) { 27 | if (!visited[i]) { 28 | std::cout << "Component " << ++componentCount << ": "; 29 | DFS(i, visited); 30 | std::cout << '\n'; 31 | } 32 | } 33 | } 34 | 35 | private: 36 | // Recursive utility function for DFS 37 | void DFS(int node, std::vector& visited) { 38 | visited[node] = true; 39 | std::cout << node << " "; 40 | 41 | for (int neighbor : adjList[node]) { 42 | if (!visited[neighbor]) { 43 | DFS(neighbor, visited); 44 | } 45 | } 46 | } 47 | }; 48 | 49 | int main() { 50 | Graph graph(9); 51 | 52 | // Adding edges to the graph to form multiple connected components 53 | graph.addEdge(0, 1); 54 | graph.addEdge(1, 2); 55 | graph.addEdge(2, 0); 56 | graph.addEdge(3, 4); 57 | graph.addEdge(5, 6); 58 | graph.addEdge(6, 7); 59 | graph.addEdge(8, 8); 60 | 61 | // Finding connected components using DFS 62 | graph.findConnectedComponents(); 63 | 64 | return 0; 65 | } 66 | 67 | // The Graph class represents an undirected graph using an adjacency list. 68 | // addEdge is used to add edges to the graph. 69 | // findConnectedComponents is a function that uses DFS to find and print connected components in the graph. 70 | // The graph is created with edges forming multiple connected components, and DFS is applied to find and print these components. -------------------------------------------------------------------------------- /Linked Lists/CircularLinkedList.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | // Define a structure for a node in the circular linked list 4 | struct Node { 5 | int data; 6 | Node* next; 7 | 8 | Node(int value) : data(value), next(nullptr) {} 9 | }; 10 | 11 | // Define a class for the circular linked list 12 | class CircularLinkedList { 13 | public: 14 | CircularLinkedList() : head(nullptr) {} 15 | 16 | // Function to insert a new node at the end of the list 17 | void insert(int value) { 18 | Node* newNode = new Node(value); 19 | if (head == nullptr) { 20 | head = newNode; 21 | head->next = head; // Make it circular by pointing to itself 22 | } else { 23 | newNode->next = head->next; 24 | head->next = newNode; 25 | head = newNode; 26 | } 27 | } 28 | 29 | // Function to display the circular linked list 30 | void display() { 31 | if (head == nullptr) { 32 | std::cout << "Circular Linked List is empty." << std::endl; 33 | return; 34 | } 35 | 36 | Node* current = head->next; 37 | do { 38 | std::cout << current->data << " -> "; 39 | current = current->next; 40 | } while (current != head->next); 41 | 42 | std::cout << "Head: " << head->data << std::endl; 43 | } 44 | 45 | // Function to delete a node with a given value from the list 46 | void deleteNode(int value) { 47 | if (head == nullptr) { 48 | std::cout << "Circular Linked List is empty. Cannot delete." << std::endl; 49 | return; 50 | } 51 | 52 | Node* current = head->next; 53 | Node* prev = head; 54 | 55 | while (current != head && current->data != value) { 56 | prev = current; 57 | current = current->next; 58 | } 59 | 60 | if (current == head && current->data != value) { 61 | std::cout << "Node with value " << value << " not found in the list." << std::endl; 62 | return; 63 | } 64 | 65 | if (current == head) { 66 | if (current->next == current) { 67 | head = nullptr; 68 | } else { 69 | head = current->next; 70 | } 71 | } 72 | 73 | prev->next = current->next; 74 | delete current; 75 | } 76 | 77 | // Destructor to release memory when the circular linked list is destroyed 78 | ~CircularLinkedList() { 79 | if (head == nullptr) return; 80 | 81 | Node* current = head->next; 82 | while (current != head) { 83 | Node* temp = current; 84 | current = current->next; 85 | delete temp; 86 | } 87 | 88 | delete head; 89 | } 90 | 91 | private: 92 | Node* head; 93 | }; 94 | 95 | int main() { 96 | CircularLinkedList list; 97 | 98 | list.insert(10); 99 | list.insert(20); 100 | list.insert(30); 101 | list.insert(40); 102 | 103 | std::cout << "Circular Linked List: "; 104 | list.display(); 105 | 106 | list.deleteNode(20); 107 | std::cout << "Circular Linked List after deleting 20: "; 108 | list.display(); 109 | 110 | return 0; 111 | } 112 | -------------------------------------------------------------------------------- /Linked Lists/CuricularLinkedList1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Pankaj-Str/Data-Structures-CPP/1655668903104335d240f3210cc5f2ea8bcb33d3/Linked Lists/CuricularLinkedList1 -------------------------------------------------------------------------------- /Linked Lists/CuricularLinkedList1.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | struct Node{ 6 | int data; 7 | struct Node *next; 8 | }; 9 | 10 | struct Node* head = NULL; 11 | 12 | void insert(int newdata){ 13 | struct Node *newnode = (struct Node *) malloc(sizeof(struct Node)); 14 | struct Node *ptr = head; 15 | newnode->data = newdata; 16 | newnode->next = head; 17 | if(head != NULL){ 18 | while (ptr->next != head) 19 | 20 | ptr = ptr->next; 21 | ptr->next = newnode; 22 | 23 | 24 | }else 25 | newnode->next = newnode; 26 | head = newnode; 27 | 28 | 29 | } 30 | 31 | void display(){ 32 | struct Node* ptr; 33 | ptr = head; 34 | do{ 35 | cout<data <<" "; 36 | ptr = ptr->next; 37 | }while(ptr != head); 38 | } 39 | int main(){ 40 | insert(3); 41 | insert(4); 42 | insert(5); 43 | insert(7); 44 | insert(8); 45 | insert(9); 46 | insert(10); 47 | cout<<"this circular linked list is : - "; 48 | display(); 49 | return 0; 50 | } 51 | 52 | 53 | 54 | 55 | -------------------------------------------------------------------------------- /Linked Lists/DoublyLinkedList.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | // Define a structure for a node in the doubly linked list 4 | struct Node { 5 | int data; 6 | Node* prev; 7 | Node* next; 8 | 9 | Node(int value) : data(value), prev(nullptr), next(nullptr) {} 10 | }; 11 | 12 | // Define a class for the doubly linked list 13 | class DoublyLinkedList { 14 | public: 15 | DoublyLinkedList() : head(nullptr), tail(nullptr) {} 16 | 17 | // Function to insert a new node at the end of the list 18 | void insert(int value) { 19 | Node* newNode = new Node(value); 20 | if (head == nullptr) { 21 | head = tail = newNode; 22 | } else { 23 | newNode->prev = tail; 24 | tail->next = newNode; 25 | tail = newNode; 26 | } 27 | } 28 | 29 | // Function to display the doubly linked list from head to tail 30 | void display() { 31 | Node* current = head; 32 | while (current != nullptr) { 33 | std::cout << current->data << " <-> "; 34 | current = current->next; 35 | } 36 | std::cout << "nullptr" << std::endl; 37 | } 38 | 39 | // Function to display the doubly linked list from tail to head 40 | void displayReverse() { 41 | Node* current = tail; 42 | while (current != nullptr) { 43 | std::cout << current->data << " <-> "; 44 | current = current->prev; 45 | } 46 | std::cout << "nullptr" << std::endl; 47 | } 48 | 49 | // Function to delete a node with a given value from the list 50 | void deleteNode(int value) { 51 | Node* current = head; 52 | 53 | while (current != nullptr && current->data != value) { 54 | current = current->next; 55 | } 56 | 57 | if (current == nullptr) { 58 | std::cout << "Node with value " << value << " not found in the list." << std::endl; 59 | return; 60 | } 61 | 62 | if (current == head) { 63 | head = current->next; 64 | if (head != nullptr) { 65 | head->prev = nullptr; 66 | } 67 | } else if (current == tail) { 68 | tail = current->prev; 69 | tail->next = nullptr; 70 | } else { 71 | current->prev->next = current->next; 72 | current->next->prev = current->prev; 73 | } 74 | 75 | delete current; 76 | } 77 | 78 | // Destructor to release memory when the doubly linked list is destroyed 79 | ~DoublyLinkedList() { 80 | while (head != nullptr) { 81 | Node* temp = head; 82 | head = head->next; 83 | delete temp; 84 | } 85 | } 86 | 87 | private: 88 | Node* head; 89 | Node* tail; 90 | }; 91 | 92 | int main() { 93 | DoublyLinkedList list; 94 | 95 | list.insert(10); 96 | list.insert(20); 97 | list.insert(30); 98 | list.insert(40); 99 | 100 | std::cout << "Doubly Linked List (Head to Tail): "; 101 | list.display(); 102 | 103 | std::cout << "Doubly Linked List (Tail to Head): "; 104 | list.displayReverse(); 105 | 106 | list.deleteNode(20); 107 | std::cout << "Doubly Linked List after deleting 20: "; 108 | list.display(); 109 | 110 | return 0; 111 | } 112 | -------------------------------------------------------------------------------- /Linked Lists/DoublyLinkedList1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Pankaj-Str/Data-Structures-CPP/1655668903104335d240f3210cc5f2ea8bcb33d3/Linked Lists/DoublyLinkedList1 -------------------------------------------------------------------------------- /Linked Lists/DoublyLinkedList1.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // structure 5 | struct TrainCarriage 6 | { 7 | int passenger; 8 | TrainCarriage* next; 9 | TrainCarriage* prev; 10 | TrainCarriage(int passenger) : passenger(passenger), next(nullptr),prev(nullptr){} 11 | }; 12 | 13 | class Train{ 14 | TrainCarriage* front; 15 | 16 | public : Train() : front(nullptr){} 17 | 18 | // function to add a new carriage to the front of the train 19 | void addCarriage(int passenger){ 20 | TrainCarriage* newCarriage = new TrainCarriage(passenger); 21 | if(front != nullptr){ 22 | newCarriage->next = front; 23 | front->prev = newCarriage; 24 | } 25 | front = newCarriage; 26 | } 27 | // function to desplay the passengers in the train 28 | 29 | void display(){ 30 | TrainCarriage* current = front; 31 | 32 | while (current != nullptr) 33 | { 34 | cout<<"Passenger : "<< current->passenger<<" <- "; 35 | current = current ->next; 36 | } 37 | cout<<"End of the Train "< 2 | // Linked List 3 | 4 | // Define a node structure 5 | // individual elements in the linked list 6 | 7 | struct Node{ 8 | int data; 9 | Node* next; 10 | Node(int data) : data(data), next(nullptr) {} 11 | }; 12 | 13 | // define a linkedlist class to manage the list 14 | 15 | class LinkedList{ 16 | 17 | private : Node* head; // Pointer to the first node in the list 18 | public : LinkedList() : head(nullptr){ } 19 | 20 | // function to insert a new element 21 | // begninning of the list 22 | 23 | void insert(int data){ 24 | Node * newNode = new Node(data); 25 | newNode ->next = head; 26 | head = newNode; 27 | } 28 | 29 | void display(){ 30 | 31 | Node* current = head; 32 | while(current != nullptr){ 33 | std::cout<data<<" -> "; 34 | current = current->next; 35 | } 36 | std::cout<<"nullptr"< 2 | 3 | // Define a structure for a node in the linked list 4 | struct Node { 5 | int data; 6 | Node* next; 7 | 8 | Node(int value) : data(value), next(nullptr) {} 9 | }; 10 | 11 | // Define a class for the linked list 12 | class LinkedList { 13 | public: 14 | LinkedList() : head(nullptr) {} 15 | 16 | // Function to insert a new node at the end of the list 17 | void insert(int value) { 18 | Node* newNode = new Node(value); 19 | if (head == nullptr) { 20 | head = newNode; 21 | } else { 22 | Node* current = head; 23 | while (current->next != nullptr) { 24 | current = current->next; 25 | } 26 | current->next = newNode; 27 | } 28 | } 29 | 30 | // Function to display the linked list 31 | void display() { 32 | Node* current = head; 33 | while (current != nullptr) { 34 | std::cout << current->data << " -> "; 35 | current = current->next; 36 | } 37 | std::cout << "nullptr" << std::endl; 38 | } 39 | 40 | // Function to delete a node with a given value from the list 41 | void deleteNode(int value) { 42 | Node* current = head; 43 | Node* prev = nullptr; 44 | 45 | while (current != nullptr && current->data != value) { 46 | prev = current; 47 | current = current->next; 48 | } 49 | 50 | if (current == nullptr) { 51 | std::cout << "Node with value " << value << " not found in the list." << std::endl; 52 | return; 53 | } 54 | 55 | if (prev == nullptr) { 56 | head = current->next; 57 | } else { 58 | prev->next = current->next; 59 | } 60 | 61 | delete current; 62 | } 63 | 64 | // Destructor to release memory when the linked list is destroyed 65 | ~LinkedList() { 66 | while (head != nullptr) { 67 | Node* temp = head; 68 | head = head->next; 69 | delete temp; 70 | } 71 | } 72 | 73 | private: 74 | Node* head; 75 | }; 76 | 77 | int main() { 78 | LinkedList list; 79 | 80 | list.insert(10); 81 | list.insert(20); 82 | list.insert(30); 83 | list.insert(40); 84 | 85 | std::cout << "Linked List: "; 86 | list.display(); 87 | 88 | list.deleteNode(20); 89 | std::cout << "Linked List after deleting 20: "; 90 | list.display(); 91 | 92 | return 0; 93 | } 94 | -------------------------------------------------------------------------------- /Linked Lists/README.md: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /Queue/FIFO: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Pankaj-Str/Data-Structures-CPP/1655668903104335d240f3210cc5f2ea8bcb33d3/Queue/FIFO -------------------------------------------------------------------------------- /Queue/FIFO.cpp: -------------------------------------------------------------------------------- 1 | //First-In, First-Out (FIFO) 2 | #include 3 | #include 4 | using namespace std; 5 | int main(){ 6 | queue myQueue; 7 | 8 | // Enqueue (push) elements in to queue 9 | 10 | myQueue.push(10); 11 | myQueue.push(20); 12 | myQueue.push(30); 13 | 14 | // Front element of the queue 15 | cout<<"front element of the queue : "< 2 | #include 3 | 4 | using namespace std; 5 | 6 | int main(){ 7 | 8 | // queue create a queue of integers 9 | 10 | queue myQueue; 11 | 12 | // Enqueue elements into the queue 13 | myQueue.push(10); 14 | myQueue.push(20); 15 | myQueue.push(30); 16 | 17 | // 30 20 10 18 | 19 | // display the front element of the queue 20 | 21 | cout<<"Front element of the queue : "<< myQueue.front()< 2 | 3 | // Recursive function to calculate the factorial of a number 4 | int factorial(int n) { 5 | // Base case: factorial of 0 is 1 6 | if (n == 0 || n == 1) { 7 | return 1; 8 | } else { 9 | // Recursive case: n! = n * (n-1)! 10 | return n * factorial(n - 1); 11 | } 12 | } 13 | 14 | // Recursive function to calculate the nth Fibonacci number 15 | int fibonacci(int n) { 16 | // Base cases: Fibonacci of 0 is 0, and Fibonacci of 1 is 1 17 | if (n == 0) { 18 | return 0; 19 | } else if (n == 1) { 20 | return 1; 21 | } else { 22 | // Recursive case: Fibonacci(n) = Fibonacci(n-1) + Fibonacci(n-2) 23 | return fibonacci(n - 1) + fibonacci(n - 2); 24 | } 25 | } 26 | 27 | int main() { 28 | // Example of factorial calculation 29 | int num = 5; 30 | std::cout << "Factorial of " << num << " is: " << factorial(num) << std::endl; 31 | 32 | // Example of Fibonacci sequence 33 | int fibNum = 6; 34 | std::cout << "Fibonacci number at position " << fibNum << " is: " << fibonacci(fibNum) << std::endl; 35 | 36 | return 0; 37 | } 38 | -------------------------------------------------------------------------------- /Recursion/README.md: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /Recursion/Recursion1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Pankaj-Str/Data-Structures-CPP/1655668903104335d240f3210cc5f2ea8bcb33d3/Recursion/Recursion1 -------------------------------------------------------------------------------- /Recursion/Recursion1.cpp: -------------------------------------------------------------------------------- 1 | // factorial of calculate 2 | 3 | #include 4 | using namespace std; 5 | 6 | int factorial(int n){ 7 | 8 | // base case : factorial of 0 - 1 9 | 10 | if(n == 0 || n == 1){ 11 | return 1; 12 | }else{ 13 | // recursive case : n! = n * (n-1)! 14 | 15 | return n * factorial(n - 1); 16 | } 17 | 18 | } 19 | int main(){ 20 | 21 | int num = 5; 22 | 23 | cout<<" factorial of "< 2 | 3 | // Recursive function to calculate the sum of digits of a number 4 | int sumOfDigits(int n) { 5 | // Base case: if n is a single-digit number, return n 6 | if (n < 10) { 7 | return n; 8 | } else { 9 | // Recursive case: sum = last digit + sum of digits in the remaining part 10 | return n % 10 + sumOfDigits(n / 10); 11 | } 12 | } 13 | 14 | int main() { 15 | // Example of sum of digits calculation 16 | int number = 12345; 17 | std::cout << "Sum of digits of " << number << " is: " << sumOfDigits(number) << std::endl; 18 | 19 | return 0; 20 | } 21 | -------------------------------------------------------------------------------- /Sorting techniques/BubbleSort: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Pankaj-Str/Data-Structures-CPP/1655668903104335d240f3210cc5f2ea8bcb33d3/Sorting techniques/BubbleSort -------------------------------------------------------------------------------- /Sorting techniques/BubbleSort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void bubbleSort(int arr[], int n){ 5 | 6 | for (int i = 0 ; i < n - 1; ++i) 7 | { 8 | for(int j = 0; j < n - i - 1; ++j){ 9 | if(arr[j] > arr[j + 1]){ 10 | 11 | // swap arr[j] and arr[j + 1] 12 | swap(arr[j],arr[j+1]); 13 | 14 | } 15 | } 16 | } 17 | 18 | } 19 | 20 | int main(){ 21 | 22 | int arr[] = {77,54,25,12,22,11}; 23 | int n = sizeof(arr)/sizeof(arr[0]); 24 | 25 | bubbleSort(arr,n); 26 | 27 | cout<<"Sorted array "; 28 | 29 | for(int i = 0 ; i < n ;++i){ 30 | cout< 2 | 3 | int partition(int arr[], int low, int high) { 4 | int pivot = arr[high]; 5 | int i = (low - 1); 6 | 7 | for (int j = low; j <= high - 1; ++j) { 8 | if (arr[j] < pivot) { 9 | ++i; 10 | std::swap(arr[i], arr[j]); 11 | } 12 | } 13 | 14 | std::swap(arr[i + 1], arr[high]); 15 | return (i + 1); 16 | } 17 | 18 | void quickSort(int arr[], int low, int high) { 19 | if (low < high) { 20 | int pivotIndex = partition(arr, low, high); 21 | 22 | quickSort(arr, low, pivotIndex - 1); 23 | quickSort(arr, pivotIndex + 1, high); 24 | } 25 | } 26 | 27 | int main() { 28 | int arr[] = {64, 25, 12, 22, 11}; 29 | int n = sizeof(arr) / sizeof(arr[0]); 30 | 31 | quickSort(arr, 0, n - 1); 32 | 33 | std::cout << "Sorted array: "; 34 | for (int i = 0; i < n; ++i) { 35 | std::cout << arr[i] << " "; 36 | } 37 | 38 | return 0; 39 | } 40 | -------------------------------------------------------------------------------- /Sorting techniques/SelectionSort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void selectionSort(int arr[], int n) { 4 | for (int i = 0; i < n - 1; ++i) { 5 | int min_index = i; 6 | for (int j = i + 1; j < n; ++j) { 7 | if (arr[j] < arr[min_index]) { 8 | min_index = j; 9 | } 10 | } 11 | // Swap the found minimum element with the first element 12 | std::swap(arr[i], arr[min_index]); 13 | } 14 | } 15 | 16 | int main() { 17 | int arr[] = {64, 25, 12, 22, 11}; 18 | int n = sizeof(arr) / sizeof(arr[0]); 19 | 20 | selectionSort(arr, n); 21 | 22 | std::cout << "Sorted array: "; 23 | for (int i = 0; i < n; ++i) { 24 | std::cout << arr[i] << " "; 25 | } 26 | 27 | return 0; 28 | } 29 | -------------------------------------------------------------------------------- /Stack/LIFO: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Pankaj-Str/Data-Structures-CPP/1655668903104335d240f3210cc5f2ea8bcb33d3/Stack/LIFO -------------------------------------------------------------------------------- /Stack/LIFO.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | // List In , First Out 6 | 7 | int main(){ 8 | 9 | // create an integer stack 10 | stack myStack; 11 | 12 | // push elements onto the stack 13 | 14 | myStack.push(10); 15 | myStack.push(20); 16 | myStack.push(30); 17 | 18 | // print the top element of the stack 19 | 20 | cout<<"Top Element of the stack : "<< myStack.top()< 2 | #include 3 | #include 4 | 5 | class ExpressionParser { 6 | public: 7 | ExpressionParser(const std::string& expression) : input(expression), position(0) {} 8 | 9 | double parse() { 10 | double result = parseAdditionSubtraction(); 11 | if (position < input.length()) { 12 | std::cerr << "Error: Unexpected character '" << input[position] << "'" << std::endl; 13 | // You can add more detailed error handling here 14 | } 15 | return result; 16 | } 17 | 18 | private: 19 | std::string input; 20 | size_t position; 21 | 22 | double parseAdditionSubtraction() { 23 | double left = parseMultiplicationDivision(); 24 | while (position < input.length()) { 25 | char op = input[position]; 26 | if (op != '+' && op != '-') { 27 | break; 28 | } 29 | position++; 30 | double right = parseMultiplicationDivision(); 31 | if (op == '+') { 32 | left += right; 33 | } else { 34 | left -= right; 35 | } 36 | } 37 | return left; 38 | } 39 | 40 | double parseMultiplicationDivision() { 41 | double left = parseTerm(); 42 | while (position < input.length()) { 43 | char op = input[position]; 44 | if (op != '*' && op != '/') { 45 | break; 46 | } 47 | position++; 48 | double right = parseTerm(); 49 | if (op == '*') { 50 | left *= right; 51 | } else { 52 | if (right == 0) { 53 | std::cerr << "Error: Division by zero" << std::endl; 54 | // You can add more detailed error handling here 55 | } else { 56 | left /= right; 57 | } 58 | } 59 | } 60 | return left; 61 | } 62 | 63 | double parseTerm() { 64 | if (position >= input.length()) { 65 | std::cerr << "Error: Unexpected end of expression" << std::endl; 66 | // You can add more detailed error handling here 67 | return 0.0; 68 | } 69 | 70 | char currentChar = input[position]; 71 | if (std::isdigit(currentChar)) { 72 | std::string number; 73 | while (position < input.length() && (std::isdigit(input[position]) || input[position] == '.')) { 74 | number += input[position]; 75 | position++; 76 | } 77 | return std::stod(number); 78 | } else if (currentChar == '(') { 79 | position++; 80 | double result = parseAdditionSubtraction(); 81 | if (position >= input.length() || input[position] != ')') { 82 | std::cerr << "Error: Unmatched parentheses" << std::endl; 83 | // You can add more detailed error handling here 84 | } else { 85 | position++; 86 | } 87 | return result; 88 | } else if (currentChar == '-') { 89 | position++; 90 | return -parseTerm(); 91 | } else { 92 | std::cerr << "Error: Unexpected character '" << currentChar << "'" << std::endl; 93 | // You can add more detailed error handling here 94 | return 0.0; 95 | } 96 | } 97 | }; 98 | 99 | int main() { 100 | std::string expression; 101 | std::cout << "Enter an arithmetic expression: "; 102 | std::getline(std::cin, expression); 103 | 104 | ExpressionParser parser(expression); 105 | double result = parser.parse(); 106 | 107 | if (result != 0.0) { 108 | std::cout << "Result: " << result << std::endl; 109 | } 110 | 111 | return 0; 112 | } 113 | -------------------------------------------------------------------------------- /Stack/README.md: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /Stack/StackExample.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main() { 5 | std::stack myStack; 6 | 7 | // Pushing elements onto the stack 8 | myStack.push(10); 9 | myStack.push(20); 10 | myStack.push(30); 11 | myStack.push(40); 12 | 13 | std::cout << "Stack size: " << myStack.size() << std::endl; 14 | 15 | // Top element of the stack 16 | std::cout << "Top element: " << myStack.top() << std::endl; 17 | 18 | // Popping elements from the stack 19 | myStack.pop(); 20 | myStack.pop(); 21 | 22 | std::cout << "Stack size after popping: " << myStack.size() << std::endl; 23 | 24 | // Check if the stack is empty 25 | if (myStack.empty()) { 26 | std::cout << "Stack is empty." << std::endl; 27 | } else { 28 | std::cout << "Stack is not empty." << std::endl; 29 | } 30 | 31 | // Display the remaining elements in the stack 32 | std::cout << "Remaining elements in the stack: "; 33 | while (!myStack.empty()) { 34 | std::cout << myStack.top() << " "; 35 | myStack.pop(); 36 | } 37 | std::cout << std::endl; 38 | 39 | return 0; 40 | } 41 | -------------------------------------------------------------------------------- /Tree Data Structure/README.md: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /Tree Data Structure/Table Heap/Heap_01.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | int main() { 6 | // Creating a table (vector of vectors) to represent a 2D array 7 | std::vector> table = { 8 | {4, 8, 12}, 9 | {6, 10, 14}, 10 | {2, 7, 9} 11 | }; 12 | 13 | // Flatten the table into a 1D vector 14 | std::vector flatTable; 15 | for (const auto& row : table) { 16 | flatTable.insert(flatTable.end(), row.begin(), row.end()); 17 | } 18 | 19 | // Convert the 1D vector into a max-heap 20 | std::make_heap(flatTable.begin(), flatTable.end(), std::less()); 21 | 22 | // Print the table and the max-heap 23 | std::cout << "Original Table:" << std::endl; 24 | for (const auto& row : table) { 25 | for (int value : row) { 26 | std::cout << value << " "; 27 | } 28 | std::cout << std::endl; 29 | } 30 | 31 | std::cout << "\nMax-Heap (from flattened table):" << std::endl; 32 | for (int value : flatTable) { 33 | std::cout << value << " "; 34 | } 35 | std::cout << std::endl; 36 | 37 | return 0; 38 | } 39 | -------------------------------------------------------------------------------- /Tree Data Structure/Table Heap/Table_heap: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Pankaj-Str/Data-Structures-CPP/1655668903104335d240f3210cc5f2ea8bcb33d3/Tree Data Structure/Table Heap/Table_heap -------------------------------------------------------------------------------- /Tree Data Structure/Table Heap/Table_heap.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | 8 | int main(){ 9 | 10 | vector minHeap; 11 | 12 | // insert elements into min-heap 13 | 14 | minHeap.push_back(4); 15 | minHeap.push_back(10); 16 | minHeap.push_back(3); 17 | minHeap.push_back(5); 18 | minHeap.push_back(70); 19 | 20 | //convert into vector into a min-heap 21 | 22 | make_heap(minHeap.begin(),minHeap.end(),greater()); 23 | 24 | // print the min-heap 25 | 26 | cout<<"MIn - Heap "; 27 | for(int value : minHeap){ 28 | cout<()); 35 | minHeap.pop_back(); 36 | 37 | // print the min- heap after extraction 38 | 39 | cout<<" MIN - heap after extracting "< 2 | #include 3 | #include 4 | 5 | int main() { 6 | // Creating a table (vector) to represent data 7 | std::vector dataTable = {4, 8, 12, 6, 10, 14, 2, 7, 9}; 8 | 9 | // Convert the vector into a max-heap 10 | std::make_heap(dataTable.begin(), dataTable.end(), std::less()); 11 | 12 | // Print the original table and the max-heap 13 | std::cout << "Original Table:" << std::endl; 14 | for (int value : dataTable) { 15 | std::cout << value << " "; 16 | } 17 | std::cout << std::endl; 18 | 19 | std::cout << "\nMax-Heap:" << std::endl; 20 | for (int value : dataTable) { 21 | std::cout << value << " "; 22 | } 23 | std::cout << std::endl; 24 | 25 | return 0; 26 | } 27 | -------------------------------------------------------------------------------- /Tree Data Structure/Tree Hash/Tree_hash.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int main(){ 6 | 7 | // create a map represent a hash table 8 | 9 | unordered_map treeHash; 10 | 11 | // Inserting kay and value into hash table 12 | 13 | treeHash["apple"] = 200; 14 | treeHash["banana"] = 300; 15 | treeHash["orange"] = 400; 16 | 17 | 18 | // accessing values using keys 19 | 20 | cout<<"Price of apple : " < 2 | #include 3 | 4 | struct TreeNode { 5 | int data; 6 | TreeNode* left; 7 | TreeNode* right; 8 | 9 | TreeNode(int value) : data(value), left(nullptr), right(nullptr) {} 10 | }; 11 | 12 | // Function to build a binary tree and hash its elements 13 | void buildTreeAndHash(TreeNode* &root, std::unordered_map &hashTable) { 14 | // Inserting nodes into the binary tree and hashing their values 15 | root = new TreeNode(10); 16 | hashTable[10] = 1; 17 | 18 | root->left = new TreeNode(5); 19 | hashTable[5] = 2; 20 | 21 | root->right = new TreeNode(15); 22 | hashTable[15] = 3; 23 | } 24 | 25 | int main() { 26 | TreeNode* root = nullptr; 27 | std::unordered_map hashTable; 28 | 29 | // Build a binary tree and hash its elements 30 | buildTreeAndHash(root, hashTable); 31 | 32 | // Accessing values using keys from the hash table 33 | std::cout << "Value corresponding to key 10: " << hashTable[10] << std::endl; 34 | std::cout << "Value corresponding to key 5: " << hashTable[5] << std::endl; 35 | std::cout << "Value corresponding to key 15: " << hashTable[15] << std::endl; 36 | 37 | return 0; 38 | } 39 | -------------------------------------------------------------------------------- /Tree Data Structure/simple_binary_tree.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | // Node structure for a binary tree 4 | struct TreeNode { 5 | int data; 6 | TreeNode* left; 7 | TreeNode* right; 8 | 9 | // Constructor 10 | TreeNode(int value) : data(value), left(nullptr), right(nullptr) {} 11 | }; 12 | 13 | // Function to perform an in-order traversal of the binary tree 14 | void inOrderTraversal(TreeNode* root) { 15 | if (root != nullptr) { 16 | inOrderTraversal(root->left); 17 | std::cout << root->data << " "; 18 | inOrderTraversal(root->right); 19 | } 20 | } 21 | 22 | // Function to insert a node into the binary tree 23 | TreeNode* insertNode(TreeNode* root, int value) { 24 | if (root == nullptr) { 25 | return new TreeNode(value); 26 | } 27 | 28 | if (value < root->data) { 29 | root->left = insertNode(root->left, value); 30 | } else { 31 | root->right = insertNode(root->right, value); 32 | } 33 | 34 | return root; 35 | } 36 | 37 | int main() { 38 | // Creating an empty binary tree 39 | TreeNode* root = nullptr; 40 | 41 | // Inserting nodes into the binary tree 42 | root = insertNode(root, 10); 43 | root = insertNode(root, 5); 44 | root = insertNode(root, 15); 45 | root = insertNode(root, 3); 46 | root = insertNode(root, 7); 47 | 48 | // Performing an in-order traversal 49 | std::cout << "In-order traversal: "; 50 | inOrderTraversal(root); 51 | std::cout << std::endl; 52 | 53 | return 0; 54 | } 55 | // TreeNode is a structure representing a node in the binary tree. 56 | // insertNode is a function for inserting a new node into the binary tree based on the node's value. 57 | // inOrderTraversal is a function that performs an in-order traversal of the binary tree, printing the values of the nodes. --------------------------------------------------------------------------------