├── .gitignore ├── DLL.cpp ├── Graph Programs ├── graph_adjacency_list.cpp ├── graph_adjacency_matrix.cpp └── graph_topological_sort.cpp ├── Patterns ├── pattern1.cpp ├── pattern2.cpp ├── pattern3.cpp ├── pattern4.cpp ├── pattern6.cpp └── pattern7.cpp ├── Plan.md ├── Queue └── Queue.cpp ├── README.md ├── SLL.cpp ├── Searching Techniques └── MEDIAN_SEARCH.cpp ├── Searching problems ├── BINARY_SEARCH.cpp ├── BruteForce.cpp ├── LINEAR_SEARCH.cpp ├── RabinKarp.cpp └── ternarySearch.cpp ├── Sorting ├── Heapsort.cpp ├── bubblesort.c ├── bucketsort.cpp ├── count_sort.c ├── countingsort.cpp ├── insertionsort.cpp ├── mergesort.cpp ├── quicksort.c ├── radixsort.cpp ├── selectionsort.c └── shellsort.c ├── Stack ├── Stack.cpp └── Stack2.cpp ├── Tree Problems ├── BINARY_SEARCH_TREE.cpp └── TREE.cpp ├── dfs.c ├── image.jpg └── xorlist.c /.gitignore: -------------------------------------------------------------------------------- 1 | # Prerequisites 2 | *.d 3 | 4 | # Compiled Object files 5 | *.slo 6 | *.lo 7 | *.o 8 | *.obj 9 | 10 | # Precompiled Headers 11 | *.gch 12 | *.pch 13 | 14 | # Compiled Dynamic libraries 15 | *.so 16 | *.dylib 17 | *.dll 18 | 19 | # Fortran module files 20 | *.mod 21 | *.smod 22 | 23 | # Compiled Static libraries 24 | *.lai 25 | *.la 26 | *.a 27 | *.lib 28 | 29 | # Executables 30 | *.exe 31 | *.out 32 | *.app 33 | 34 | # General 35 | *.DS_Store 36 | .AppleDouble 37 | .LSOverride 38 | 39 | # Icon must end with two \r 40 | Icon 41 | 42 | 43 | # Thumbnails 44 | ._* 45 | 46 | # Files that might appear in the root of a volume 47 | .DocumentRevisions-V100 48 | .fseventsd 49 | .Spotlight-V100 50 | .TemporaryItems 51 | .Trashes 52 | .VolumeIcon.icns 53 | .com.apple.timemachine.donotpresent 54 | 55 | # Directories potentially created on remote AFP share 56 | .AppleDB 57 | .AppleDesktop 58 | Network Trash Folder 59 | Temporary Items 60 | .apdisk 61 | 62 | -------------------------------------------------------------------------------- /DLL.cpp: -------------------------------------------------------------------------------- 1 | // A complete working C program to demonstrate all insertion methods 2 | #include 3 | #include 4 | 5 | // A linked list node 6 | struct Node 7 | { 8 | int data; 9 | struct Node *next; 10 | struct Node *prev; 11 | }; 12 | 13 | /* Given a reference (pointer to pointer) to the head of a list 14 | and an int, inserts a new node on the front of the list. */ 15 | void push(struct Node** head_ref, int new_data) 16 | { 17 | /* 1. allocate node */ 18 | struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); 19 | 20 | /* 2. put in the data */ 21 | new_node->data = new_data; 22 | 23 | /* 3. Make next of new node as head and previous as NULL */ 24 | new_node->next = (*head_ref); 25 | new_node->prev = NULL; 26 | 27 | /* 4. change prev of head node to new node */ 28 | if((*head_ref) != NULL) 29 | (*head_ref)->prev = new_node ; 30 | 31 | /* 5. move the head to point to the new node */ 32 | (*head_ref) = new_node; 33 | } 34 | 35 | /* Given a node as prev_node, insert a new node after the given node */ 36 | void insertAfter(struct Node* prev_node, int new_data) 37 | { 38 | /*1. check if the given prev_node is NULL */ 39 | if (prev_node == NULL) 40 | { 41 | printf("the given previous node cannot be NULL"); 42 | return; 43 | } 44 | 45 | /* 2. allocate new node */ 46 | struct Node* new_node =(struct Node*) malloc(sizeof(struct Node)); 47 | 48 | /* 3. put in the data */ 49 | new_node->data = new_data; 50 | 51 | /* 4. Make next of new node as next of prev_node */ 52 | new_node->next = prev_node->next; 53 | 54 | /* 5. Make the next of prev_node as new_node */ 55 | prev_node->next = new_node; 56 | 57 | /* 6. Make prev_node as previous of new_node */ 58 | new_node->prev = prev_node; 59 | 60 | /* 7. Change previous of new_node's next node */ 61 | if (new_node->next != NULL) 62 | new_node->next->prev = new_node; 63 | } 64 | 65 | /* Given a reference (pointer to pointer) to the head 66 | of a DLL and an int, appends a new node at the end */ 67 | void append(struct Node** head_ref, int new_data) 68 | { 69 | /* 1. allocate node */ 70 | struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); 71 | 72 | struct Node *last = *head_ref; /* used in step 5*/ 73 | 74 | /* 2. put in the data */ 75 | new_node->data = new_data; 76 | 77 | /* 3. This new node is going to be the last node, so 78 | make next of it as NULL*/ 79 | new_node->next = NULL; 80 | 81 | /* 4. If the Linked List is empty, then make the new 82 | node as head */ 83 | if (*head_ref == NULL) 84 | { 85 | new_node->prev = NULL; 86 | *head_ref = new_node; 87 | return; 88 | } 89 | 90 | /* 5. Else traverse till the last node */ 91 | while (last->next != NULL) 92 | last = last->next; 93 | 94 | /* 6. Change the next of last node */ 95 | last->next = new_node; 96 | 97 | /* 7. Make last node as previous of new node */ 98 | new_node->prev = last; 99 | 100 | return; 101 | } 102 | 103 | // This function prints contents of linked list starting from the given node 104 | void printList(struct Node *node) 105 | { 106 | struct Node *last; 107 | printf("\nTraversal in forward direction \n"); 108 | while (node != NULL) 109 | { 110 | printf(" %d ", node->data); 111 | last = node; 112 | node = node->next; 113 | } 114 | 115 | printf("\nTraversal in reverse direction \n"); 116 | while (last != NULL) 117 | { 118 | printf(" %d ", last->data); 119 | last = last->prev; 120 | } 121 | } 122 | 123 | /* Drier program to test above functions*/ 124 | int main() 125 | { 126 | /* Start with the empty list */ 127 | struct Node* head = NULL; 128 | 129 | // Insert 6. So linked list becomes 6->NULL 130 | append(&head, 6); 131 | 132 | // Insert 7 at the beginning. So linked list becomes 7->6->NULL 133 | push(&head, 7); 134 | 135 | // Insert 1 at the beginning. So linked list becomes 1->7->6->NULL 136 | push(&head, 1); 137 | 138 | // Insert 4 at the end. So linked list becomes 1->7->6->4->NULL 139 | append(&head, 4); 140 | 141 | // Insert 8, after 7. So linked list becomes 1->7->8->6->4->NULL 142 | insertAfter(head->next, 8); 143 | 144 | printf("Created DLL is: "); 145 | printList(head); 146 | 147 | getchar(); 148 | return 0; 149 | } 150 | -------------------------------------------------------------------------------- /Graph Programs/graph_adjacency_list.cpp: -------------------------------------------------------------------------------- 1 | // A C++ Program to demonstrate adjacency list representation of graphs 2 | 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | // A structure to represent an adjacency list node 10 | struct AdjListNode 11 | { 12 | int dest; 13 | struct AdjListNode* next; 14 | }; 15 | 16 | // A structure to represent an adjacency list 17 | struct AdjList 18 | { 19 | struct AdjListNode *head; // pointer to head node of list 20 | }; 21 | 22 | // A structure to represent a graph. A graph is an array of adjacency lists. 23 | // Size of array will be V (number of vertices in graph) 24 | struct Graph 25 | { 26 | int V; 27 | struct AdjList* array; 28 | }; 29 | 30 | // A utility function to create a new adjacency list node 31 | struct AdjListNode* newAdjListNode(int dest) 32 | { 33 | struct AdjListNode* newNode = 34 | (struct AdjListNode*) malloc(sizeof(struct AdjListNode)); 35 | newNode->dest = dest; 36 | newNode->next = NULL; 37 | return newNode; 38 | } 39 | 40 | // A utility function that creates a graph of V vertices 41 | struct Graph* createGraph(int V) 42 | { 43 | struct Graph* graph = (struct Graph*) malloc(sizeof(struct Graph)); 44 | graph->V = V; 45 | 46 | // Create an array of adjacency lists. Size of array will be V 47 | graph->array = (struct AdjList*) malloc(V * sizeof(struct AdjList)); 48 | 49 | // Initialize each adjacency list as empty by making head as NULL 50 | int i; 51 | for (i = 0; i < V; ++i) 52 | graph->array[i].head = NULL; 53 | 54 | return graph; 55 | } 56 | 57 | // Adds an edge to an undirected graph 58 | void addEdge(struct Graph* graph, int src, int dest) 59 | { 60 | // Add an edge from src to dest. A new node is added to the adjacency 61 | // list of src. The node is added at the begining 62 | struct AdjListNode* newNode = newAdjListNode(dest); 63 | newNode->next = graph->array[src].head; 64 | graph->array[src].head = newNode; 65 | 66 | // Since graph is undirected, add an edge from dest to src also 67 | newNode = newAdjListNode(src); 68 | newNode->next = graph->array[dest].head; 69 | graph->array[dest].head = newNode; 70 | } 71 | 72 | // A utility function to print the adjacenncy list representation of graph 73 | void printGraph(struct Graph* graph) 74 | { 75 | int v; 76 | for (v = 0; v < graph->V; ++v) 77 | { 78 | struct AdjListNode* pCrawl = graph->array[v].head; 79 | printf("\n Adjacency list of vertex %d\n head ", v); 80 | while (pCrawl) 81 | { 82 | printf("-> %d", pCrawl->dest); 83 | pCrawl = pCrawl->next; 84 | } 85 | printf("\n"); 86 | } 87 | } 88 | 89 | // Driver program to test above functions 90 | int main() 91 | { 92 | int choice,initial_vertex,dest_vertex,no_of_vertex; 93 | cout << "Enter the number of vertices"; 94 | cin >> no_of_vertex; 95 | struct Graph* graph = createGraph(no_of_vertex); 96 | while(1){ 97 | cout << "1. Enter a new edge\n"; 98 | cout << "2. Print graph\n"; 99 | cout << "3.Exit"; 100 | cout << "Enter your choice"; 101 | cin >> choice; 102 | switch(choice){ 103 | case 1: cout << "Enter the initial vertex"; 104 | cin >> initial_vertex; 105 | cout << "Enter the destination vertex"; 106 | cin >> dest_vertex; 107 | addEdge(graph,initial_vertex,dest_vertex); 108 | break; 109 | 110 | case 2: 111 | // print the adjacency list representation of the above graph 112 | printGraph(graph); 113 | break; 114 | } 115 | if(choice==3){ 116 | break; 117 | } 118 | } 119 | } -------------------------------------------------------------------------------- /Graph Programs/graph_adjacency_matrix.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * C++ Program to Implement Adjacency Matrix 3 | */ 4 | #include 5 | #include 6 | using namespace std; 7 | #define MAX 20 8 | /* 9 | * Adjacency Matrix Class 10 | */ 11 | class AdjacencyMatrix 12 | { 13 | private: 14 | int n; 15 | int **adj; 16 | bool *visited; 17 | public: 18 | AdjacencyMatrix(int n) 19 | { 20 | this->n = n; 21 | visited = new bool [n]; 22 | adj = new int* [n]; 23 | for (int i = 0; i < n; i++) 24 | { 25 | adj[i] = new int [n]; 26 | for(int j = 0; j < n; j++) 27 | { 28 | adj[i][j] = 0; 29 | } 30 | } 31 | } 32 | /* 33 | * Adding Edge to Graph 34 | */ 35 | void add_edge(int origin, int destin) 36 | { 37 | if( origin > n || destin > n || origin < 0 || destin < 0) 38 | { 39 | cout<<"Invalid edge!\n"; 40 | } 41 | else 42 | { 43 | adj[origin - 1][destin - 1] = 1; 44 | } 45 | } 46 | /* 47 | * Print the graph 48 | */ 49 | void display() 50 | { 51 | int i,j; 52 | for(i = 0;i < n;i++) 53 | { 54 | for(j = 0; j < n; j++) 55 | cout<>nodes; 68 | AdjacencyMatrix am(nodes); 69 | max_edges = nodes * (nodes - 1); 70 | for (int i = 0; i < max_edges; i++) 71 | { 72 | cout<<"Enter edge (-1 -1 to exit): "; 73 | cin>>origin>>destin; 74 | if((origin == -1) && (destin == -1)) 75 | break; 76 | am.add_edge(origin, destin); 77 | } 78 | am.display(); 79 | return 0; 80 | } -------------------------------------------------------------------------------- /Graph Programs/graph_topological_sort.cpp: -------------------------------------------------------------------------------- 1 | // A C++ program to print topological sorting of a DAG 2 | #include 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | // Class to represent a graph 8 | class Graph 9 | { 10 | int V; // No. of vertices' 11 | 12 | // Pointer to an array containing adjacency listsList 13 | list *adj; 14 | 15 | // A function used by topologicalSort 16 | void topologicalSortUtil(int v, bool visited[], stack &Stack); 17 | public: 18 | Graph(int V); // Constructor 19 | 20 | // function to add an edge to graph 21 | void addEdge(int v, int w); 22 | 23 | // prints a Topological Sort of the complete graph 24 | void topologicalSort(); 25 | }; 26 | 27 | Graph::Graph(int V) 28 | { 29 | this->V = V; 30 | adj = new list[V]; 31 | } 32 | 33 | void Graph::addEdge(int v, int w) 34 | { 35 | adj[v].push_back(w); // Add w to v’s list. 36 | } 37 | 38 | // A recursive function used by topologicalSort 39 | void Graph::topologicalSortUtil(int v, bool visited[], 40 | stack &Stack) 41 | { 42 | // Mark the current node as visited. 43 | visited[v] = true; 44 | 45 | // Recur for all the vertices adjacent to this vertex 46 | list::iterator i; 47 | for (i = adj[v].begin(); i != adj[v].end(); ++i) 48 | if (!visited[*i]) 49 | topologicalSortUtil(*i, visited, Stack); 50 | 51 | // Push current vertex to stack which stores result 52 | Stack.push(v); 53 | } 54 | 55 | // The function to do Topological Sort. It uses recursive 56 | // topologicalSortUtil() 57 | void Graph::topologicalSort() 58 | { 59 | stack Stack; 60 | 61 | // Mark all the vertices as not visited 62 | bool *visited = new bool[V]; 63 | for (int i = 0; i < V; i++) 64 | visited[i] = false; 65 | 66 | // Call the recursive helper function to store Topological 67 | // Sort starting from all vertices one by one 68 | for (int i = 0; i < V; i++) 69 | if (visited[i] == false) 70 | topologicalSortUtil(i, visited, Stack); 71 | 72 | // Print contents of stack 73 | while (Stack.empty() == false) 74 | { 75 | cout << Stack.top() << " "; 76 | Stack.pop(); 77 | } 78 | } 79 | 80 | // Driver program to test above functions 81 | // Driver program to test above functions 82 | int main() 83 | { 84 | // Create a graph given in the above diagram 85 | int choice,initial_vertex,dest_vertex,no_of_vertex; 86 | cout << "Enter the number of vertices"; 87 | cin >> no_of_vertex; 88 | Graph g(no_of_vertex); 89 | while(1){ 90 | cout << "1. Enter a new edge\n"; 91 | cout << "2. Print graph\n"; 92 | cout << "3.Exit"; 93 | cout << "Enter your choice"; 94 | cin >> choice; 95 | switch(choice){ 96 | case 1: cout << "Enter the initial vertex\n"; 97 | cin >> initial_vertex; 98 | cout << "Enter the destination vertex\n"; 99 | cin >> dest_vertex; 100 | g.addEdge(initial_vertex,dest_vertex); 101 | break; 102 | 103 | case 2: 104 | cout << "Following is a Topological Sort of the given graph\n"; 105 | g.topologicalSort(); 106 | break; 107 | } 108 | if(choice==3){ 109 | break; 110 | } 111 | } 112 | 113 | return 0; 114 | } -------------------------------------------------------------------------------- /Patterns/pattern1.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main(){ 5 | 6 | int n; 7 | cin >> n; //Input n to create a n*n square of stars (*) 8 | 9 | for( int i = 0; i < n; i++ ){ //Loop to iterate over 'n' number of rows 10 | for( int j = 0; j < n; j++ ){ //Loop to iterate over 'n' columns 11 | cout << "*"; 12 | } 13 | cout << endl; // Print next row in new line 14 | } 15 | return 0; 16 | 17 | } 18 | 19 | /* 20 | 5 21 | 22 | ***** 23 | ***** 24 | ***** 25 | ***** 26 | */ 27 | -------------------------------------------------------------------------------- /Patterns/pattern2.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main(){ 5 | 6 | int n; 7 | cin >> n; 8 | 9 | for( int i = 0; i < n; i++ ){ //Iterate over n rows 10 | for( int j = 0; j <= i; j++ ){ // Number of columns will be equal to one more than the row number (since rows are 0 indexed ) 11 | cout << "*"; 12 | } 13 | cout << endl; 14 | } 15 | 16 | return 0; 17 | 18 | } 19 | 20 | /* 21 | 5 22 | 23 | * 24 | ** 25 | *** 26 | **** 27 | ***** 28 | */ 29 | -------------------------------------------------------------------------------- /Patterns/pattern3.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main(){ 5 | 6 | int n; 7 | cin >> n; 8 | 9 | for( int i = n; i > 0; i-- ){ //Iterating over number of rows backwards from n down to 0 10 | for( int j = 0; j < i; j++ ){ // Number of columns with * will be equal to row number to form an upside down triangle 11 | cout << "*"; 12 | } 13 | cout << endl; 14 | } 15 | 16 | return 0; 17 | } 18 | 19 | /* 20 | 5 21 | 22 | ***** 23 | **** 24 | *** 25 | ** 26 | * 27 | 28 | */ 29 | -------------------------------------------------------------------------------- /Patterns/pattern4.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main(){ 5 | 6 | int n; 7 | cin >> n; // Accept n to construct : a right triangle with n rows followed by an upside down right triangle with n rows 8 | 9 | for( int i = 0; i < n; i++ ){ // Iterate over the number of rows for first triangle 10 | for( int j = 0; j <= i; j++ ){ // Number of stars in a column will be equal to the row number we are at currently. 11 | cout << "*"; // Print * 12 | } 13 | cout << endl; // Mover over to the next row 14 | } 15 | 16 | for( int i = n-1; i > 0; i-- ){ // Iterate backwards from n to 0 to construct an upside down triangle with n rows 17 | for( int j = 0; j < i; j++ ){ // Number of stars in a column will be equal to the row number we are at currently. 18 | cout << "*"; // Print * 19 | } 20 | cout << endl; // Move to the next row 21 | } 22 | 23 | return 0; 24 | 25 | } 26 | 27 | /* 28 | 29 | 5 30 | 31 | * 32 | ** 33 | *** 34 | **** 35 | ***** 36 | **** 37 | *** 38 | ** 39 | * 40 | 41 | */ 42 | -------------------------------------------------------------------------------- /Patterns/pattern6.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main(){ 5 | 6 | /* Accept the number of rows to be printed */ 7 | int n; 8 | cin >> n; 9 | 10 | /* Print a row 11 | * Number of elements in a row = row count. 12 | * eg. row1 has 1 element, row 2 has 2 elements, so on... 13 | */ 14 | for( int i = 1; i <= n; i++ ){ 15 | /* Print the same number repeatedly */ 16 | for( int j = 1; j <= i; j++ ){ 17 | cout << i; 18 | } 19 | /* Once all the numbers of a row a printed, 20 | * print a newline before starting the next row. 21 | */ 22 | cout << endl; 23 | } 24 | 25 | return 0; 26 | } 27 | 28 | /* 29 | 30 | 5 31 | 32 | 1 33 | 22 34 | 333 35 | 4444 36 | 55555 37 | 38 | */ 39 | -------------------------------------------------------------------------------- /Patterns/pattern7.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main(){ 5 | 6 | /* Accept the number of rows to be printed */ 7 | int n; 8 | cin >> n; 9 | 10 | /* Initialise the number to be printed */ 11 | int count = 1; 12 | 13 | /* Begin printing numbers from 1 to n */ 14 | 15 | /* Print a row 16 | * Number of elements in a row = row count. 17 | * eg. row1 has 1 element, row 2 has 2 elements, 18 | */ 19 | for( int i = 0; i < n; i++ ){ 20 | /* Print the numbers in a particular row. 21 | * Each number is followed by a single space 22 | */ 23 | for( int j = 0; j <= i; j++ ){ 24 | cout << count << " "; 25 | count++; 26 | } 27 | /* Once all the numbers of a row a printed, 28 | * print a newline before starting the next row. 29 | */ 30 | cout << endl; 31 | } 32 | 33 | return 0; 34 | 35 | } 36 | 37 | /* 38 | 39 | 5 40 | 41 | 1 42 | 2 3 43 | 4 5 6 44 | 7 8 9 10 45 | 11 12 13 14 15 46 | 47 | */ 48 | -------------------------------------------------------------------------------- /Plan.md: -------------------------------------------------------------------------------- 1 | #### Plan 2 | -[ ] [Linked list] 3 | - [ ] [Singly Linked list] 4 | - [ ] [Doubly Linked list] 5 | - [ ] Circular Linked list 6 | - [ ] Memory efficient doubly Linked list 7 | - [ ] Skip Linked list 8 | - [ ] Unrolled Linked list 9 | 10 | - [ ] [Stacks] 11 | 12 | - [ ] [Queues] 13 | 14 | - [ ] [Sorting] 15 | - [ ] Bubble sort 16 | - [ ] Merge sort 17 | - [ ] Insertion sort 18 | - [ ] Selection sort 19 | - [ ] Quick sort 20 | - [ ] Topological sort 21 | - [ ] Heap sort 22 | - [ ] Bucket sort 23 | - [ ] Shell sort 24 | 25 | - [ ] [Heap] 26 | 27 | - [ ] [Tree] 28 | - [ ] [general tree] 29 | - [ ] [BST] 30 | 31 | - [ ] Searching 32 | - [ ] Binary search 33 | - [ ] Jump search 34 | - [ ] Fibonacci search 35 | - [ ] Depth First Search 36 | - [ ] Breadth First Search 37 | - [ ] Kosaraju's Algorithm (find all SCCs) 38 | 39 | - [ ] Backtrack 40 | - [ ] anagram 41 | - [ ] array sum combinations 42 | - [ ] combination sum 43 | - [ ] expression add operators 44 | - [ ] factor combinations 45 | - [ ] generate abbreviations 46 | - [ ] generate parenthesis 47 | - [ ] letter combination 48 | - [ ] palindrome partitioning 49 | - [ ] pattern match 50 | - [ ] permute 51 | - [ ] permute unique 52 | - [ ] subsets 53 | - [ ] subsets unique 54 | 55 | - [ ] Array 56 | - [ ] next_permutation 57 | -------------------------------------------------------------------------------- /Queue/Queue.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | using namespace std; 4 | 5 | struct node 6 | { 7 | int data; 8 | struct node * next; 9 | }; 10 | 11 | struct qu 12 | { 13 | struct node *f; 14 | struct node *r; 15 | }; 16 | void initialise(struct qu* q) 17 | { q->f=q->r=NULL; 18 | 19 | } 20 | 21 | void create(struct qu *q,int item) 22 | { 23 | struct node *newnode; 24 | newnode =new node; 25 | if(newnode==NULL) 26 | cout<<"queue is full"; 27 | newnode->data=item; 28 | newnode->next=NULL; 29 | 30 | if(q->f==NULL) 31 | { 32 | q->f=q->r=newnode; 33 | } 34 | q->r->next=newnode; 35 | q->r=q->r->next; 36 | } 37 | 38 | void deleted(struct qu*q) 39 | { //cout<<"yes"; 40 | if(q->f == NULL) 41 | cout<<"empty"; 42 | // cout<<"yes"; 43 | // struct node *temp; 44 | // temp = q->f; 45 | q->f=q->f->next; 46 | 47 | 48 | if(q->f==NULL) 49 | q->r=NULL; 50 | 51 | 52 | 53 | 54 | 55 | } 56 | 57 | void display(struct qu *q) 58 | { 59 | if(q->f==NULL) 60 | cout<<"empty"; 61 | else 62 | { 63 | struct node * temp; 64 | while(q->f!=NULL) 65 | { //temp=q->f; 66 | cout<f->data<<"\n"; 67 | q->f=q->f->next; 68 | } 69 | //cout<f->data<<"\n"; 70 | } 71 | 72 | } 73 | 74 | int main() 75 | { 76 | struct qu q; 77 | 78 | int n,i,j; 79 | cin>>n; 80 | initialise(&q); 81 | for(i=0;i>j; 84 | create(&q,j); 85 | } 86 | display(&q); 87 | deleted(&q); 88 | cout<<"\n"; 89 | display(&q); 90 | 91 | } 92 | 93 | 94 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |
2 | 3 |
4 | 5 | # Data-Structures 6 | 7 | ### Implementation tree 8 | 9 | ``` 10 | Data Structures 11 | ├── Graph Programs 12 | │ ├── adjacency_list.hpp # graph implementation with adjacency list 13 | │ └── adjacency_matrix.hpp # graph implementation with adjacency matrix 14 | │ └── topological_sort.hpp # topological sort (adjacency list) 15 | ├── Heap Programs 16 | │ └── HEAP.cpp # heap implementation 17 | ├── Linked List Programs 18 | │ ├── DOUBLY_LINKED_LIST.cpp # doubly linked list 19 | │ └── SINGLY_LINKED_LIST.cpp # singly linked list 20 | ├── Queue Programs 21 | │ └── QUEUE.cpp # queue implementation 22 | ├── Sorting Programs 23 | │ ├── BUBBLE_SORT.cpp # bubble sort 24 | │ ├── INSERTION_SORT.cpp # insertion sort 25 | │ ├── MERGE_SORT.cpp # merge sort 26 | │ ├── QUICK_SORT.cpp # quick sort 27 | │ └── SELECTION_SORT.cpp # selection sort 28 | ├── Searching Programs 29 | │ ├── LINEAR_SEARCH.cpp # Linear search 30 | │ ├── BINARY_SEARCH.cpp # Binary search 31 | │ ├── Ternary_Search.cpp # Ternary search 32 | │ ├── Brute_Force.cpp # Brute force 33 | │ ├── Rabin_Karp.cpp # Rabin Karp 34 | ├── Stack Programs 35 | │ └── Stack.cpp # stack implementation 36 | └── Tree Programs 37 | ├── TREE.cpp # general tree implementation 38 | ├── SEGMENT_TREE.cpp # segment tree implementation 39 | └── BINARY_SEARCH_TREE.cpp # binary search tree 40 | ``` 41 | -------------------------------------------------------------------------------- /SLL.cpp: -------------------------------------------------------------------------------- 1 | // A simple C program for traversal of a linked list 2 | #include 3 | #include 4 | 5 | struct Node 6 | { 7 | int data; 8 | struct Node *next; 9 | }; 10 | 11 | // This function prints contents of linked list starting from 12 | // the given node 13 | void printList(struct Node *n) 14 | { 15 | while (n != NULL) 16 | { 17 | printf(" %d ", n->data); 18 | n = n->next; 19 | } 20 | } 21 | 22 | int main() 23 | { 24 | struct Node* head = NULL; 25 | struct Node* second = NULL; 26 | struct Node* third = NULL; 27 | 28 | // allocate 3 nodes in the heap 29 | head = (struct Node*)malloc(sizeof(struct Node)); 30 | second = (struct Node*)malloc(sizeof(struct Node)); 31 | third = (struct Node*)malloc(sizeof(struct Node)); 32 | 33 | head->data = 1; //assign data in first node 34 | head->next = second; // Link first node with second 35 | 36 | second->data = 2; //assign data to second node 37 | second->next = third; 38 | 39 | third->data = 3; //assign data to third node 40 | third->next = NULL; 41 | 42 | printList(head); 43 | 44 | return 0; 45 | } 46 | -------------------------------------------------------------------------------- /Searching Techniques/MEDIAN_SEARCH.cpp: -------------------------------------------------------------------------------- 1 | //Libraries Included 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | 7 | /* 8 | 9 | int findMedian() -> Returns the median of the input array. 10 | int partition() -> The partition work is done by this function. 11 | int kthSmallest() -> The recursive function that performs the major calculations 12 | of finding the kthSmallest element only on the condition that the 13 | value of k is less than the size of the array produced after after 14 | every recursive cycle. 15 | int main() -> Driver Function. 16 | */ 17 | 18 | 19 | /* 20 | predefined stuff -> 21 | 22 | sort() 23 | swap() 24 | INT_MAX 25 | */ 26 | int findMedian(int arr[], int size_of_array) 27 | { 28 | sort(arr, arr+size_of_array); // Sort the array 29 | return arr[size_of_array/2]; // Return middle element 30 | } 31 | 32 | int partition(int arr[], int low, int high, int variable_to_be_found) 33 | { 34 | // Search for variable_to_find in arr[low..high] and move it to end 35 | int i; 36 | for (i=low; i 0 && k <= high - low + 1) 60 | { 61 | int n = high-low+1; // Number of elements in arr[low..high] 62 | 63 | // Divide arr[] in groups of size 5, calculate median 64 | // of every group and store it in median[] array. 65 | int i, median[(n+4)/5]; // There will be floor((n+4)/5) groups; 66 | for (i=0; i k-1) // If position is more, recur for left 88 | return kthSmallest(arr, low, pos-1, k); 89 | 90 | // Else recur for right subarray 91 | return kthSmallest(arr, pos+1, high, k-pos+l-1); 92 | } 93 | 94 | // If k is more than number of elements in array 95 | return INT_MAX; 96 | } 97 | 98 | // It searches for x in arr[l..r], and partitions the array 99 | // around x. 100 | 101 | int main() 102 | { 103 | int arr[] = {12, 3, 5, 7, 4, 19, 26}; 104 | int n = sizeof(arr)/sizeof(arr[0]), k = 3; 105 | cout << "K'th smallest element is " 106 | << kthSmallest(arr, 0, n-1, k); 107 | return 0; 108 | } -------------------------------------------------------------------------------- /Searching problems/BINARY_SEARCH.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | const int N = 1000; 5 | int arr[N]; 6 | int n,m,k; 7 | int main() 8 | { 9 | //First we will load our array. It will be consisted of n integers. 10 | scanf("%d",&n); 11 | for(int i=0;i>1; 27 | //If our number at position midd is higher than the m that means that our 28 | //number is in the left side of the array, so we are putting the high to be midd -1 29 | //We checked that midd isn't our wanted element, so the element with tha highest id that we didn't 30 | //check is midd -1 so we are putting high to that value. 31 | //Because we are dividing our array by two each time we are getting complexity of O(log(N)) 32 | if(arr[midd]>m)high=midd-1; 33 | else low=midd; 34 | } 35 | //Complexity of the given solution is O(log(N)) 36 | if(arr[low]==m) 37 | printf("Found it on the %d-th position.\n",low+1); 38 | else 39 | printf("We didn't find it.\n"); 40 | return 0; 41 | } 42 | -------------------------------------------------------------------------------- /Searching problems/BruteForce.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | void main() 5 | { 6 | string originalString = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; 7 | string pattern = "IJKB"; 8 | bool patternFound = true; 9 | int i = -1; 10 | int size = originalString.length(); 11 | while (i < size) 12 | { 13 | patternFound = true; 14 | for (int j = 0; j < pattern.length(); j++) 15 | { 16 | i++; 17 | if (pattern[j] != originalString[i]) 18 | { 19 | patternFound = false; 20 | break; 21 | } 22 | } 23 | if (patternFound == true) 24 | { 25 | cout << "Pattern found at: " << i << endl; 26 | break; 27 | } 28 | } 29 | if (patternFound == false) 30 | { 31 | cout << "Pattern wasn't found " << endl; 32 | } 33 | system("pause"); 34 | } -------------------------------------------------------------------------------- /Searching problems/LINEAR_SEARCH.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | const int N = 1000; 5 | int arr[N]; 6 | int n,m,k; 7 | int main() 8 | { 9 | //First we will load our array. It will be consisted of n integers. 10 | scanf("%d",&n); 11 | for(int i=0;i 2 | #include 3 | #include 4 | // d is the number of characters in the input alphabet 5 | #define d 256 6 | using namespace std; 7 | void main() 8 | { 9 | int q = 101; // A prime number 10 | string originalString = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; 11 | string pattern = "IJK"; 12 | bool patternFound = true; 13 | int n = originalString.length(); //size of original string 14 | int m = pattern.length(); //size of pattern 15 | int t = 0; //hash value of original string 16 | int p = 0; //hash value of pattern 17 | int i, j; 18 | int h = 1; 19 | //pow(d,M-1)%q 20 | for (i = 0; i < m - 1; i++) 21 | { 22 | h = (h * d) % q; 23 | } 24 | 25 | for (i = 0; i < m; i++) 26 | { 27 | p = (d * p + pattern[i]) % q; 28 | t = (d * t + originalString[i]) % q; 29 | } 30 | 31 | for (i = 0; i <= n - m; i++) 32 | { 33 | if (p == t) 34 | { 35 | for (j = 0; j < m; j++) 36 | { 37 | if (originalString[i + j] != pattern[j]) 38 | break; 39 | } 40 | 41 | if (j == m) 42 | { 43 | cout << "Pattern found at index " << i << endl; 44 | break; 45 | } 46 | } 47 | 48 | if (i < n - m) 49 | { 50 | t = (d * (t - originalString[i] * h) + originalString[i + m]) % q; 51 | if (t < 0) //if value is negative 52 | { 53 | 54 | t = (t + q); 55 | } 56 | } 57 | } 58 | system("pause"); 59 | } -------------------------------------------------------------------------------- /Searching problems/ternarySearch.cpp: -------------------------------------------------------------------------------- 1 | //Ternary Search Uses Divide And Conquer Technique 2 | #include 3 | 4 | using namespace std; 5 | int ternarySearch(int arr[],int l,int r, int x){ 6 | if(r>=l){ 7 | int mid1 = l + (r-l)/3; 8 | int mid2 = r - (r-l)/3; 9 | if(arr[mid1] == x) 10 | return mid1; 11 | /* 12 | In this search, after each iteration it neglects (1/3)rd part of the array and repeats the same operations on the remaining 2/3rd part of array 13 | */ 14 | if(arr[mid2] == x) 15 | return mid2; 16 | if(xarr[mid2]) 19 | return ternarySearch(arr,mid2+1,r,x); 20 | else 21 | return ternarySearch(arr,mid1+1,mid2-1,x); 22 | } 23 | return -1; // if x is not found in array arr 24 | } 25 | int main(){ 26 | int arr[] = {1, 2, 3, 5}; 27 | int size = sizeof(arr)/ sizeof(arr[0]); 28 | int find = 3; 29 | cout<<"Position of "< 2 | using namespace std; 3 | 4 | // To heapify a subtree rooted with node i which is 5 | // an index in arr[]. n is size of heap 6 | void heapify(int arr[], int n, int i) 7 | { 8 | int largest = i; // Initialize largest as root 9 | int l = 2*i + 1; // left = 2*i + 1 10 | int r = 2*i + 2; // right = 2*i + 2 11 | 12 | // If left child is larger than root 13 | if (l < n && arr[l] > arr[largest]) 14 | largest = l; 15 | 16 | // If right child is larger than largest so far 17 | if (r < n && arr[r] > arr[largest]) 18 | largest = r; 19 | 20 | // If largest is not root 21 | if (largest != i) 22 | { 23 | swap(arr[i], arr[largest]); 24 | 25 | // Recursively heapify the affected sub-tree 26 | heapify(arr, n, largest); 27 | } 28 | } 29 | 30 | // main function to do heap sort 31 | void heapSort(int arr[], int n) 32 | { 33 | // Build heap (rearrange array) 34 | for (int i = n / 2 - 1; i >= 0; i--) 35 | heapify(arr, n, i); 36 | 37 | // One by one extract an element from heap 38 | for (int i=n-1; i>=0; i--) 39 | { 40 | // Move current root to end 41 | swap(arr[0], arr[i]); 42 | 43 | // call max heapify on the reduced heap 44 | heapify(arr, i, 0); 45 | } 46 | } 47 | 48 | /* A utility function to print array of size n */ 49 | void printArray(int arr[], int n) 50 | { 51 | for (int i=0; i 2 | #define MAX 100 3 | int main(void) 4 | { 5 | int arr[MAX],i,j,temp,n,xchanges; 6 | printf("Enter the number of elements : "); 7 | scanf("%d",&n); 8 | for(i=0; i arr[j+1]) 20 | { 21 | temp = arr[j]; 22 | arr[j] = arr[j+1]; 23 | arr[j+1] = temp; 24 | xchanges++; 25 | } 26 | } 27 | if(xchanges==0) /*If list is sorted*/ 28 | break; 29 | } 30 | printf("Sorted list is :\n"); 31 | for(i=0; i 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 3 | #include 4 | #define RANGE 255 5 | 6 | // The main function that sort the given string arr[] in 7 | // alphabatical order 8 | void countSort(char arr[]) 9 | { 10 | // The output character array that will have sorted arr 11 | char output[strlen(arr)]; 12 | 13 | // Create a count array to store count of inidividul 14 | // characters and initialize count array as 0 15 | int count[RANGE + 1], i; 16 | memset(count, 0, sizeof(count)); 17 | 18 | // Store count of each character 19 | for(i = 0; arr[i]; ++i) 20 | ++count[arr[i]]; 21 | 22 | // Change count[i] so that count[i] now contains actual 23 | // position of this character in output array 24 | for (i = 1; i <= RANGE; ++i) 25 | count[i] += count[i-1]; 26 | 27 | // Build the output character array 28 | for (i = 0; arr[i]; ++i) 29 | { 30 | output[count[arr[i]]-1] = arr[i]; 31 | --count[arr[i]]; 32 | } 33 | 34 | // Copy the output array to arr, so that arr now 35 | // contains sorted characters 36 | for (i = 0; arr[i]; ++i) 37 | arr[i] = output[i]; 38 | } 39 | 40 | // Driver program to test above function 41 | int main() 42 | { 43 | char arr[] = "array";//"applepp"; 44 | 45 | countSort(arr); 46 | 47 | printf("Sorted character array is %sn", arr); 48 | return 0; 49 | } 50 | -------------------------------------------------------------------------------- /Sorting/countingsort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void CounterSort(int a[], int n, int r, int lower) 5 | { 6 | int i, j = 0, counter[r] = {0}; 7 | // Counting the number occurrence of each element. 8 | for(i=0; i 0) 22 | goto flag; 23 | i++; 24 | } 25 | } 26 | 27 | int main() 28 | { 29 | int n, i, range, ulimit, llimit; 30 | cout<<"\nEnter the number of elements: "; 31 | cin>>n; 32 | 33 | cout<<"\nEnter the lower and upper limit of the data: "; 34 | cin>>llimit>>ulimit; 35 | 36 | // Range of the input data. 37 | range = ulimit-llimit+1; 38 | 39 | int arr[n]; 40 | for(i = 0; i < n; i++) 41 | { 42 | cout<<"Enter element "<>arr[i]; 44 | } 45 | 46 | CounterSort(arr, n, range, llimit); 47 | 48 | // Printing the sorted data. 49 | cout<<"\nSorted Data "; 50 | for (i = 0; i < n; i++) 51 | cout<<"->"< 2 | using namespace std; 3 | 4 | void insertionSort(int a[],int n){ 5 | for(int i=1;i=1;j--){ 7 | if (a[j] 3 | void swap(int* a, int* b) 4 | { 5 | int t = *a; 6 | *a = *b; 7 | *b = t; 8 | } 9 | int partition (int arr[], int low, int high) 10 | { 11 | int pivot = arr[high]; // pivot 12 | int i = (low - 1); // Index of smaller element 13 | 14 | for (int j = low; j <= high- 1; j++) 15 | { 16 | 17 | if (arr[j] <= pivot) 18 | { 19 | i++; 20 | swap(&arr[i], &arr[j]); 21 | } 22 | } 23 | swap(&arr[i + 1], &arr[high]); 24 | return (i + 1); 25 | } 26 | 27 | void quickSort(int arr[], int low, int high) 28 | { 29 | if (low < high) 30 | { 31 | int pi = partition(arr, low, high); 32 | 33 | quickSort(arr, low, pi - 1); 34 | quickSort(arr, pi + 1, high); 35 | } 36 | } 37 | 38 | void printArray(int arr[], int size) 39 | { 40 | int i; 41 | for (i=0; i < size; i++) 42 | printf("%d ", arr[i]); 43 | printf("\n"); 44 | } 45 | int main() 46 | { 47 | int arr[] = {10, 7, 8, 9, 1, 5}; 48 | int n = sizeof(arr)/sizeof(arr[0]); 49 | quickSort(arr, 0, n-1); 50 | printf("Sorted array: \n"); 51 | printArray(arr, n); 52 | return 0; 53 | } 54 | -------------------------------------------------------------------------------- /Sorting/radixsort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void countSort(int arr[], int n, int exp){ 5 | int output[n+1]; // output array 6 | int i,freq[10] = {0}; 7 | for(i=0;i=0;i--){ 12 | output[freq[(arr[i]/exp)%10]-1]=arr[i]; 13 | freq[(arr[i]/exp)%10]--; 14 | } 15 | for (i = 0; i < n; i++) 16 | arr[i] = output[i]; 17 | } 18 | void radixsort(int arr[], int n) 19 | { 20 | int m = arr[0]; 21 | for(int i=1;im) 23 | m=arr[i]; 24 | for (int exp = 1; m/exp > 0; exp *= 10) 25 | countSort(arr, n, exp); 26 | } 27 | void print(int arr[],int n){ 28 | for (int i=0;i 2 | #define MAX 100 3 | int main(void) 4 | { 5 | int arr[MAX],i,j,k,n; 6 | printf("Enter the number of elements : "); 7 | scanf("%d",&n); 8 | for(i=0; i=0 && k 2 | 3 | void shellsort(int arr[], int num) 4 | 5 | { 6 | int i, j, k, tmp; 7 | for (i = num / 2; i > 0; i = i / 2) 8 | { 9 | 10 | // Do a gapped insertion sort for this gap size. 11 | // The first gap elements a[0..i-1] are already in 12 | //gapped order keep adding one more element until the 13 | //entire array is gap sorted. 14 | for (j = i; j < num; j++) 15 | { 16 | for(k = j - i; k >= 0; k = k - i) 17 | { 18 | if (arr[k+i] >= arr[k]) 19 | break; 20 | else 21 | { 22 | tmp = arr[k]; 23 | arr[k] = arr[k+i]; 24 | arr[k+i] = tmp; 25 | } 26 | } 27 | } 28 | } 29 | } 30 | 31 | int main() 32 | 33 | { 34 | int arr[30]; 35 | int k, num; 36 | printf("Enter total no. of elements : "); 37 | scanf("%d", &num); 38 | printf("\nEnter %d numbers: ", num); 39 | for (k = 0 ; k < num; k++) 40 | { 41 | scanf("%d", &arr[k]); 42 | } 43 | shellsort(arr, num); 44 | printf("\n Sorted array is: "); 45 | for (k = 0; k < num; k++) 46 | printf("%d ", arr[k]); 47 | return 0; 48 | 49 | } -------------------------------------------------------------------------------- /Stack/Stack.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #define Stack_Size 10 4 | using namespace std; 5 | 6 | class Stack{ 7 | 8 | private: 9 | int top; 10 | int item; 11 | int s[Stack_Size]; 12 | public: 13 | Stack(){top=-1;} 14 | void push(int item); 15 | int pop(); 16 | void display(); 17 | }; 18 | 19 | void Stack::push(int item) 20 | { 21 | if(top==Stack_Size-1) 22 | { 23 | cout<<"Stack Overflow!"<>choice; 61 | 62 | switch(choice) 63 | { 64 | case 1: 65 | cout<<"Enter an item to push:"<>item; 67 | s.push(item); 68 | break; 69 | case 2: 70 | item=s.pop(); 71 | if(item==-1) 72 | cout<<"Stack Underflow!"< /*Importing the necessary header files*/ 8 | using namespace std; 9 | #define MAX 50 /*Defining the size of the stack*/ 10 | template 11 | class Stack { 12 | private: 13 | X S[MAX]; /*The stack array*/ 14 | int top; /*The top element to be pushed to stack */ 15 | public: 16 | Stack() { top = -1;} /*Initialized the top to -1 (empty) */ 17 | /* 18 | The push method pushes the element to the top of the stack. 19 | If the stack is full, it returns an error message, otherwise the element is pushed to stack. 20 | */ 21 | void push(X el) { 22 | if(!isFull()) 23 | { 24 | top++; 25 | S[top]=el; 26 | cout << el << " pushed to stack.\n"; 27 | } 28 | else 29 | cout << "Stack is full!\n"; 30 | } 31 | /* 32 | The pop method pops and element from the stack. 33 | If the stack is empty, it returns an error message, otherwise the element is popped from stack. 34 | */ 35 | void pop() { 36 | if(!isEmpty()) 37 | { 38 | cout << topel() << " popped from stack.\n"; 39 | top--; 40 | } 41 | else 42 | cout << "Stack is empty!\n"; 43 | } 44 | /* 45 | The clear method clears all the elements from the stack. 46 | If the stack is empty, it returns an error message, otherwise the stack is cleared. 47 | */ 48 | void clear() { 49 | if(!isEmpty()) 50 | { 51 | top=-1; 52 | cout << "Stack cleared successfully!\n"; 53 | } 54 | else 55 | cout << "Stack is empty!\n"; 56 | } 57 | /* 58 | The topel method returns the topmost element from the stack. 59 | If the stack is empty, it returns an error message, otherwise the top element from stack is returned. 60 | */ 61 | X topel() { 62 | if(!isEmpty()) 63 | return S[top]; 64 | else 65 | cout << "Stack is empty!\n"; 66 | } 67 | /* 68 | The isEmpty method checks whether the stack is empty. 69 | If the top = -1, it returns true, otherwise false. 70 | */ 71 | bool isEmpty() { 72 | if(top==-1) 73 | return true; 74 | else 75 | return false; 76 | } 77 | /* 78 | The isFull method checks whether the stack is full. 79 | If the top >= MAX - 1, it returns true, otherwise false. 80 | */ 81 | bool isFull() { 82 | if(top>=MAX-1) 83 | return true; 84 | else 85 | return false; 86 | } 87 | }; 88 | int main() 89 | { 90 | Stack s1; /* Stack obj implemented as an int */ 91 | Stack s2; /* Stack obj implemented as a char */ 92 | int el; 93 | char el1; 94 | char ch; 95 | do { 96 | cout << "MENU: (q to quit)\n"; 97 | cout << "a) Push to int stack\n"; 98 | cout << "b) Push to char stack\n"; 99 | cout << "c) Pop from int stack\n"; 100 | cout << "d) Pop from char stack\n"; 101 | cout << "e) Clear int stack\n"; 102 | cout << "f) Clear char stack\n"; 103 | cin >> ch; 104 | switch(ch) { 105 | case 'a': 106 | cout << "Enter value for int stack\n"; 107 | cin >> el; 108 | s1.push(el); 109 | break; 110 | case 'b': 111 | cout << "Enter value for char stack\n"; 112 | cin >> el1; 113 | s2.push(el1); 114 | break; 115 | case 'c': 116 | s1.pop(); 117 | break; 118 | case 'd': 119 | s2.pop(); 120 | break; 121 | case 'e': 122 | s1.clear(); 123 | break; 124 | case 'f': 125 | s2.clear(); 126 | break; 127 | default: 128 | cout << "Wrong option\n"; 129 | } 130 | } while(ch!='q'); /* Run the menu till q is pressed. */ 131 | return 0; 132 | } 133 | -------------------------------------------------------------------------------- /Tree Problems/BINARY_SEARCH_TREE.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class BinarySearchTree { 6 | private: 7 | 8 | struct tree_node { 9 | tree_node* left; 10 | tree_node* right; 11 | int data; 12 | }; 13 | tree_node* root; 14 | public: 15 | 16 | BinarySearchTree() { 17 | root = NULL; 18 | } 19 | 20 | bool isEmpty() const { 21 | return root == NULL; 22 | } 23 | void print_inorder(); 24 | void inorder(tree_node*); 25 | void print_preorder(); 26 | void preorder(tree_node*); 27 | void print_postorder(); 28 | void postorder(tree_node*); 29 | void insert(int); 30 | void remove(int); 31 | }; 32 | 33 | // Smaller elements go left 34 | // larger elements go right 35 | 36 | void BinarySearchTree::insert(int d) { 37 | tree_node* t = new tree_node; 38 | tree_node* parent; 39 | t->data = d; 40 | t->left = NULL; 41 | t->right = NULL; 42 | parent = NULL; 43 | // is this a new tree? 44 | if (isEmpty()) root = t; 45 | else { 46 | //Note: ALL insertions are as leaf nodes 47 | tree_node* curr; 48 | curr = root; 49 | // Find the Node's parent 50 | while (curr) { 51 | parent = curr; 52 | if (t->data > curr->data) curr = curr->right; 53 | else curr = curr->left; 54 | } 55 | 56 | if (t->data < parent->data) 57 | parent->left = t; 58 | else 59 | parent->right = t; 60 | } 61 | } 62 | 63 | void BinarySearchTree::remove(int d) { 64 | //Locate the element 65 | bool found = false; 66 | if (isEmpty()) { 67 | cout << " This Tree is empty! " << endl; 68 | return; 69 | } 70 | tree_node* curr; 71 | tree_node* parent; 72 | curr = root; 73 | while (curr != NULL) { 74 | if (curr->data == d) { 75 | found = true; 76 | break; 77 | } else { 78 | parent = curr; 79 | if (d > curr->data) curr = curr->right; 80 | else curr = curr->left; 81 | } 82 | } 83 | if (!found) { 84 | cout << " Data not found! " << endl; 85 | return; 86 | } 87 | 88 | // 3 cases : 89 | // 1. We're removing a leaf node 90 | // 2. We're removing a node with a single child 91 | // 3. we're removing a node with 2 children 92 | 93 | // Node with single child 94 | if ((curr->left == NULL && curr->right != NULL) || (curr->left != NULL 95 | && curr->right == NULL)) { 96 | if (curr->left == NULL && curr->right != NULL) { 97 | if (parent->left == curr) { 98 | parent->left = curr->right; 99 | delete curr; 100 | } else { 101 | parent->right = curr->right; 102 | delete curr; 103 | } 104 | } else // left child present, no right child 105 | { 106 | if (parent->left == curr) { 107 | parent->left = curr->left; 108 | delete curr; 109 | } else { 110 | parent->right = curr->left; 111 | delete curr; 112 | } 113 | } 114 | return; 115 | } 116 | 117 | //We're looking at a leaf node 118 | if (curr->left == NULL && curr->right == NULL) { 119 | if (parent->left == curr) 120 | parent->left = NULL; 121 | else parent->right = NULL; 122 | delete curr; 123 | return; 124 | } 125 | 126 | //Node with 2 children 127 | // replace node with smallest value in right subtree 128 | if (curr->left != NULL && curr->right != NULL) { 129 | tree_node* chkr; 130 | chkr = curr->right; 131 | if ((chkr->left == NULL) && (chkr->right == NULL)) { 132 | curr = chkr; 133 | delete chkr; 134 | curr->right = NULL; 135 | } else // right child has children 136 | { 137 | //if the node's right child has a left child 138 | // Move all the way down left to locate smallest element 139 | 140 | if ((curr->right)->left != NULL) { 141 | tree_node* lcurr; 142 | tree_node* lcurrp; 143 | lcurrp = curr->right; 144 | lcurr = (curr->right)->left; 145 | while (lcurr->left != NULL) { 146 | lcurrp = lcurr; 147 | lcurr = lcurr->left; 148 | } 149 | curr->data = lcurr->data; 150 | delete lcurr; 151 | lcurrp->left = NULL; 152 | } else { 153 | tree_node* tmp; 154 | tmp = curr->right; 155 | curr->data = tmp->data; 156 | curr->right = tmp->right; 157 | delete tmp; 158 | } 159 | 160 | } 161 | return; 162 | } 163 | } 164 | 165 | void BinarySearchTree::print_inorder() { 166 | inorder(root); 167 | } 168 | 169 | void BinarySearchTree::inorder(tree_node* p) { 170 | if (p != NULL) { 171 | if (p->left) inorder(p->left); 172 | cout << " " << p->data << " "; 173 | if (p->right) inorder(p->right); 174 | } else return; 175 | } 176 | 177 | void BinarySearchTree::print_preorder() { 178 | preorder(root); 179 | } 180 | 181 | void BinarySearchTree::preorder(tree_node* p) { 182 | if (p != NULL) { 183 | cout << " " << p->data << " "; 184 | if (p->left) preorder(p->left); 185 | if (p->right) preorder(p->right); 186 | } else return; 187 | } 188 | 189 | void BinarySearchTree::print_postorder() { 190 | postorder(root); 191 | } 192 | 193 | void BinarySearchTree::postorder(tree_node* p) { 194 | if (p != NULL) { 195 | if (p->left) postorder(p->left); 196 | if (p->right) postorder(p->right); 197 | cout << " " << p->data << " "; 198 | } else return; 199 | } 200 | 201 | int main() { 202 | BinarySearchTree b; 203 | int ch, tmp, tmp1; 204 | while (1) { 205 | cout << endl << endl; 206 | cout << " Binary Search Tree Operations " << endl; 207 | cout << " ----------------------------- " << endl; 208 | cout << " 1. Insertion/Creation " << endl; 209 | cout << " 2. In-Order Traversal " << endl; 210 | cout << " 3. Pre-Order Traversal " << endl; 211 | cout << " 4. Post-Order Traversal " << endl; 212 | cout << " 5. Removal " << endl; 213 | cout << " 6. Exit " << endl; 214 | cout << " Enter your choice : "; 215 | cin>>ch; 216 | switch (ch) { 217 | case 1: cout << " Enter Number to be inserted : "; 218 | cin>>tmp; 219 | b.insert(tmp); 220 | break; 221 | case 2: cout << endl; 222 | cout << " In-Order Traversal " << endl; 223 | cout << " -------------------" << endl; 224 | b.print_inorder(); 225 | break; 226 | case 3: cout << endl; 227 | cout << " Pre-Order Traversal " << endl; 228 | cout << " -------------------" << endl; 229 | b.print_preorder(); 230 | break; 231 | case 4: cout << endl; 232 | cout << " Post-Order Traversal " << endl; 233 | cout << " --------------------" << endl; 234 | b.print_postorder(); 235 | break; 236 | case 5: cout << " Enter data to be deleted : "; 237 | cin>>tmp1; 238 | b.remove(tmp1); 239 | break; 240 | case 6: system("pause"); 241 | return 0; 242 | break; 243 | } 244 | } 245 | } 246 | -------------------------------------------------------------------------------- /Tree Problems/TREE.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * C++ Program To Implement BST 3 | */ 4 | # include 5 | # include 6 | using namespace std; 7 | /* 8 | * Node Declaration 9 | */ 10 | struct node 11 | { 12 | int info; 13 | struct node *left; 14 | struct node *right; 15 | }*root; 16 | 17 | /* 18 | * Class Declaration 19 | */ 20 | class BST 21 | { 22 | public: 23 | void find(int, node **, node **); 24 | void insert(int); 25 | void del(int); 26 | void case_a(node *,node *); 27 | void case_b(node *,node *); 28 | void case_c(node *,node *); 29 | void preorder(node *); 30 | void inorder(node *); 31 | void postorder(node *); 32 | void display(node *, int); 33 | BST() 34 | { 35 | root = NULL; 36 | } 37 | }; 38 | /* 39 | * Main Contains Menu 40 | */ 41 | int main() 42 | { 43 | int choice, num; 44 | BST bst; 45 | node *temp; 46 | while (1) 47 | { 48 | cout<<"-----------------"<>choice; 60 | switch(choice) 61 | { 62 | case 1: 63 | temp = new node; 64 | cout<<"Enter the number to be inserted : "; 65 | cin>>temp->info; 66 | bst.insert(root, temp); 67 | case 2: 68 | if (root == NULL) 69 | { 70 | cout<<"Tree is empty, nothing to delete"<>num; 75 | bst.del(num); 76 | break; 77 | case 3: 78 | cout<<"Inorder Traversal of BST:"<info) 118 | { 119 | *loc = root; 120 | *par = NULL; 121 | return; 122 | } 123 | if (item < root->info) 124 | ptr = root->left; 125 | else 126 | ptr = root->right; 127 | ptrsave = root; 128 | while (ptr != NULL) 129 | { 130 | if (item == ptr->info) 131 | { 132 | *loc = ptr; 133 | *par = ptrsave; 134 | return; 135 | } 136 | ptrsave = ptr; 137 | if (item < ptr->info) 138 | ptr = ptr->left; 139 | else 140 | ptr = ptr->right; 141 | } 142 | *loc = NULL; 143 | *par = ptrsave; 144 | } 145 | 146 | /* 147 | * Inserting Element into the Tree 148 | */ 149 | void BST::insert(node *tree, node *newnode) 150 | { 151 | if (root == NULL) 152 | { 153 | root = new node; 154 | root->info = newnode->info; 155 | root->left = NULL; 156 | root->right = NULL; 157 | cout<<"Root Node is Added"<info == newnode->info) 161 | { 162 | cout<<"Element already in the tree"<info > newnode->info) 166 | { 167 | if (tree->left != NULL) 168 | { 169 | insert(tree->left, newnode); 170 | } 171 | else 172 | { 173 | tree->left = newnode; 174 | (tree->left)->left = NULL; 175 | (tree->left)->right = NULL; 176 | cout<<"Node Added To Left"<right != NULL) 183 | { 184 | insert(tree->right, newnode); 185 | } 186 | else 187 | { 188 | tree->right = newnode; 189 | (tree->right)->left = NULL; 190 | (tree->right)->right = NULL; 191 | cout<<"Node Added To Right"<left == NULL && location->right == NULL) 215 | case_a(parent, location); 216 | if (location->left != NULL && location->right == NULL) 217 | case_b(parent, location); 218 | if (location->left == NULL && location->right != NULL) 219 | case_b(parent, location); 220 | if (location->left != NULL && location->right != NULL) 221 | case_c(parent, location); 222 | free(location); 223 | } 224 | 225 | /* 226 | * Case A 227 | */ 228 | void BST::case_a(node *par, node *loc ) 229 | { 230 | if (par == NULL) 231 | { 232 | root = NULL; 233 | } 234 | else 235 | { 236 | if (loc == par->left) 237 | par->left = NULL; 238 | else 239 | par->right = NULL; 240 | } 241 | } 242 | 243 | /* 244 | * Case B 245 | */ 246 | void BST::case_b(node *par, node *loc) 247 | { 248 | node *child; 249 | if (loc->left != NULL) 250 | child = loc->left; 251 | else 252 | child = loc->right; 253 | if (par == NULL) 254 | { 255 | root = child; 256 | } 257 | else 258 | { 259 | if (loc == par->left) 260 | par->left = child; 261 | else 262 | par->right = child; 263 | } 264 | } 265 | 266 | /* 267 | * Case C 268 | */ 269 | void BST::case_c(node *par, node *loc) 270 | { 271 | node *ptr, *ptrsave, *suc, *parsuc; 272 | ptrsave = loc; 273 | ptr = loc->right; 274 | while (ptr->left != NULL) 275 | { 276 | ptrsave = ptr; 277 | ptr = ptr->left; 278 | } 279 | suc = ptr; 280 | parsuc = ptrsave; 281 | if (suc->left == NULL && suc->right == NULL) 282 | case_a(parsuc, suc); 283 | else 284 | case_b(parsuc, suc); 285 | if (par == NULL) 286 | { 287 | root = suc; 288 | } 289 | else 290 | { 291 | if (loc == par->left) 292 | par->left = suc; 293 | else 294 | par->right = suc; 295 | } 296 | suc->left = loc->left; 297 | suc->right = loc->right; 298 | } 299 | 300 | /* 301 | * Pre Order Traversal 302 | */ 303 | void BST::preorder(node *ptr) 304 | { 305 | if (root == NULL) 306 | { 307 | cout<<"Tree is empty"<info<<" "; 313 | preorder(ptr->left); 314 | preorder(ptr->right); 315 | } 316 | } 317 | /* 318 | * In Order Traversal 319 | */ 320 | void BST::inorder(node *ptr) 321 | { 322 | if (root == NULL) 323 | { 324 | cout<<"Tree is empty"<left); 330 | cout<info<<" "; 331 | inorder(ptr->right); 332 | } 333 | } 334 | 335 | /* 336 | * Postorder Traversal 337 | */ 338 | void BST::postorder(node *ptr) 339 | { 340 | if (root == NULL) 341 | { 342 | cout<<"Tree is empty"<left); 348 | postorder(ptr->right); 349 | cout<info<<" "; 350 | } 351 | } 352 | 353 | /* 354 | * Display Tree Structure 355 | */ 356 | void BST::display(node *ptr, int level) 357 | { 358 | int i; 359 | if (ptr != NULL) 360 | { 361 | display(ptr->right, level+1); 362 | cout<: "; 365 | else 366 | { 367 | for (i = 0;i < level;i++) 368 | cout<<" "; 369 | } 370 | cout<info; 371 | display(ptr->left, level+1); 372 | } 373 | } -------------------------------------------------------------------------------- /dfs.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void DFS(int); 4 | int G[10][10],visited[10],n; //n is no of vertices and graph is sorted in array G[10][10] 5 | 6 | void main() 7 | { 8 | int i,j; 9 | printf("Enter number of vertices:"); 10 | 11 | scanf("%d",&n); 12 | 13 | //read the adjecency matrix 14 | printf("\nEnter adjecency matrix of the graph:"); 15 | 16 | for(i=0;i 2 | #include 3 | 4 | struct Node 5 | { 6 | int data; 7 | struct Node *x_ptr; 8 | }; 9 | 10 | //XOR Operation 11 | struct Node * xor(struct Node *m, struct Node *n){ 12 | return (struct Node *)((unsigned)m ^ (unsigned)n); 13 | } 14 | 15 | //Inserting into XOR List to beg 16 | void insert(struct Node **head, int x){ 17 | //Create a new node to be inserted 18 | struct Node *temp = (struct Node *)malloc(sizeof(struct Node)); 19 | temp->data = x; 20 | 21 | //As it is inserted at beginning its x_ptr will (NULL XOR head) 22 | temp->x_ptr = xor(NULL,(*head)); 23 | 24 | //If list is not empty then x_ptr of head will be (new node XOR next node) 25 | if((*head) != NULL){ 26 | //Get address of Next Node 27 | struct Node *nextNode = xor(NULL,(*head)->x_ptr); 28 | 29 | //Store XOR of new node and next node 30 | (*head)->x_ptr = xor(temp,nextNode); 31 | } 32 | 33 | //Make the new node as head 34 | *head = temp; 35 | } 36 | 37 | //Printing XOR List 38 | void printList(struct Node *head) 39 | { 40 | struct Node *previous, *current, *next; 41 | previous = NULL; 42 | current = head; 43 | 44 | while(current) 45 | { 46 | //print data of current node 47 | printf(" %d ",current->data); 48 | 49 | //get address of next node as (previous node XOR (previous XOR next node)) 50 | //where current->x_ptr = (previous XOR next node) 51 | next = xor(previous,current->x_ptr); 52 | 53 | //update previous and current for next iteration 54 | previous = current; 55 | current = next; 56 | } 57 | 58 | printf("\n"); 59 | } 60 | 61 | int main(){ 62 | /*10->20->30->40->50 */ 63 | struct Node *head=NULL; 64 | insert(&head,50); 65 | insert(&head,40); 66 | insert(&head,30); 67 | insert(&head,20); 68 | insert(&head,10); 69 | printList(head); 70 | return 0; 71 | } 72 | --------------------------------------------------------------------------------