├── .dep.inc ├── .gitignore ├── Makefile ├── README.md ├── Sample Chapter Data Structures and Algorithms Made Easy Fifth Edition.pdf ├── Table of Contents Data Structures and Algorithms Made Easy Fifth Edition.pdf ├── main.c └── src ├── Chapter_01_Introduction ├── ComplexityWithBreakStatement.c └── IfElese.c ├── Chapter_02_Recursion_and_Backtracking ├── binaryNumber.cpp ├── connectedCells.cpp └── generateString.cpp ├── Chapter_03_Linked_Lists ├── AlternatingSplit.c ├── DoublyLinkedList.c ├── LoopLength.c ├── SinglyLinkedList.c ├── checkLoop.c ├── circular linked list.c ├── findLoopBeginning.c ├── intersectingListNode.c ├── intersectingNodeBruteForce.c ├── intersection.c ├── kth node from end.c ├── middleNode.c ├── printListInReverse.c ├── removeDuplicates.c ├── reverseLinkedList.c └── sortedInsert.c ├── Chapter_04_Queues ├── DynamicQueue.c ├── QueueWithTwoStacks.c ├── QueuesWithLinkedLists.c ├── ReverseQueue.c └── SimpleQueue.c ├── Chapter_04_Stacks ├── DynamicStack.c ├── QueueWithTwoStacks.c ├── ReverseQueue.c ├── SimpleArrayImplementationofStack.c ├── StackWithLinkedLists.c ├── TwoStacksInOneArray.c ├── balanced parenthesis using stack ├── find_spans.c ├── findingSpan.cpp ├── getMinimum.c ├── getMinimums.c ├── infixToPostfix.c ├── infixToPostfix.cpp ├── isPalindrome.c ├── isPalindrome2.c ├── largestHistrogram_n^2.cpp ├── largestHistrogram_n^3.cpp ├── largestHistrogram_nlogn.cpp ├── postfixEvaluation.c ├── postfixEvaluation.cpp └── reverseStack.c ├── Chapter_06_Trees ├── BinaryTree.c ├── FindMaxUsingLevelOrder.c ├── InorderTraversalIterative.c ├── InorderTraversalRecursive.c ├── LevelOrder.c ├── PostorderTraversalIterative.c ├── PostorderTraversalRecursive.c ├── PreorderTraversalIterative.c └── PreorderTraversalRecursive.c ├── Chapter_09_Graph_Algorithms ├── AdjacencyMatrix.c ├── AdjacentList.c ├── DFS.c ├── GraphUsingAdjacencyList.cpp ├── GraphUsingAdjacencyMatrix.cpp └── TopologicalSort.c ├── Chapter_10_Sorting ├── SortedSquaredArray.cpp ├── SortedSquaredArray2.cpp ├── bubbleSort.c ├── insertionSort.c └── selectionSort.c ├── Chapter_11_Searching ├── BinarySearch.c ├── InterpolationSearch.c ├── OrderedLinearSearch.c └── UnorderedLinearSearch.c ├── Chapter_14_Hashing └── LinearChainingImplementation.c └── Chapter_22_Miscellaneous_Bitwise_Hacking ├── CountingNumberofOnesIn1toN.c ├── CountingNumberofOneswithBitwiseAND.c ├── CountingNumberofOneswithModuloOperator.c ├── CountingNumberofOneswithPreprocessing.c ├── CountingNumberofOneswithTogglingApproach.c ├── DecimaltoBinary.c ├── DecimaltoBinary.cpp ├── FindUniqueNumber.c ├── FindUniqueNumber.cpp ├── SwapBits.c ├── SwapBits.cpp ├── countSetBitsMethod1.c └── isPowerof2.cpp /.dep.inc: -------------------------------------------------------------------------------- 1 | # This code depends on make tool being used 2 | DEPFILES=$(wildcard $(addsuffix .d, ${OBJECTFILES} ${TESTOBJECTFILES})) 3 | ifneq (${DEPFILES},) 4 | include ${DEPFILES} 5 | endif 6 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /Debug/ 2 | /nbproject/ 3 | /dist/ 4 | /build/ 5 | /.gitignore/ 6 | *.exe 7 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | # 2 | # There exist several targets which are by default empty and which can be 3 | # used for execution of your targets. These targets are usually executed 4 | # before and after some main targets. They are: 5 | # 6 | # .build-pre: called before 'build' target 7 | # .build-post: called after 'build' target 8 | # .clean-pre: called before 'clean' target 9 | # .clean-post: called after 'clean' target 10 | # .clobber-pre: called before 'clobber' target 11 | # .clobber-post: called after 'clobber' target 12 | # .all-pre: called before 'all' target 13 | # .all-post: called after 'all' target 14 | # .help-pre: called before 'help' target 15 | # .help-post: called after 'help' target 16 | # 17 | # Targets beginning with '.' are not intended to be called on their own. 18 | # 19 | # Main targets can be executed directly, and they are: 20 | # 21 | # build build a specific configuration 22 | # clean remove built files from a configuration 23 | # clobber remove all built files 24 | # all build all configurations 25 | # help print help mesage 26 | # 27 | # Targets .build-impl, .clean-impl, .clobber-impl, .all-impl, and 28 | # .help-impl are implemented in nbproject/makefile-impl.mk. 29 | # 30 | # Available make variables: 31 | # 32 | # CND_BASEDIR base directory for relative paths 33 | # CND_DISTDIR default top distribution directory (build artifacts) 34 | # CND_BUILDDIR default top build directory (object files, ...) 35 | # CONF name of current configuration 36 | # CND_PLATFORM_${CONF} platform name (current configuration) 37 | # CND_ARTIFACT_DIR_${CONF} directory of build artifact (current configuration) 38 | # CND_ARTIFACT_NAME_${CONF} name of build artifact (current configuration) 39 | # CND_ARTIFACT_PATH_${CONF} path to build artifact (current configuration) 40 | # CND_PACKAGE_DIR_${CONF} directory of package (current configuration) 41 | # CND_PACKAGE_NAME_${CONF} name of package (current configuration) 42 | # CND_PACKAGE_PATH_${CONF} path to package (current configuration) 43 | # 44 | # NOCDDL 45 | 46 | 47 | # Environment 48 | MKDIR=mkdir 49 | CP=cp 50 | CCADMIN=CCadmin 51 | 52 | 53 | # build 54 | build: .build-post 55 | 56 | .build-pre: 57 | # Add your pre 'build' code here... 58 | 59 | .build-post: .build-impl 60 | # Add your post 'build' code here... 61 | 62 | 63 | # clean 64 | clean: .clean-post 65 | 66 | .clean-pre: 67 | # Add your pre 'clean' code here... 68 | 69 | .clean-post: .clean-impl 70 | # Add your post 'clean' code here... 71 | 72 | 73 | # clobber 74 | clobber: .clobber-post 75 | 76 | .clobber-pre: 77 | # Add your pre 'clobber' code here... 78 | 79 | .clobber-post: .clobber-impl 80 | # Add your post 'clobber' code here... 81 | 82 | 83 | # all 84 | all: .all-post 85 | 86 | .all-pre: 87 | # Add your pre 'all' code here... 88 | 89 | .all-post: .all-impl 90 | # Add your post 'all' code here... 91 | 92 | 93 | # build tests 94 | build-tests: .build-tests-post 95 | 96 | .build-tests-pre: 97 | # Add your pre 'build-tests' code here... 98 | 99 | .build-tests-post: .build-tests-impl 100 | # Add your post 'build-tests' code here... 101 | 102 | 103 | # run tests 104 | test: .test-post 105 | 106 | .test-pre: build-tests 107 | # Add your pre 'test' code here... 108 | 109 | .test-post: .test-impl 110 | # Add your post 'test' code here... 111 | 112 | 113 | # help 114 | help: .help-post 115 | 116 | .help-pre: 117 | # Add your pre 'help' code here... 118 | 119 | .help-post: .help-impl 120 | # Add your post 'help' code here... 121 | 122 | 123 | 124 | # include project implementation makefile 125 | include nbproject/Makefile-impl.mk 126 | 127 | # include project make variables 128 | include nbproject/Makefile-variables.mk 129 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Data Structures And Algorithms Made Easy 2 | ---------------------------------------- 3 | 4 | Copyright (c) August 28, 2016 CareerMonk Publications and others. 5 | 6 | E-Mail : info@careermonk.com 7 | 8 | Last modification by : Narasimha Karumanchi 9 | 10 | Book Title : Data Structures And Algorithms Made Easy 11 | 12 | ISBN : 9788193245279 13 | 14 | Warranty : This software is provided "as is" without any warranty; without even the implied warranty of merchantability or fitness for a particular purpose. 15 | 16 | Book Description 17 | ---------------- 18 | Peeling Data Structures and Algorithms for interviews [re-printed with corrections and new problems]: 19 | 20 | "Data Structures And Algorithms Made Easy: Data Structure And Algorithmic Puzzles" is a book that offers solutions to complex data structures and algorithms. There are multiple solutions for each problem and the book is coded in C/C++, it comes handy as an interview and exam guide for computer scientists. 21 | 22 | A handy guide of sorts for any computer science professional, Data Structures And Algorithms Made Easy: Data Structure And Algorithmic Puzzles is a solution bank for various complex problems related to data structures and algorithms. It can be used as a reference manual by those readers in the computer science industry. 23 | 24 | The book has around 21 chapters and covers Recursion and Backtracking, Linked Lists, Stacks, Queues,Trees, Priority Queue and Heaps, Disjoint Sets ADT, Graph Algorithms, Sorting, Searching, Selection Algorithms [Medians], Symbol Tables, Hashing, String Algorithms, Algorithms Design Techniques, Greedy Algorithms, Divide and Conquer Algorithms, Dynamic Programming, Complexity Classes, and other Miscellaneous Concepts. 25 | 26 | Data Structures And Algorithms Made Easy: Data Structure And Algorithmic Puzzles by Narasimha Karumanchi was published in March, and it is coded in C/C++ language. This book serves as guide to prepare for interviews, exams, and campus work. It is also available in Java. In short, this book offers solutions to various complex data structures and algorithmic problems. 27 | 28 | What is unique? 29 | 30 | Our main objective isn't to propose theorems and proofs about DS and Algorithms. We took the direct route and solved problems of varying complexities. That is, each problem corresponds to multiple solutions with different complexities. In other words, we enumerated possible solutions. With this approach, even when a new question arises, we offer a choice of different solution strategies based on your priorities. 31 | 32 | Topics Covered: 33 | 34 | Introduction 35 | Recursion and Backtracking 36 | Linked Lists 37 | Stacks 38 | Queues 39 | Trees 40 | Priority Queue and Heaps 41 | Disjoint Sets ADT 42 | Graph Algorithms 43 | Sorting 44 | Searching 45 | Selection Algorithms [Medians] 46 | Symbol Tables 47 | Hashing 48 | String Algorithms 49 | Algorithms Design Techniques 50 | Greedy Algorithms 51 | Divide and Conquer Algorithms 52 | Dynamic Programming 53 | Complexity Classes 54 | Miscellaneous Concepts 55 | -------------------------------------------------------------------------------- /Sample Chapter Data Structures and Algorithms Made Easy Fifth Edition.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/careermonk/data-structures-and-algorithms-made-easy/301ffd212f04b84f33bdbcb79ce2baafab0c5b34/Sample Chapter Data Structures and Algorithms Made Easy Fifth Edition.pdf -------------------------------------------------------------------------------- /Table of Contents Data Structures and Algorithms Made Easy Fifth Edition.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/careermonk/data-structures-and-algorithms-made-easy/301ffd212f04b84f33bdbcb79ce2baafab0c5b34/Table of Contents Data Structures and Algorithms Made Easy Fifth Edition.pdf -------------------------------------------------------------------------------- /main.c: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | 7 | /* 8 | * File: main.c 9 | * Author: narkarum 10 | * 11 | * Created on May 14, 2016, 12:26 AM 12 | */ 13 | 14 | #include 15 | #include 16 | 17 | /* 18 | * 19 | */ 20 | int main(int argc, char** argv) { 21 | countingNumberofOnesIn1toN_test(); 22 | return (EXIT_SUCCESS); 23 | } 24 | 25 | -------------------------------------------------------------------------------- /src/Chapter_01_Introduction/ComplexityWithBreakStatement.c: -------------------------------------------------------------------------------- 1 | //========================================================================= 2 | // Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 3 | // E-Mail : info@careermonk.com 4 | // Creation Date : 2014-01-10 06:15:46 5 | // Last modification : 2008-10-31 6 | // by : Narasimha Karumanchi 7 | // Book Title : Data Structures And Algorithms made Easy 8 | // Warranty : This software is provided "as is" without any 9 | // warranty; without even the implied warranty of 10 | // merchantability or fitness for a particular purpose. 11 | //========================================================================= 12 | 13 | int functionWithBreak(int n){ 14 | int count = 0; 15 | int i = 0,j; 16 | for(i=n/2;i 2 | #include 3 | 4 | using namespace std; 5 | void binary(int n,vector v,int i) 6 | { 7 | if(i==n) 8 | { 9 | for(int x:v) 10 | { 11 | cout< v(n); 27 | binary(n,v,0); 28 | return 0; 29 | } -------------------------------------------------------------------------------- /src/Chapter_02_Recursion_and_Backtracking/connectedCells.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | int getVal(vector> &a,int i,int j,int H,int L) 5 | { 6 | if(i<0 || j<0 || i>=L || j>=H) 7 | return 0; 8 | else 9 | return a[i][j]; 10 | } 11 | void connectedCells(vector> &a,int i,int j,int maxRow,int maxCol,int size,vector> &cnt,int &mxSize){ 12 | if(i>=maxRow || j>= maxCol) 13 | return ; 14 | cnt[i][j]=1; 15 | size++;//we have encountered one 16 | mxSize=max(size,mxSize); 17 | int directions[][2]={{-1,-1},{-1,0},{-1,+1},{0,-1},{0,+1},{+1,-1},{+1,0},{+1,+1}}; 18 | //check its neighbours 19 | for(int z=0;z<8;z++) 20 | { 21 | int new_i=i+directions[z][0]; 22 | int new_j=j+directions[z][1]; 23 | int val=getVal(a,new_i,new_j,maxRow,maxCol); 24 | if(val>0 && cnt[new_i][new_j]==0){ 25 | connectedCells(a,new_i,new_j,maxRow,maxCol,size,cnt,mxSize); 26 | } 27 | } 28 | cnt[i][j]=0; 29 | } 30 | int maxOnes(vector> &a,int maxRow,int maxCol) 31 | { 32 | int size=0; 33 | int mxSize=0; 34 | vector> cnt( maxRow , vector (maxCol, 0)); 35 | for(int x=0;x> a{{1,1,0,0,0},{0,1,1,0,0},{0,0,1,0,1},{1,0,0,0,1},{0,1,0,1,1}}; 49 | cout< 2 | #include 3 | using namespace std; 4 | void k_strings(int requiredStringLen, int givenLen,vector v,int i) 5 | { 6 | //backtrack 7 | if(i==requiredStringLen) 8 | { 9 | for(int x:v) 10 | cout< a(n); 24 | k_strings(n,3,a,0); 25 | return 0; 26 | } -------------------------------------------------------------------------------- /src/Chapter_03_Linked_Lists/AlternatingSplit.c: -------------------------------------------------------------------------------- 1 | /*Copyright (c) 2008 CareerMonk Publications and others. 2 | #E-Mail : info@careermonk.com 3 | #Creation Date : 2008-01-10 06:15:46 4 | #Created by : Narasimha Karumanchi 5 | #Book Title : Data Structures And Algorithms Made Easy 6 | #Warranty : This software is provided "as is" without any 7 | # warranty; without even the implied warranty of 8 | # merchantability or fitness for a particular purpose.*/ 9 | 10 | #include 11 | #include 12 | 13 | /* A structure of linked list ListNode */ 14 | struct ListNode { 15 | int data; 16 | struct ListNode *next; 17 | } *head; 18 | 19 | void initialize(){ 20 | head = NULL; 21 | } 22 | 23 | /* 24 | Given a Inserts a ListNode in pTemp of a singly linked list. 25 | */ 26 | void insert(int data) { 27 | /* Create a new Linked List ListNode */ 28 | struct ListNode* newNode = (struct ListNode*) malloc(sizeof(struct ListNode)); 29 | newNode->data = data; 30 | /* Next pointer of new ListNode will point to head ListNode of linked list */ 31 | newNode->next = head; 32 | /* make new ListNode as new head of linked list */ 33 | head = newNode; 34 | printf("Inserted Element : %d\n", data); 35 | } 36 | 37 | int getLength(struct ListNode *head){ 38 | /* Input Validation */ 39 | if (head == NULL) { 40 | printf("Error : Invalid ListNode pointer !!!\n"); 41 | return 0; 42 | } 43 | 44 | int length =0; 45 | while(head != NULL){ 46 | head = head->next; 47 | length++; 48 | } 49 | return length; 50 | } 51 | 52 | struct ListNode * middleNode(struct ListNode *head){ 53 | /* Input Validation */ 54 | if(head == NULL){ 55 | printf("Error: List is empty!\n"); 56 | return NULL; 57 | } 58 | struct ListNode *slow, *fast; 59 | slow = fast = head; 60 | /* In every iteration, slow pointer will move one node whereas fast pointer will move two ListNodes. 61 | When fast pointer reaches last ListNode then slow pointer will be pointing to middle ListNode */ 62 | while(fast != NULL && fast->next != NULL) { 63 | fast = fast->next->next; 64 | slow = slow->next; 65 | } 66 | return slow; 67 | } 68 | 69 | /* 70 | Prints a linked list from head ListNode till tail ListNode 71 | */ 72 | void printLinkedList(struct ListNode *ListNodePtr) { 73 | while (ListNodePtr != NULL) { 74 | printf("%d", ListNodePtr->data); 75 | ListNodePtr = ListNodePtr->next; 76 | if(ListNodePtr != NULL) 77 | printf("-->"); 78 | } 79 | } 80 | 81 | void alternatingSplit(struct ListNode* head, struct ListNode** head1, struct ListNode** head2) { 82 | struct ListNode* a = NULL; // Split the nodes to these 'a' and 'b' lists 83 | struct ListNode* b = NULL; 84 | struct ListNode* current = head; 85 | while (current != NULL) { 86 | // Move a ListNode to 'a' 87 | struct ListNode* newNode = current; // the front current node 88 | current = newNode->next; // Advance the current pointer 89 | newNode->next = a; // Link the node with the head of list a 90 | a = newNode; 91 | 92 | // Move a ListNode to 'b' 93 | if (current != NULL) { 94 | struct ListNode* newNode = current; // the front source node 95 | current = newNode->next; // Advance the source pointer 96 | newNode->next = b; // Link the node with the head of list b 97 | b = newNode; 98 | } 99 | } 100 | *head1 = a; 101 | *head2 = b; 102 | } 103 | 104 | int main() { 105 | struct ListNode *head1, *head2; 106 | initialize(); 107 | /* Creating a linked List*/ 108 | insert(3); 109 | insert(8); 110 | insert(12); 111 | insert(0); 112 | insert(35); 113 | insert(6); 114 | insert(10); 115 | insert(350); 116 | insert(16); 117 | insert(19); 118 | printf("\nLinked List\n"); 119 | printLinkedList(head); 120 | alternatingSplit(head, &head1, &head2); 121 | printf("\nLinked List1\n"); 122 | printLinkedList(head1); 123 | printf("\nLinked List2\n"); 124 | printLinkedList(head2); 125 | return 0; 126 | } 127 | -------------------------------------------------------------------------------- /src/Chapter_03_Linked_Lists/LoopLength.c: -------------------------------------------------------------------------------- 1 | /*Copyright (c) 2008 CareerMonk Publications and others. 2 | #E-Mail : info@careermonk.com 3 | #Creation Date : 2008-01-10 06:15:46 4 | #Created by : Narasimha Karumanchi 5 | #Book Title : Data Structures And Algorithms Made Easy 6 | #Warranty : This software is provided "as is" without any 7 | # warranty; without even the implied warranty of 8 | # merchantability or fitness for a particular purpose.*/ 9 | #include 10 | #include 11 | 12 | /* A structure of linked list ListNode */ 13 | struct ListNode { 14 | int data; 15 | struct ListNode *next; 16 | } *head; 17 | 18 | void initialize(){ 19 | head = NULL; 20 | } 21 | 22 | /* 23 | Given a Inserts a ListNode in pTemp of a singly linked list. 24 | */ 25 | void insert(int data) { 26 | /* Create a new Linked List ListNode */ 27 | struct ListNode* newNode = (struct ListNode*) malloc(sizeof(struct ListNode)); 28 | newNode->data = data; 29 | /* Next pointer of new ListNode will point to head ListNode of linked list */ 30 | newNode->next = head; 31 | /* make new ListNode as new head of linked list */ 32 | head = newNode; 33 | printf("Inserted Element : %d\n", data); 34 | } 35 | 36 | int getLength(struct ListNode *head){ 37 | /* Input Validation */ 38 | if (head == NULL) { 39 | printf("Error : Invalid ListNode pointer !!!\n"); 40 | return 0; 41 | } 42 | 43 | int length =0; 44 | while(head != NULL){ 45 | head = head->next; 46 | length++; 47 | } 48 | return length; 49 | } 50 | 51 | 52 | int checkLoop(struct ListNode *head) { 53 | struct ListNode *slow, *fast; 54 | slow = fast = head; 55 | 56 | while(fast && fast->next) { 57 | /* Slow pointer will move one node per iteration whereas fast node will move two nodes per iteration */ 58 | slow = slow->next; 59 | fast = fast->next->next; 60 | if (slow == fast) { 61 | printf("\n Linked list contains a loop\n"); 62 | return 1; 63 | } 64 | } 65 | printf("\n No loop in linked list\n"); 66 | return 0; 67 | } 68 | 69 | int loopLength(struct ListNode * head) { 70 | struct ListNode *slow = head, *fast = head; 71 | int loopExists = 0, counter = 0; 72 | while (fast && fast->next) { 73 | slow = slow->next; 74 | fast = fast->next->next; 75 | if (slow == fast){ 76 | loopExists = 1; 77 | break; 78 | } 79 | } 80 | if(loopExists) { 81 | counter = 1; 82 | fast = fast->next; 83 | while(slow != fast) { 84 | fast = fast->next; 85 | counter++; 86 | } 87 | return counter; 88 | } 89 | return 0; 90 | } 91 | 92 | /* 93 | Prints a linked list from head ListNode till tail ListNode 94 | */ 95 | void printLinkedList(struct ListNode *ListNodePtr) { 96 | while (ListNodePtr != NULL) { 97 | printf("%d", ListNodePtr->data); 98 | ListNodePtr = ListNodePtr->next; 99 | if(ListNodePtr != NULL) 100 | printf("-->"); 101 | } 102 | } 103 | 104 | int main() { 105 | struct ListNode *temp; 106 | initialize(); 107 | /* Creating a linked List*/ 108 | insert(8); 109 | insert(3); 110 | insert(2); 111 | insert(7); 112 | insert(9); 113 | 114 | printf("\nLinked List\n"); 115 | printLinkedList(head); 116 | checkLoop(head); 117 | /* Create loop in linked list. Set next pointer of last node to second node from head */ 118 | head->next->next->next->next->next = head->next->next; 119 | checkLoop(head); 120 | printf ("\n Loop length is %d", loopLength(head)); 121 | return 0; 122 | } 123 | -------------------------------------------------------------------------------- /src/Chapter_03_Linked_Lists/SinglyLinkedList.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | struct listNode{ 4 | int data; 5 | struct listNode *next; 6 | }; 7 | int singlyListLength(struct listNode *head){ 8 | int count=0; 9 | struct listNode *current=head; 10 | while(current!=NULL){ 11 | count++; 12 | current=current->next; 13 | } 14 | return count; 15 | } 16 | void insertInSinglyLinkedList(struct listNode **head, int data, int pos){ 17 | int k=1; 18 | struct listNode *q,*p; 19 | struct listNode *newNode=(struct listNode*)malloc(sizeof(struct listNode)); 20 | if(!newNode){ 21 | printf("Memory Error\n"); 22 | return; 23 | } 24 | newNode->data=data; 25 | p=*head; 26 | if(pos==1 || p==NULL){ 27 | newNode->next=*head; 28 | *head=newNode; 29 | } 30 | else{ 31 | while(p!=NULL && (knext; 35 | } 36 | newNode->next=q->next; 37 | q->next=newNode; 38 | } 39 | } 40 | void deleteNodeFromLinkedList(struct listNode **head, int pos){ 41 | int k=1; 42 | struct listNode *p,*q; 43 | p=*head; 44 | if(*head==NULL){ 45 | printf("List Empty\n"); 46 | return; 47 | } 48 | else if(pos==1){ 49 | *head=(*head)->next; 50 | free(p); 51 | } 52 | else{ 53 | while(p!=NULL && knext; 57 | } 58 | if(p==NULL){ 59 | printf("Position does not exist\n"); 60 | } 61 | else{ 62 | q->next=p->next; 63 | free(p); 64 | } 65 | } 66 | } 67 | void printSLList(struct listNode *head){ 68 | while(head!=NULL){ 69 | printf("%d ",head->data); 70 | head=head->next; 71 | } 72 | printf("\n"); 73 | } 74 | int SinglyLinkedList_test(){ 75 | struct listNode *head=NULL; 76 | insertInSinglyLinkedList(&head,5,5); 77 | insertInSinglyLinkedList(&head,2,5); 78 | printf("Elements in List:%d\n",singlyListLength(head)); 79 | printSLList(head); 80 | deleteNodeFromLinkedList(&head,1); 81 | printSLList(head); 82 | return 0; 83 | } 84 | -------------------------------------------------------------------------------- /src/Chapter_03_Linked_Lists/checkLoop.c: -------------------------------------------------------------------------------- 1 | /*Copyright (c) 2008 CareerMonk Publications and others. 2 | #E-Mail : info@careermonk.com 3 | #Creation Date : 2008-01-10 06:15:46 4 | #Created by : Narasimha Karumanchi 5 | #Book Title : Data Structures And Algorithms Made Easy 6 | #Warranty : This software is provided "as is" without any 7 | # warranty; without even the implied warranty of 8 | # merchantability or fitness for a particular purpose.*/ 9 | 10 | #include 11 | #include 12 | 13 | /* A structure of linked list ListNode */ 14 | struct ListNode { 15 | int data; 16 | struct ListNode *next; 17 | } *head; 18 | 19 | void initialize(){ 20 | head = NULL; 21 | } 22 | 23 | /* 24 | Given a Inserts a ListNode in pTemp of a singly linked list. 25 | */ 26 | void insert(int data) { 27 | /* Create a new Linked List ListNode */ 28 | struct ListNode* newNode = (struct ListNode*) malloc(sizeof(struct ListNode)); 29 | newNode->data = data; 30 | /* Next pointer of new ListNode will point to head ListNode of linked list */ 31 | newNode->next = head; 32 | /* make new ListNode as new head of linked list */ 33 | head = newNode; 34 | printf("Inserted Element : %d\n", data); 35 | } 36 | 37 | int getLength(struct ListNode *head){ 38 | /* Input Validation */ 39 | if (head == NULL) { 40 | printf("Error : Invalid ListNode pointer !!!\n"); 41 | return 0; 42 | } 43 | 44 | int length =0; 45 | while(head != NULL){ 46 | head = head->next; 47 | length++; 48 | } 49 | return length; 50 | } 51 | 52 | 53 | int checkLoop(struct ListNode *head) { 54 | struct ListNode *slow, *fast; 55 | slow = fast = head; 56 | 57 | while(fast && fast->next) { 58 | /* Slow pointer will move one node per iteration whereas fast node will move two nodes per iteration */ 59 | slow = slow->next; 60 | fast = fast->next->next; 61 | if (slow == fast) { 62 | printf("\n Linked list contains a loop\n"); 63 | return 1; 64 | } 65 | } 66 | printf("\n No loop in linked list\n"); 67 | return 0; 68 | } 69 | /* 70 | Prints a linked list from head ListNode till tail ListNode 71 | */ 72 | void printLinkedList(struct ListNode *ListNodePtr) { 73 | while (ListNodePtr != NULL) { 74 | printf("%d", ListNodePtr->data); 75 | ListNodePtr = ListNodePtr->next; 76 | if(ListNodePtr != NULL) 77 | printf("-->"); 78 | } 79 | } 80 | 81 | int main() { 82 | struct ListNode *middle; 83 | initialize(); 84 | /* Creating a linked List*/ 85 | insert(8); 86 | insert(3); 87 | insert(2); 88 | insert(7); 89 | insert(9); 90 | 91 | printf("\nLinked List\n"); 92 | printLinkedList(head); 93 | checkLoop(head); 94 | /* Create loop in linked list. Set next pointer of last node to second node from head */ 95 | head->next->next->next->next->next = head->next; 96 | checkLoop(head); 97 | return 0; 98 | } 99 | -------------------------------------------------------------------------------- /src/Chapter_03_Linked_Lists/circular linked list.c: -------------------------------------------------------------------------------- 1 | /*Copyright (c) 2016 CareerMonk Publications and others. 2 | #E-Mail : info@careermonk.com 3 | #Creation Date : 2008-01-10 06:15:46 4 | #Created by : Narasimha Karumanchi 5 | #Book Title : Data Structures And Algorithms Made Easy 6 | #Warranty : This software is provided "as is" without any 7 | # warranty; without even the implied warranty of 8 | # merchantability or fitness for a particular purpose.*/ 9 | 10 | #include 11 | #include 12 | 13 | struct CLLNode{ 14 | int data; 15 | struct CLLNode* next; 16 | }; 17 | 18 | struct CLLNode *head = NULL; 19 | 20 | //length of the list 21 | int length(struct CLLNode *head) { 22 | struct CLLNode *current = head; 23 | int count = 0; 24 | if(head == NULL) 25 | return 0; 26 | 27 | do { 28 | current = current->next; 29 | count++; 30 | } while (current != head); 31 | 32 | return count; 33 | } 34 | 35 | // display list using iteration 36 | void printList(struct CLLNode *head) { 37 | struct CLLNode *current = head; 38 | if(head == NULL) 39 | return; 40 | 41 | do { 42 | printf ("%d-->", current->data); 43 | current = current->next; 44 | } while(current != head); 45 | } 46 | 47 | // Insert at the beginning of the list 48 | void insertAtBeginInCLL (struct CLLNode **head, int data){ 49 | struct CLLNode *current = *head; 50 | struct CLLNode *newNode = (struct CLLNode *) (malloc(sizeof(struct CLLNode))); 51 | if(!newNode) { 52 | printf("Memory Error"); 53 | return; 54 | } 55 | newNode->data = data; 56 | newNode->next = newNode; 57 | if(current == NULL){ 58 | *head = newNode; 59 | return; 60 | } 61 | 62 | while (current->next != *head) 63 | current = current->next; 64 | 65 | newNode->next = *head; 66 | current->next = newNode; 67 | *head = newNode; 68 | } 69 | 70 | // insert item at the end of the list 71 | void insertAtEndInCLL(struct CLLNode **head, int data){ 72 | struct CLLNode *current = *head; 73 | struct CLLNode *newNode = (struct CLLNode *) (malloc(sizeof(struct CLLNode))); 74 | if(!newNode) { 75 | printf("Memory Error"); 76 | return; 77 | } 78 | newNode->data = data; 79 | while (current->next != *head) 80 | current = current->next; 81 | 82 | newNode->next = newNode; 83 | 84 | if(*head ==NULL) 85 | *head = newNode; 86 | else { 87 | newNode->next = *head; 88 | current->next = newNode; 89 | } 90 | } 91 | 92 | void deleteLastNodeFromCLL (struct CLLNode **head) { 93 | struct CLLNode *temp = *head, *current = *head; 94 | 95 | if(*head == NULL) { 96 | printf( "List empty!"); 97 | return; 98 | } 99 | while (current->next != *head) { 100 | temp = current; 101 | current = current->next; 102 | } 103 | temp->next = current->next; 104 | free(current); 105 | return; 106 | } 107 | void deleteFrontNodeFromCLL (struct CLLNode **head) { 108 | struct CLLNode *temp = *head; 109 | struct CLLNode *current = *head; 110 | 111 | if(*head == NULL) { 112 | printf("List empty"); 113 | return; 114 | } 115 | 116 | while (current->next != *head) 117 | current = current->next; 118 | 119 | current->next = (*head)->next; 120 | *head = (*head)->next; 121 | 122 | free(temp); 123 | return; 124 | } 125 | 126 | 127 | int main(){ 128 | struct CLLNode *head = NULL; 129 | printf("%d \n",length(head)); 130 | insertAtBeginInCLL(&head, 30); 131 | insertAtBeginInCLL(&head, 20); 132 | insertAtBeginInCLL(&head, 10); 133 | printf("List length is %d \n",length(head)); 134 | printList(head); 135 | printf("\n"); 136 | insertAtEndInCLL(&head, 40); 137 | insertAtEndInCLL(&head, 50); 138 | insertAtEndInCLL(&head, 60); 139 | printf("List length is %d \n",length(head)); 140 | printList(head); 141 | deleteLastNodeFromCLL(&head); 142 | printf("List length is %d \n",length(head)); 143 | printList(head); 144 | deleteFrontNodeFromCLL(&head); 145 | printf("List length is %d \n",length(head)); 146 | printList(head); 147 | return 0; 148 | } 149 | -------------------------------------------------------------------------------- /src/Chapter_03_Linked_Lists/findLoopBeginning.c: -------------------------------------------------------------------------------- 1 | /*Copyright (c) 2008 CareerMonk Publications and others. 2 | #E-Mail : info@careermonk.com 3 | #Creation Date : 2008-01-10 06:15:46 4 | #Created by : Narasimha Karumanchi 5 | #Book Title : Data Structures And Algorithms Made Easy 6 | #Warranty : This software is provided "as is" without any 7 | # warranty; without even the implied warranty of 8 | # merchantability or fitness for a particular purpose.*/ 9 | 10 | #include 11 | #include 12 | 13 | /* A structure of linked list ListNode */ 14 | struct ListNode { 15 | int data; 16 | struct ListNode *next; 17 | } *head; 18 | 19 | void initialize(){ 20 | head = NULL; 21 | } 22 | 23 | /* 24 | Given a Inserts a ListNode in pTemp of a singly linked list. 25 | */ 26 | void insert(int data) { 27 | /* Create a new Linked List ListNode */ 28 | struct ListNode* newNode = (struct ListNode*) malloc(sizeof(struct ListNode)); 29 | newNode->data = data; 30 | /* Next pointer of new ListNode will point to head ListNode of linked list */ 31 | newNode->next = head; 32 | /* make new ListNode as new head of linked list */ 33 | head = newNode; 34 | printf("Inserted Element : %d\n", data); 35 | } 36 | 37 | int getLength(struct ListNode *head){ 38 | /* Input Validation */ 39 | if (head == NULL) { 40 | printf("Error : Invalid ListNode pointer !!!\n"); 41 | return 0; 42 | } 43 | 44 | int length =0; 45 | while(head != NULL){ 46 | head = head->next; 47 | length++; 48 | } 49 | return length; 50 | } 51 | 52 | 53 | int checkLoop(struct ListNode *head) { 54 | struct ListNode *slow, *fast; 55 | slow = fast = head; 56 | 57 | while(fast && fast->next) { 58 | /* Slow pointer will move one node per iteration whereas fast node will move two nodes per iteration */ 59 | slow = slow->next; 60 | fast = fast->next->next; 61 | if (slow == fast) { 62 | printf("\n Linked list contains a loop\n"); 63 | return 1; 64 | } 65 | } 66 | printf("\n No loop in linked list\n"); 67 | return 0; 68 | } 69 | 70 | struct ListNode * findLoopBeginning(struct ListNode * head) { 71 | struct ListNode *slow = head, *fast = head; 72 | int loopExists = 0; 73 | while (fast && fast->next) { 74 | slow = slow->next; 75 | fast = fast->next->next; 76 | if (slow == fast){ 77 | loopExists = 1; 78 | break; 79 | } 80 | } 81 | if(loopExists) { 82 | slow = head; 83 | while(slow != fast) { 84 | fast = fast->next; 85 | slow = slow->next; 86 | } 87 | return slow; 88 | } 89 | return NULL; 90 | } 91 | 92 | /* 93 | Prints a linked list from head ListNode till tail ListNode 94 | */ 95 | void printLinkedList(struct ListNode *ListNodePtr) { 96 | while (ListNodePtr != NULL) { 97 | printf("%d", ListNodePtr->data); 98 | ListNodePtr = ListNodePtr->next; 99 | if(ListNodePtr != NULL) 100 | printf("-->"); 101 | } 102 | } 103 | 104 | int main() { 105 | struct ListNode *temp; 106 | initialize(); 107 | /* Creating a linked List*/ 108 | insert(8); 109 | insert(3); 110 | insert(2); 111 | insert(7); 112 | insert(9); 113 | 114 | printf("\nLinked List\n"); 115 | printLinkedList(head); 116 | checkLoop(head); 117 | /* Create loop in linked list. Set next pointer of last node to second node from head */ 118 | head->next->next->next->next->next = head->next->next; 119 | checkLoop(head); 120 | temp = findLoopBeginning(head); 121 | printf ("\n Loop beginning is %d", temp->data); 122 | return 0; 123 | } 124 | -------------------------------------------------------------------------------- /src/Chapter_03_Linked_Lists/intersectingListNode.c: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2008 CareerMonk Publications and others. 2 | // #E-Mail : info@careermonk.com 3 | // Creation Date : 2008-01-10 06:15:46 4 | // Created by : Narasimha Karumanchi 5 | // Book Title : Data Structures And Algorithms Made Easy 6 | // Warranty : This software is provided "as is" without any 7 | // warranty; without even the implied warranty of 8 | // merchantability or fitness for a particular purpose. 9 | 10 | #include 11 | #include 12 | 13 | /* A structure of linked list ListNode */ 14 | struct ListNode { 15 | int data; 16 | struct ListNode *next; 17 | } *head1, *head2; 18 | 19 | void initialize(){ 20 | head1 = NULL; 21 | head2 = NULL; 22 | } 23 | 24 | /* 25 | Given a Inserts a ListNode in pTemp of a singly linked list. 26 | */ 27 | void insert(struct ListNode **head, int data) { 28 | /* Create a new Linked List ListNode */ 29 | struct ListNode* newListNode = (struct ListNode*) malloc(sizeof(struct ListNode)); 30 | newListNode->data = data; 31 | /* Next pointer of new ListNode will point to head ListNode of linked list */ 32 | newListNode->next = *head; 33 | /* make new ListNode as new head of linked list */ 34 | *head = newListNode; 35 | } 36 | 37 | int getLength(struct ListNode *head){ 38 | /* Input Validation */ 39 | if (head == NULL) { 40 | printf("Error : Invalid ListNode pointer !!!\n"); 41 | return 0; 42 | } 43 | 44 | int length =0; 45 | while(head != NULL){ 46 | head = head->next; 47 | length++; 48 | } 49 | return length; 50 | } 51 | 52 | // Prints a linked list from head ListNode till tail ListNode 53 | void printLinkedList(struct ListNode *head) { 54 | while (head != NULL) { 55 | printf("%d", head->data); 56 | head = head->next; 57 | if(head != NULL) 58 | printf("-->"); 59 | } 60 | } 61 | 62 | /* Reverses a given linked list, and return the head pointer of reversed linked list */ 63 | struct ListNode* reverseLinkedList(struct ListNode *head) { 64 | struct ListNode *previous, *current, *next; 65 | previous = NULL; 66 | current = head; 67 | 68 | while (current != NULL) { 69 | next = current->next; 70 | current->next = previous; 71 | previous = current; 72 | current = next; 73 | } 74 | return previous; 75 | } 76 | 77 | struct ListNode * intersectingListNode(struct ListNode * head1, struct ListNode * head2){ 78 | // get count of both the lists 79 | int m = getLength(head1); 80 | int n = getLength(head2); 81 | 82 | //to store the merge point 83 | struct ListNode * mergePoint = NULL; 84 | 85 | // finding the value of d based on the longer list 86 | int diff = (m > n) ? (m-n) : (n-m); 87 | 88 | //traverse the smaller longer list for 'diff' steps 89 | if(m > n){ 90 | while(diff--) 91 | head1 = head1 -> next; 92 | } 93 | else{ 94 | while(diff--) 95 | head2 = head2 -> next; 96 | } 97 | 98 | // now both lists have equal ListNodes till the end. 99 | while(head1 && head2){ 100 | if(head1 -> next->data == head2 -> next->data){ 101 | mergePoint = head1 -> next; 102 | break; 103 | } 104 | 105 | head1 = head1 -> next; 106 | head2 = head2 -> next; 107 | } 108 | 109 | return mergePoint; 110 | } 111 | 112 | int main() { 113 | struct ListNode *intersectingNode; 114 | initialize(); 115 | /* Creating a linked List*/ 116 | insert(&head1, 3); 117 | insert(&head1, 8); 118 | insert(&head1, 12); 119 | insert(&head1, 0); 120 | insert(&head1, 35); 121 | insert(&head1, 6); 122 | insert(&head1, 10); 123 | insert(&head1, 350); 124 | insert(&head1, 16); 125 | insert(&head1, 19); 126 | head1 = reverseLinkedList(head1); 127 | printf("\nLinked List\n"); 128 | printLinkedList(head1); 129 | insert(&head2, 13); 130 | insert(&head2, 18); 131 | insert(&head2, 112); 132 | insert(&head2, 10); 133 | insert(&head2, 135); 134 | insert(&head2, 16); 135 | insert(&head2, 10); 136 | insert(&head2, 350); 137 | insert(&head2, 16); 138 | insert(&head2, 19); 139 | head2 = reverseLinkedList(head2); 140 | printf("\nLinked List\n"); 141 | printLinkedList(head2); 142 | intersectingNode = intersectingListNode(head1, head2); 143 | if (intersectingListNode) 144 | printf("\n Intersecting ListNode is %d", intersectingNode->data); 145 | else 146 | printf("\n NULL \n"); 147 | return 0; 148 | } 149 | -------------------------------------------------------------------------------- /src/Chapter_03_Linked_Lists/intersectingNodeBruteForce.c: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2008 CareerMonk Publications and others. 2 | // #E-Mail : info@careermonk.com 3 | // Creation Date : 2008-01-10 06:15:46 4 | // Created by : Narasimha Karumanchi 5 | // Book Title : Data Structures And Algorithms Made Easy 6 | // Warranty : This software is provided "as is" without any 7 | // warranty; without even the implied warranty of 8 | // merchantability or fitness for a particular purpose. 9 | 10 | #include 11 | #include 12 | 13 | /* A structure of linked list ListNode */ 14 | struct ListNode { 15 | int data; 16 | struct ListNode *next; 17 | } *head1, *head2; 18 | 19 | void initialize(){ 20 | head1 = NULL; 21 | head2 = NULL; 22 | } 23 | 24 | /* 25 | Given a Inserts a ListNode in pTemp of a singly linked list. 26 | */ 27 | void insert(struct ListNode **head, int data) { 28 | /* Create a new Linked List ListNode */ 29 | struct ListNode* newNode = (struct ListNode*) malloc(sizeof(struct ListNode)); 30 | newNode->data = data; 31 | /* Next pointer of new ListNode will point to head ListNode of linked list */ 32 | newNode->next = *head; 33 | /* make new ListNode as new head of linked list */ 34 | *head = newNode; 35 | } 36 | 37 | int getLength(struct ListNode *head){ 38 | /* Input Validation */ 39 | if (head == NULL) { 40 | printf("Error : Invalid ListNode pointer !!!\n"); 41 | return 0; 42 | } 43 | 44 | int length =0; 45 | while(head != NULL){ 46 | head = head->next; 47 | length++; 48 | } 49 | return length; 50 | } 51 | 52 | // Prints a linked list from head ListNode till tail ListNode 53 | void printLinkedList(struct ListNode *head) { 54 | while (head != NULL) { 55 | printf("%d", head->data); 56 | head = head->next; 57 | if(head != NULL) 58 | printf("-->"); 59 | } 60 | } 61 | 62 | /* Reverses a given linked list, and return the head pointer of reversed linked list */ 63 | struct ListNode* reverseLinkedList(struct ListNode *head) { 64 | struct ListNode *previous, *current, *next; 65 | previous = NULL; 66 | current = head; 67 | 68 | while (current != NULL) { 69 | next = current->next; 70 | current->next = previous; 71 | previous = current; 72 | current = next; 73 | } 74 | return previous; 75 | } 76 | 77 | struct ListNode * intersectingNodeBruteForce(struct ListNode *head1, struct ListNode *head2){ 78 | // stores the result, if no ListNode is intersecting we return NULL 79 | struct ListNode *temp; 80 | 81 | while(head1 != NULL){ 82 | temp = head2; 83 | printf("\n List1 data is %d", head1->data); 84 | while(temp != NULL){ 85 | if(temp->data == head1->data){ 86 | printf("\n List2 data is %d", temp->data); 87 | // found a matching ListNode 88 | return head1; 89 | } 90 | temp = temp -> next; 91 | } 92 | head1 = head1 -> next; 93 | } 94 | return NULL; 95 | } 96 | 97 | int main() { 98 | struct ListNode *intersectingNode; 99 | initialize(); 100 | /* Creating a linked List*/ 101 | insert(&head1, 3); 102 | insert(&head1, 8); 103 | insert(&head1, 12); 104 | insert(&head1, 0); 105 | insert(&head1, 35); 106 | insert(&head1, 6); 107 | insert(&head1, 10); 108 | insert(&head1, 350); 109 | insert(&head1, 16); 110 | insert(&head1, 19); 111 | head1 = reverseLinkedList(head1); 112 | printf("\nLinked List\n"); 113 | printLinkedList(head1); 114 | insert(&head2, 13); 115 | insert(&head2, 18); 116 | insert(&head2, 112); 117 | insert(&head2, 10); 118 | insert(&head2, 135); 119 | insert(&head2, 16); 120 | insert(&head2, 10); 121 | insert(&head2, 350); 122 | insert(&head2, 16); 123 | insert(&head2, 19); 124 | head2 = reverseLinkedList(head2); 125 | printf("\nLinked List\n"); 126 | printLinkedList(head2); 127 | intersectingNode = intersectingNodeBruteForce(head1, head2); 128 | if (intersectingNode) 129 | printf("\n Intersecting node is %d", intersectingNode->data); 130 | else 131 | printf("\n NULL \n"); 132 | return 0; 133 | } 134 | -------------------------------------------------------------------------------- /src/Chapter_03_Linked_Lists/intersection.c: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2008 CareerMonk Publications and others. 2 | // #E-Mail : info@careermonk.com 3 | // Creation Date : 2008-01-10 06:15:46 4 | // Created by : Narasimha Karumanchi 5 | // Book Title : Data Structures And Algorithms Made Easy 6 | // Warranty : This software is provided "as is" without any 7 | // warranty; without even the implied warranty of 8 | // merchantability or fitness for a particular purpose. 9 | 10 | #include 11 | #include 12 | 13 | /* A structure of linked list ListNode */ 14 | struct ListNode { 15 | int data; 16 | struct ListNode *next; 17 | } *head1, *head2; 18 | 19 | void initialize(){ 20 | head1 = NULL; 21 | head2 = NULL; 22 | } 23 | 24 | /* 25 | Given a Inserts a ListNode in pTemp of a singly linked list. 26 | */ 27 | void insert(struct ListNode **head, int data) { 28 | /* Create a new Linked List ListNode */ 29 | struct ListNode* newNode = (struct ListNode*) malloc(sizeof(struct ListNode)); 30 | newNode->data = data; 31 | /* Next pointer of new ListNode will point to head ListNode of linked list */ 32 | newNode->next = *head; 33 | /* make new ListNode as new head of linked list */ 34 | *head = newNode; 35 | } 36 | 37 | int getLength(struct ListNode *head){ 38 | /* Input Validation */ 39 | if (head == NULL) { 40 | printf("Error : Invalid ListNode pointer !!!\n"); 41 | return 0; 42 | } 43 | 44 | int length =0; 45 | while(head != NULL){ 46 | head = head->next; 47 | length++; 48 | } 49 | return length; 50 | } 51 | 52 | // Prints a linked list from head ListNode till tail ListNode 53 | void printLinkedList(struct ListNode *head) { 54 | while (head != NULL) { 55 | printf("%d", head->data); 56 | head = head->next; 57 | if(head != NULL) 58 | printf("-->"); 59 | } 60 | } 61 | 62 | /* Reverses a given linked list, and return the head pointer of reversed linked list */ 63 | struct ListNode* reverseLinkedList(struct ListNode *head) { 64 | struct ListNode *previous, *current, *next; 65 | previous = NULL; 66 | current = head; 67 | 68 | while (current != NULL) { 69 | next = current->next; 70 | current->next = previous; 71 | previous = current; 72 | current = next; 73 | } 74 | return previous; 75 | } 76 | 77 | // Insert new Node in the beginning of the linked list 78 | void push(struct ListNode** head, int data){ 79 | struct ListNode* newNode = (struct ListNode*)malloc(sizeof(struct ListNode)); 80 | newNode->data = data; 81 | newNode->next = *head; 82 | *head = newNode; 83 | } 84 | 85 | // Solution to give common elements in the reverse 86 | struct ListNode * intersection1(struct ListNode *list1, struct ListNode *list2) { 87 | struct ListNode *head = NULL; 88 | while (list1 != NULL && list2 != NULL) { 89 | if (list1->data == list2->data) { 90 | push(&head, list1->data); // Copy common element. 91 | list1 = list1->next; 92 | list2 = list2->next; 93 | } else if (list1->data > list2->data) { 94 | list2 = list2->next; 95 | } else { // list1->data < list2->data 96 | list1 = list1->next; 97 | } 98 | } 99 | return head; 100 | } 101 | 102 | // Solution to give common elements in the reverse 103 | struct ListNode * intersection2(struct ListNode *list1, struct ListNode *list2) { 104 | struct ListNode *head = NULL; 105 | struct ListNode* tail; 106 | while (list1 != NULL && list2 != NULL) { 107 | if (list1->data == list2->data) { 108 | if (head == NULL) { 109 | push(&head, list1->data); 110 | tail = head; 111 | } 112 | else{ 113 | push(&tail->next, list1->data); 114 | tail = tail->next; 115 | } 116 | list1 = list1->next; 117 | list2 = list2->next; 118 | } else if (list1->data > list2->data) { 119 | list2 = list2->next; 120 | } else { // list1->data < list2->data 121 | list1 = list1->next; 122 | } 123 | } 124 | return head; 125 | } 126 | 127 | // Solution uses the temporary dummy node to build up the result list 128 | struct ListNode * intersection3(struct ListNode *list1, struct ListNode *list2) { 129 | struct ListNode dummy; 130 | struct ListNode *tail = &dummy; 131 | dummy.next = NULL; 132 | while (list1 != NULL && list2 != NULL) { 133 | if (list1->data == list2->data) { 134 | push((&tail->next), list1->data); // Copy common element. 135 | list1 = list1->next; 136 | list2 = list2->next; 137 | tail = tail->next; 138 | } else if (list1->data > list2->data) { 139 | list2 = list2->next; 140 | } else { // list1->data < list2->data 141 | list1 = list1->next; 142 | } 143 | } 144 | return dummy.next; 145 | } 146 | 147 | int main() { 148 | struct ListNode *commonNodes; 149 | initialize(); 150 | /* Creating a linked List*/ 151 | insert(&head1, 3); 152 | insert(&head1, 8); 153 | insert(&head1, 12); 154 | insert(&head1, 20); 155 | insert(&head1, 35); 156 | insert(&head1, 36); 157 | insert(&head1, 100); 158 | insert(&head1, 350); 159 | insert(&head1, 516); 160 | insert(&head1, 519); 161 | head1 = reverseLinkedList(head1); 162 | printf("\nLinked List\n"); 163 | printLinkedList(head1); 164 | insert(&head2, 3); 165 | insert(&head2, 8); 166 | insert(&head2, 13); 167 | insert(&head2, 22); 168 | insert(&head2, 35); 169 | insert(&head2, 36); 170 | insert(&head2, 200); 171 | insert(&head2, 380); 172 | insert(&head2, 516); 173 | insert(&head2, 529); 174 | head2 = reverseLinkedList(head2); 175 | printf("\nLinked List\n"); 176 | printLinkedList(head2); 177 | commonNodes = intersection1(head1, head2); 178 | printf("\nCommon elements\n"); 179 | while (commonNodes != NULL) { 180 | printf(" %d-->", commonNodes->data); 181 | commonNodes = commonNodes->next; 182 | } 183 | commonNodes = intersection2(head1, head2); 184 | printf("\nCommon elements\n"); 185 | while (commonNodes != NULL) { 186 | printf(" %d-->", commonNodes->data); 187 | commonNodes = commonNodes->next; 188 | } 189 | commonNodes = intersection3(head1, head2); 190 | printf("\nCommon elements\n"); 191 | while (commonNodes != NULL) { 192 | printf(" %d-->", commonNodes->data); 193 | commonNodes = commonNodes->next; 194 | } 195 | } 196 | -------------------------------------------------------------------------------- /src/Chapter_03_Linked_Lists/kth node from end.c: -------------------------------------------------------------------------------- 1 | /*Copyright (c) 2008 CareerMonk Publications and others. 2 | #E-Mail : info@careermonk.com 3 | #Creation Date : 2008-01-10 06:15:46 4 | #Created by : Narasimha Karumanchi 5 | #Book Title : Data Structures And Algorithms Made Easy 6 | #Warranty : This software is provided "as is" without any 7 | # warranty; without even the implied warranty of 8 | # merchantability or fitness for a particular purpose.*/ 9 | 10 | #include 11 | #include 12 | 13 | /* A structure of linked list ListNode */ 14 | struct ListNode { 15 | int data; 16 | struct ListNode *next; 17 | } *head; 18 | 19 | void initialize(){ 20 | head = NULL; 21 | } 22 | 23 | /* 24 | Given a Inserts a ListNode in pTemp of a singly linked list. 25 | */ 26 | void insert(int data) { 27 | /* Create a new Linked List ListNode */ 28 | struct ListNode* newNode = (struct ListNode*) malloc(sizeof(struct ListNode)); 29 | newNode->data = data; 30 | /* Next pointer of new ListNode will point to head ListNode of linked list */ 31 | newNode->next = head; 32 | /* make new ListNode as new head of linked list */ 33 | head = newNode; 34 | printf("Inserted Element : %d\n", data); 35 | } 36 | 37 | int getLength(struct ListNode *head){ 38 | /* Input Validation */ 39 | if (head == NULL) { 40 | printf("Error : Invalid ListNode pointer !!!\n"); 41 | return 0; 42 | } 43 | 44 | int length =0; 45 | while(head != NULL){ 46 | head = head->next; 47 | length++; 48 | } 49 | return length; 50 | } 51 | 52 | struct ListNode* kthNodeFromEnd(struct ListNode* head, int k){ 53 | struct ListNode *pTemp, *kthNode; 54 | int i; 55 | pTemp = kthNode = head; 56 | /* k should be less than length of Linked List */ 57 | if(k > getLength(head)){ 58 | printf("Error : k is greater than length of linked list\n"); 59 | return NULL; 60 | } 61 | /* Move pTemp pointer k-1 ListNodes. This will create 62 | a difference of k-1 ListNodes between pTemp and kthNode */ 63 | for(i = 0; i < k-1; i++){ 64 | pTemp = pTemp->next; 65 | } 66 | /* Now, move both pointers together till pTemp reaches 67 | last ListNode of linked list. when pTemp reaches last ListNode 68 | kthNode pointer will be pointing to Nth last ListNode*/ 69 | while(pTemp->next != NULL){ 70 | pTemp = pTemp->next; 71 | kthNode = kthNode->next; 72 | } 73 | 74 | return kthNode; 75 | } 76 | /* 77 | Prints a linked list from head ListNode till tail ListNode 78 | */ 79 | void printLinkedList(struct ListNode *ListNodePtr) { 80 | while (ListNodePtr != NULL) { 81 | printf("%d", ListNodePtr->data); 82 | ListNodePtr = ListNodePtr->next; 83 | if(ListNodePtr != NULL) 84 | printf("-->"); 85 | } 86 | } 87 | 88 | int main() { 89 | struct ListNode *kthNode; 90 | initialize(); 91 | /* Creating a linked List*/ 92 | insert(3); 93 | insert(8); 94 | insert(12); 95 | insert(0); 96 | insert(35); 97 | insert(6); 98 | 99 | printf("\nLinked List\n"); 100 | printLinkedList(head); 101 | kthNode = kthNodeFromEnd(head, 3); 102 | printf("\nkth node from end in the linked list is %d", kthNode->data); 103 | return 0; 104 | } 105 | -------------------------------------------------------------------------------- /src/Chapter_03_Linked_Lists/middleNode.c: -------------------------------------------------------------------------------- 1 | /*Copyright (c) 2008 CareerMonk Publications and others. 2 | #E-Mail : info@careermonk.com 3 | #Creation Date : 2008-01-10 06:15:46 4 | #Created by : Narasimha Karumanchi 5 | #Book Title : Data Structures And Algorithms Made Easy 6 | #Warranty : This software is provided "as is" without any 7 | # warranty; without even the implied warranty of 8 | # merchantability or fitness for a particular purpose.*/ 9 | 10 | #include 11 | #include 12 | 13 | /* A structure of linked list ListNode */ 14 | struct ListNode { 15 | int data; 16 | struct ListNode *next; 17 | } *head; 18 | 19 | void initialize(){ 20 | head = NULL; 21 | } 22 | 23 | /* 24 | Given a Inserts a ListNode in pTemp of a singly linked list. 25 | */ 26 | void insert(int data) { 27 | /* Create a new Linked List ListNode */ 28 | struct ListNode* newNode = (struct ListNode*) malloc(sizeof(struct ListNode)); 29 | newNode->data = data; 30 | /* Next pointer of new ListNode will point to head ListNode of linked list */ 31 | newNode->next = head; 32 | /* make new ListNode as new head of linked list */ 33 | head = newNode; 34 | printf("Inserted Element : %d\n", data); 35 | } 36 | 37 | int getLength(struct ListNode *head){ 38 | /* Input Validation */ 39 | if (head == NULL) { 40 | printf("Error : Invalid ListNode pointer !!!\n"); 41 | return 0; 42 | } 43 | 44 | int length =0; 45 | while(head != NULL){ 46 | head = head->next; 47 | length++; 48 | } 49 | return length; 50 | } 51 | 52 | struct ListNode * middleNode(struct ListNode *head){ 53 | /* Input Validation */ 54 | if(head == NULL){ 55 | printf("Error: List is empty!\n"); 56 | return NULL; 57 | } 58 | struct ListNode *slow, *fast; 59 | slow = fast = head; 60 | /* In every iteration, slow pointer will move one node whereas fast pointer will move two ListNodes. 61 | When fast pointer reaches last ListNode then slow pointer will be pointing to middle ListNode */ 62 | while(fast != NULL && fast->next != NULL) { 63 | fast = fast->next->next; 64 | slow = slow->next; 65 | } 66 | return slow; 67 | } 68 | 69 | /* 70 | Prints a linked list from head ListNode till tail ListNode 71 | */ 72 | void printLinkedList(struct ListNode *ListNodePtr) { 73 | while (ListNodePtr != NULL) { 74 | printf("%d", ListNodePtr->data); 75 | ListNodePtr = ListNodePtr->next; 76 | if(ListNodePtr != NULL) 77 | printf("-->"); 78 | } 79 | } 80 | 81 | int main() { 82 | struct ListNode *middle; 83 | initialize(); 84 | /* Creating a linked List*/ 85 | insert(3); 86 | insert(8); 87 | insert(12); 88 | insert(0); 89 | insert(35); 90 | insert(6); 91 | insert(10); 92 | insert(350); 93 | insert(16); 94 | insert(19); 95 | printf("\nLinked List\n"); 96 | printLinkedList(head); 97 | middle = middleNode(head); 98 | printf("\n Middle in the linked list is %d", middle->data); 99 | return 0; 100 | } 101 | -------------------------------------------------------------------------------- /src/Chapter_03_Linked_Lists/printListInReverse.c: -------------------------------------------------------------------------------- 1 | /*Copyright (c) 2008 CareerMonk Publications and others. 2 | #E-Mail : info@careermonk.com 3 | #Creation Date : 2008-01-10 06:15:46 4 | #Created by : Narasimha Karumanchi 5 | #Book Title : Data Structures And Algorithms Made Easy 6 | #Warranty : This software is provided "as is" without any 7 | # warranty; without even the implied warranty of 8 | # merchantability or fitness for a particular purpose.*/ 9 | #include 10 | #include 11 | 12 | /* A structure of linked list ListNode */ 13 | struct ListNode { 14 | int data; 15 | struct ListNode *next; 16 | } *head; 17 | 18 | void initialize(){ 19 | head = NULL; 20 | } 21 | 22 | /* 23 | Given a Inserts a ListNode in pTemp of a singly linked list. 24 | */ 25 | void insert(int data) { 26 | /* Create a new Linked List ListNode */ 27 | struct ListNode* newNode = (struct ListNode*) malloc(sizeof(struct ListNode)); 28 | newNode->data = data; 29 | /* Next pointer of new ListNode will point to head ListNode of linked list */ 30 | newNode->next = head; 31 | /* make new ListNode as new head of linked list */ 32 | head = newNode; 33 | printf("Inserted Element : %d\n", data); 34 | } 35 | 36 | int getLength(struct ListNode *head){ 37 | /* Input Validation */ 38 | if (head == NULL) { 39 | printf("Error : Invalid ListNode pointer !!!\n"); 40 | return 0; 41 | } 42 | 43 | int length =0; 44 | while(head != NULL){ 45 | head = head->next; 46 | length++; 47 | } 48 | return length; 49 | } 50 | 51 | void printListInReverse(struct ListNode *head) { 52 | if(!head) 53 | return; 54 | printListInReverse(head->next); 55 | printf("%d-->", head->data); 56 | } 57 | /* 58 | Prints a linked list from head ListNode till tail ListNode 59 | */ 60 | void printLinkedList(struct ListNode *ListNodePtr) { 61 | while (ListNodePtr != NULL) { 62 | printf("%d", ListNodePtr->data); 63 | ListNodePtr = ListNodePtr->next; 64 | if(ListNodePtr != NULL) 65 | printf("-->"); 66 | } 67 | } 68 | 69 | int main() { 70 | struct ListNode *middle; 71 | initialize(); 72 | /* Creating a linked List*/ 73 | insert(3); 74 | insert(8); 75 | insert(12); 76 | insert(0); 77 | insert(35); 78 | insert(6); 79 | insert(10); 80 | insert(350); 81 | insert(16); 82 | insert(19); 83 | printf("\nLinked List\n"); 84 | printLinkedList(head); 85 | printf("\nLinked list in reverse\n"); 86 | printListInReverse(head); 87 | return 0; 88 | } 89 | -------------------------------------------------------------------------------- /src/Chapter_03_Linked_Lists/removeDuplicates.c: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2008 CareerMonk Publications and others. 2 | // #E-Mail : info@careermonk.com 3 | // Creation Date : 2008-01-10 06:15:46 4 | // Created by : Narasimha Karumanchi 5 | // Book Title : Data Structures And Algorithms Made Easy 6 | // Warranty : This software is provided "as is" without any 7 | // warranty; without even the implied warranty of 8 | // merchantability or fitness for a particular purpose. 9 | 10 | #include 11 | #include 12 | 13 | /* A structure of linked list ListNode */ 14 | struct ListNode { 15 | int data; 16 | struct ListNode *next; 17 | } *head; 18 | 19 | void initialize(){ 20 | head = NULL; 21 | } 22 | 23 | /* 24 | Given a Inserts a ListNode in pTemp of a singly linked list. 25 | */ 26 | void insert(struct ListNode **head, int data) { 27 | /* Create a new Linked List ListNode */ 28 | struct ListNode* newNode = (struct ListNode*) malloc(sizeof(struct ListNode)); 29 | newNode->data = data; 30 | /* Next pointer of new ListNode will point to head ListNode of linked list */ 31 | newNode->next = *head; 32 | /* make new ListNode as new head of linked list */ 33 | *head = newNode; 34 | } 35 | 36 | int getLength(struct ListNode *head){ 37 | /* Input Validation */ 38 | if (head == NULL) { 39 | printf("Error : Invalid ListNode pointer !!!\n"); 40 | return 0; 41 | } 42 | 43 | int length =0; 44 | while(head != NULL){ 45 | head = head->next; 46 | length++; 47 | } 48 | return length; 49 | } 50 | 51 | // Prints a linked list from head ListNode till tail ListNode 52 | void printLinkedList(struct ListNode *head) { 53 | while (head != NULL) { 54 | printf("%d", head->data); 55 | head = head->next; 56 | if(head != NULL) 57 | printf("-->"); 58 | } 59 | } 60 | 61 | /* Reverses a given linked list, and return the head pointer of reversed linked list */ 62 | struct ListNode* reverseLinkedList(struct ListNode *head) { 63 | struct ListNode *previous, *current, *next; 64 | previous = NULL; 65 | current = head; 66 | 67 | while (current != NULL) { 68 | next = current->next; 69 | current->next = previous; 70 | previous = current; 71 | current = next; 72 | } 73 | return previous; 74 | } 75 | 76 | // Remove duplicates from a sorted list 77 | void removeDuplicates(struct ListNode **head) { 78 | struct ListNode* current = *head; 79 | if (current == NULL) return; // do nothing if the list is empty 80 | // Compare current ListNode with next ListNode 81 | while(current->next!=NULL) { 82 | if (current->data == current->next->data) { 83 | struct ListNode* nextNext = current->next->next; 84 | free(current->next); 85 | current->next = nextNext; 86 | } 87 | else { 88 | current = current->next; // only advance if no deletion 89 | } 90 | } 91 | } 92 | 93 | int main() { 94 | struct ListNode *commonNodes; 95 | initialize(); 96 | /* Creating a linked List*/ 97 | insert(&head, 3); 98 | insert(&head, 8); 99 | insert(&head, 13); 100 | insert(&head, 13); 101 | insert(&head, 35); 102 | insert(&head, 120); 103 | insert(&head, 200); 104 | insert(&head, 200); 105 | insert(&head, 516); 106 | insert(&head, 516); 107 | printf("\nLinked List\n"); 108 | head = reverseLinkedList(head); 109 | printLinkedList(head); 110 | removeDuplicates(&head); 111 | printf("\nLinked List\n"); 112 | printLinkedList(head); 113 | } 114 | -------------------------------------------------------------------------------- /src/Chapter_03_Linked_Lists/reverseLinkedList.c: -------------------------------------------------------------------------------- 1 | /*Copyright (c) 2008 CareerMonk Publications and others. 2 | #E-Mail : info@careermonk.com 3 | #Creation Date : 2008-01-10 06:15:46 4 | #Created by : Narasimha Karumanchi 5 | #Book Title : Data Structures And Algorithms Made Easy 6 | #Warranty : This software is provided "as is" without any 7 | # warranty; without even the implied warranty of 8 | # merchantability or fitness for a particular purpose.*/ 9 | 10 | #include 11 | #include 12 | 13 | /* A structure of linked list ListNode */ 14 | struct ListNode { 15 | int data; 16 | struct ListNode *next; 17 | } *head; 18 | 19 | void initialize(){ 20 | head = NULL; 21 | } 22 | 23 | /* 24 | Given a Inserts a ListNode in pTemp of a singly linked list. 25 | */ 26 | void insert(int data) { 27 | /* Create a new Linked List ListNode */ 28 | struct ListNode* newNode = (struct ListNode*) malloc(sizeof(struct ListNode)); 29 | newNode->data = data; 30 | /* Next pointer of new ListNode will point to head ListNode of linked list */ 31 | newNode->next = head; 32 | /* make new ListNode as new head of linked list */ 33 | head = newNode; 34 | printf("Inserted Element : %d\n", data); 35 | } 36 | 37 | int getLength(struct ListNode *head){ 38 | /* Input Validation */ 39 | if (head == NULL) { 40 | printf("Error : Invalid ListNode pointer !!!\n"); 41 | return 0; 42 | } 43 | 44 | int length =0; 45 | while(head != NULL){ 46 | head = head->next; 47 | length++; 48 | } 49 | return length; 50 | } 51 | 52 | /* Reverses a given linked list, and return the head pointer of reversed linked list */ 53 | struct ListNode* reverseLinkedList(struct ListNode *head) { 54 | struct ListNode *previous, *current, *next; 55 | previous = NULL; 56 | current = head; 57 | 58 | while (current != NULL) { 59 | next = current->next; 60 | current->next = previous; 61 | previous = current; 62 | current = next; 63 | } 64 | return previous; 65 | } 66 | 67 | struct ListNode * reverseLinkedListRecursive(struct ListNode *head) { 68 | if (head == NULL || head->next == NULL) 69 | return head; 70 | struct ListNode *secondElem = head->next; 71 | // Need to unlink list from the rest or you will get a cycle 72 | head->next = NULL; 73 | // Reverse everything from the second element on 74 | struct ListNode *reverseRest = reverseLinkedListRecursive(secondElem); 75 | secondElem->next = head; // then we join the two lists 76 | return reverseRest; 77 | } 78 | /* 79 | Prints a linked list from head ListNode till tail ListNode 80 | */ 81 | void printLinkedList(struct ListNode *ListNodePtr) { 82 | while (ListNodePtr != NULL) { 83 | printf("%d", ListNodePtr->data); 84 | ListNodePtr = ListNodePtr->next; 85 | if(ListNodePtr != NULL) 86 | printf("-->"); 87 | } 88 | } 89 | 90 | int main() { 91 | struct ListNode *middle; 92 | initialize(); 93 | /* Creating a linked List*/ 94 | insert(3); 95 | insert(8); 96 | insert(12); 97 | insert(0); 98 | insert(35); 99 | insert(6); 100 | insert(10); 101 | insert(350); 102 | insert(16); 103 | insert(19); 104 | printf("\nLinked List\n"); 105 | printLinkedList(head); 106 | printf("\nLinked list in reverse\n"); 107 | head = reverseLinkedListRecursive(head); 108 | printLinkedList(head); 109 | return 0; 110 | } 111 | -------------------------------------------------------------------------------- /src/Chapter_03_Linked_Lists/sortedInsert.c: -------------------------------------------------------------------------------- 1 | /*Copyright (c) 2008 CareerMonk Publications and others. 2 | #E-Mail : info@careermonk.com 3 | #Creation Date : 2008-01-10 06:15:46 4 | #Created by : Narasimha Karumanchi 5 | #Book Title : Data Structures And Algorithms Made Easy 6 | #Warranty : This software is provided "as is" without any 7 | # warranty; without even the implied warranty of 8 | # merchantability or fitness for a particular purpose.*/ 9 | #include 10 | #include 11 | 12 | /* A structure of linked list ListNode */ 13 | struct ListNode { 14 | int data; 15 | struct ListNode *next; 16 | } *head; 17 | 18 | void initialize(){ 19 | head = NULL; 20 | } 21 | 22 | /* 23 | Given a Inserts a ListNode in pTemp of a singly linked list. 24 | */ 25 | void insert(int data) { 26 | /* Create a new Linked List ListNode */ 27 | struct ListNode* newNode = (struct ListNode*) malloc(sizeof(struct ListNode)); 28 | newNode->data = data; 29 | /* Next pointer of new ListNode will point to head ListNode of linked list */ 30 | newNode->next = head; 31 | /* make new ListNode as new head of linked list */ 32 | head = newNode; 33 | printf("Inserted Element : %d\n", data); 34 | } 35 | 36 | int getLength(struct ListNode *head){ 37 | /* Input Validation */ 38 | if (head == NULL) { 39 | printf("Error : Invalid ListNode pointer !!!\n"); 40 | return 0; 41 | } 42 | 43 | int length =0; 44 | while(head != NULL){ 45 | head = head->next; 46 | length++; 47 | } 48 | return length; 49 | } 50 | 51 | // Function to insert the given node into the correct sorted position in the given list sorted in increasing order 52 | void sortedInsert(struct ListNode** head, int data){ 53 | /* Create a new Linked List ListNode */ 54 | struct ListNode* newNode = (struct ListNode*) malloc(sizeof(struct ListNode)); 55 | newNode->data = data; 56 | // Special case for the head end 57 | if (*head == NULL || (*head)->data >= newNode->data){ 58 | newNode->next = *head; 59 | *head = newNode; 60 | return; 61 | } 62 | 63 | // Locate the node before the point of insertion 64 | struct ListNode* current = *head; 65 | while(current->next != NULL && current->next->data < newNode->data) 66 | current = current->next; 67 | 68 | newNode->next = current->next; 69 | current->next = newNode; 70 | } 71 | 72 | /* 73 | Prints a linked list from head ListNode till tail ListNode 74 | */ 75 | void printLinkedList(struct ListNode *ListNodePtr) { 76 | while (ListNodePtr != NULL) { 77 | printf("%d", ListNodePtr->data); 78 | ListNodePtr = ListNodePtr->next; 79 | if(ListNodePtr != NULL) 80 | printf("-->"); 81 | } 82 | } 83 | 84 | int main() { 85 | struct ListNode *temp; 86 | initialize(); 87 | /* Creating a linked List*/ 88 | sortedInsert(&head, 1); 89 | 90 | sortedInsert(&head, 19); 91 | sortedInsert(&head, 5); 92 | sortedInsert(&head, 61); 93 | sortedInsert(&head, 7); 94 | 95 | printf("\nLinked List\n"); 96 | printLinkedList(head); 97 | return 0; 98 | } 99 | -------------------------------------------------------------------------------- /src/Chapter_04_Queues/DynamicQueue.c: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2008 CareerMonk Publications and others. 2 | // #E-Mail : info@careermonk.com 3 | // Creation Date : 2008-01-10 06:15:46 4 | // Created by : Narasimha Karumanchi 5 | // Book Title : Data Structures And Algorithms Made Easy 6 | // Warranty : This software is provided "as is" without any 7 | // warranty; without even the implied warranty of 8 | // merchantability or fitness for a particular purpose. 9 | 10 | #include 11 | #include 12 | #include 13 | 14 | struct Queue { 15 | int front, rear; 16 | int capacity; 17 | int size; 18 | int *array; 19 | }; 20 | 21 | // Create an empty queue 22 | struct Queue *createQueue(int capacity) { 23 | struct Queue *Q = malloc(sizeof(struct Queue)); 24 | if(!Q) 25 | return NULL; 26 | Q->capacity = capacity; 27 | Q->front = Q->rear = -1; 28 | Q->size = 0; 29 | Q->array= malloc(Q->capacity * sizeof(int)); 30 | 31 | if(!Q->array) 32 | return NULL; 33 | return Q; 34 | } 35 | 36 | // Returns queue size 37 | int size(struct Queue *Q) { 38 | return Q->size; 39 | } 40 | 41 | // Returns Frnt Element of the Queue 42 | int frontElement(struct Queue *Q) { 43 | return Q->array[Q->front]; 44 | } 45 | 46 | // Returns the Rear Element of the Queue 47 | int rearElement(struct Queue *Q) { 48 | return Q->array[Q->rear]; 49 | } 50 | 51 | // Check's if Queue is empty or not 52 | int isEmpty(struct Queue *Q) { 53 | // if the condition is true then 1 is returned else 0 is returned 54 | return (Q->size == 0); 55 | } 56 | 57 | // Check's if Queue is full or not 58 | int isFull(struct Queue *Q) { 59 | // if the condition is true then 1 is returned else 0 is returned 60 | return (Q->size == Q->capacity); 61 | } 62 | 63 | void resizeQueue(struct Queue *Q) { 64 | int size = Q->capacity; 65 | Q->capacity = Q->capacity*2; 66 | Q->array = realloc (Q->array, sizeof(int) * Q->capacity); 67 | if(!Q->array) { 68 | printf("Memory Error"); 69 | return; 70 | } 71 | if(Q->front > Q->rear ) { 72 | for(int i=0; i < Q->front; i++) { 73 | Q->array[i+size] =Q->array[i]; 74 | } 75 | Q->rear = Q->rear + size; 76 | } 77 | } 78 | 79 | 80 | // Adding elements in Queue 81 | void enqueue(struct Queue *Q, int data) { 82 | if(isFull(Q)) 83 | resizeQueue(Q); 84 | Q->rear = (Q->rear+1) % Q->capacity; 85 | Q->array[Q->rear]= data; 86 | if(Q->front == -1) 87 | Q->front = Q->rear; 88 | Q->size += 1; 89 | } 90 | 91 | // Removes an element from front of the queue 92 | int dequeue(struct Queue *Q) { 93 | int data = INT_MIN; //or element which does not exist in Queue 94 | if(isEmpty(Q)){ 95 | printf("Queue is empty\n"); 96 | return data; 97 | } 98 | data = Q->array[Q->front]; 99 | if(Q->front == Q->rear) { 100 | Q->front = Q->rear = -1; 101 | Q->size = 0; 102 | } else { 103 | Q->front = (Q->front+1) % Q->capacity; 104 | Q->size -= 1; 105 | } 106 | return data; 107 | } 108 | 109 | void deleteQueue(struct Queue *Q) { 110 | if(Q) { 111 | if(Q->array) 112 | free(Q->array); 113 | free(Q); 114 | } 115 | } 116 | 117 | int main() { 118 | // Initializing Queue 119 | struct Queue *Q; 120 | Q = createQueue(3); 121 | 122 | // Adding elements in Queue 123 | enqueue(Q, 1); 124 | enqueue(Q, 3); 125 | enqueue(Q, 7); 126 | enqueue(Q, 5); 127 | enqueue(Q, 10); 128 | enqueue(Q, 19); 129 | 130 | // Printing size of Queue 131 | printf("\nSize of queue : %d\n", size(Q)); 132 | 133 | // Printing front and rear element of Queue */ 134 | printf("Front element : %d\n", frontElement(Q)); 135 | printf("Rear element : %d\n", rearElement(Q)); 136 | 137 | // Removing Element from Queue 138 | printf("\nDequeued element : %d\n", dequeue(Q)); 139 | printf("Dequeued element : %d\n", dequeue(Q)); 140 | printf("Dequeued element : %d\n", dequeue(Q)); 141 | printf("Dequeued element : %d\n", dequeue(Q)); 142 | printf("Dequeued element : %d\n", dequeue(Q)); 143 | printf("Dequeued element : %d\n", dequeue(Q)); 144 | enqueue(Q, 15); 145 | enqueue(Q, 100); 146 | 147 | // Printing size of Queue 148 | printf("\nSize of queue : %d\n", size(Q)); 149 | 150 | // Printing front and rear element of Queue 151 | printf("Front element : %d\n", frontElement(Q)); 152 | printf("Rear element : %d\n", rearElement(Q)); 153 | 154 | // Removing Queue 155 | deleteQueue(Q); 156 | return 0; 157 | } 158 | -------------------------------------------------------------------------------- /src/Chapter_04_Queues/QueueWithTwoStacks.c: -------------------------------------------------------------------------------- 1 | /*Copyright (c) 2016 CareerMonk Publications and others. 2 | #E-Mail : info@careermonk.com 3 | #Creation Date : 2008-01-10 06:15:46 4 | #Created by : Narasimha Karumanchi 5 | #Book Title : Data Structures And Algorithms Made Easy 6 | #Warranty : This software is provided "as is" without any 7 | # warranty; without even the implied warranty of 8 | # merchantability or fitness for a particular purpose.*/ 9 | 10 | #include 11 | #include 12 | #include 13 | 14 | struct Stack { 15 | int top; 16 | int capacity; 17 | int *array; 18 | }; 19 | 20 | struct Stack *createStack(int capacity) { 21 | struct Stack *S = malloc(sizeof(struct Stack)); 22 | if(!S) 23 | return NULL; 24 | S->capacity = capacity; 25 | S->top = -1; 26 | S->array= malloc(S->capacity * sizeof(int)); 27 | if(!S->array) 28 | return NULL; 29 | return S; 30 | } 31 | 32 | int isEmpty(struct Stack *S) { 33 | return (S->top == -1); // if the condition is true then 1 is returned else 0 is returned 34 | } 35 | 36 | int size(struct Stack *S) { 37 | return (S->top + 1); 38 | } 39 | 40 | int isFull(struct Stack *S){ 41 | //if the condition is true then 1 is returned else 0 is returned 42 | return (S->top == S->capacity - 1); 43 | } 44 | 45 | void doubleStack(struct Stack *S){ 46 | S->capacity *= 2; 47 | S->array = realloc(S->array, S->capacity * sizeof(int)); 48 | } 49 | 50 | 51 | void push(struct Stack *S, int data){ 52 | if(isFull(S)) 53 | doubleStack(S); 54 | S->array[++S->top] = data; 55 | } 56 | 57 | int pop(struct Stack *S){ 58 | /* S->top == - 1 indicates empty stack*/ 59 | if(isEmpty(S)){ 60 | printf("Stack is Empty\n"); 61 | return INT_MIN; 62 | } 63 | else /* Removing element from ‘top’ of the array and reducing ‘top’ by 1*/ 64 | return (S->array[S->top--]); 65 | } 66 | 67 | int peek(struct Stack *S){ 68 | /* S->top == - 1 indicates empty stack*/ 69 | if(isEmpty(S)){ 70 | printf("Stack is Empty"); 71 | return INT_MIN;; 72 | } 73 | else 74 | return (S->array[S->top]); 75 | } 76 | 77 | void deleteStack(struct Stack *S){ 78 | if(S) { 79 | if(S->array) 80 | free(S->array); 81 | free(S); 82 | } 83 | } 84 | 85 | struct Queue { 86 | struct Stack *S1; // for enQueue 87 | struct Stack *S2; // for deQueue 88 | }; 89 | 90 | int queueSize(struct Queue *Q) { 91 | return size(Q->S1); 92 | } 93 | 94 | struct Queue *createQueue(int capacity) { 95 | struct Stack *S1 = createStack(capacity); 96 | struct Stack *S2 = createStack(capacity); 97 | struct Queue *Q = malloc(sizeof(struct Queue)); 98 | if(!Q) 99 | return NULL; 100 | Q->S1 = S1; 101 | Q->S2 = S2; 102 | return Q; 103 | } 104 | 105 | void enQueue(struct Queue *Q, int data) { 106 | push(Q->S1, data); 107 | } 108 | 109 | int deQueue(struct Queue *Q) { 110 | if(!isEmpty(Q->S2)) 111 | return pop(Q->S2); 112 | else { 113 | while( !isEmpty(Q->S1) ) 114 | push(Q->S2, pop(Q->S1)); 115 | return pop(Q->S2); 116 | } 117 | } 118 | 119 | void deleteQueue(struct Queue *Q){ 120 | if(Q) { 121 | if(Q->S1) 122 | free(Q->S1); 123 | if(Q->S2) 124 | free(Q->S2); 125 | free(Q); 126 | } 127 | } 128 | 129 | int main(){ 130 | // Initializing Queue 131 | struct Queue *Q; 132 | Q = createQueue(6); 133 | 134 | // Adding elements in Queue 135 | enQueue(Q, 1); 136 | enQueue(Q, 3); 137 | enQueue(Q, 7); 138 | enQueue(Q, 5); 139 | enQueue(Q, 10); 140 | enQueue(Q, 19); 141 | 142 | // Printing size of Queue 143 | printf("\nSize of queue : %d\n", queueSize(Q)); 144 | 145 | // Removing Element from Queue 146 | printf("\nDequeued element : %d\n", deQueue(Q)); 147 | printf("Dequeued element : %d\n", deQueue(Q)); 148 | printf("Dequeued element : %d\n", deQueue(Q)); 149 | printf("Dequeued element : %d\n", deQueue(Q)); 150 | printf("Dequeued element : %d\n", deQueue(Q)); 151 | printf("Dequeued element : %d\n", deQueue(Q)); 152 | 153 | // Removing Queue 154 | deleteQueue(Q); 155 | return 0; 156 | } 157 | -------------------------------------------------------------------------------- /src/Chapter_04_Queues/QueuesWithLinkedLists.c: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2008 CareerMonk Publications and others. 2 | // #E-Mail : info@careermonk.com 3 | // Creation Date : 2008-01-10 06:15:46 4 | // Created by : Narasimha Karumanchi 5 | // Book Title : Data Structures And Algorithms Made Easy 6 | // Warranty : This software is provided "as is" without any 7 | // warranty; without even the implied warranty of 8 | // merchantability or fitness for a particular purpose. 9 | 10 | #include 11 | #include 12 | 13 | struct ListNode { 14 | int data; 15 | struct ListNode *next; 16 | }; 17 | 18 | struct Queue { 19 | struct ListNode *front; 20 | struct ListNode *rear; 21 | }; 22 | 23 | /* Create an empty queue */ 24 | struct Queue *CreateQueue() { 25 | struct Queue *Q; 26 | struct ListNode *temp; 27 | Q = malloc(sizeof(struct Queue)); 28 | if(!Q) 29 | return NULL; 30 | 31 | temp = malloc(sizeof(struct ListNode)); 32 | Q->front = Q->rear = NULL; 33 | return Q; 34 | } 35 | 36 | /* Returns queue size */ 37 | int size(struct Queue *Q) { 38 | struct ListNode *temp = Q->front; 39 | int count = 0; 40 | 41 | if(Q->front == NULL && Q->rear == NULL) 42 | return 0; 43 | 44 | while(temp != Q->rear){ 45 | count++; 46 | temp = temp->next; 47 | } 48 | if(temp == Q->rear) 49 | count++; 50 | 51 | return count; 52 | } 53 | 54 | /* Returns Frnt Element of the Queue */ 55 | int frontElement(struct Queue *Q) { 56 | return Q->front->data; 57 | } 58 | 59 | /* Returns the Rear Element of the Queue */ 60 | int rearElement(struct Queue *Q) { 61 | return Q->rear->data; 62 | } 63 | 64 | /* 65 | Check's if Queue is empty or not 66 | */ 67 | void isEmpty(struct Queue *Q) { 68 | if (Q->front == NULL && Q->rear == NULL) 69 | printf("Empty Queue\n"); 70 | else 71 | printf("Queue is not Empty\n"); 72 | } 73 | /* 74 | Adding elements in Queue 75 | */ 76 | void enqueue(struct Queue *Q, int num) { 77 | struct ListNode *temp; 78 | temp = (struct ListNode *)malloc(sizeof(struct ListNode)); 79 | temp->data = num; 80 | temp->next = NULL; 81 | 82 | if (Q->rear == NULL) { 83 | Q->front = Q->rear = temp; 84 | } else { 85 | Q->rear->next = temp; 86 | Q->rear = temp; 87 | } 88 | } 89 | 90 | /* 91 | Removes an element from front of the queue 92 | */ 93 | void dequeue(struct Queue *Q) { 94 | struct ListNode *temp; 95 | if (Q->front == NULL) { 96 | printf("\nQueue is Empty \n"); 97 | return; 98 | } else { 99 | temp = Q->front; 100 | Q->front = Q->front->next; 101 | if(Q->front == NULL){ 102 | Q->rear = NULL; 103 | } 104 | printf("Removed Element : %d\n", temp->data); 105 | free(temp); 106 | } 107 | } 108 | 109 | /* 110 | Print's Queue 111 | */ 112 | void printQueue(struct Queue *Q) { 113 | struct ListNode *temp = Q->front; 114 | 115 | if ((Q->front == NULL) && (Q->rear == NULL)) { 116 | printf("Queue is Empty\n"); 117 | return; 118 | } 119 | 120 | while (temp != NULL) { 121 | printf("%d", temp->data); 122 | temp = temp->next; 123 | if(temp != NULL) 124 | printf("-->"); 125 | } 126 | } 127 | 128 | void deleteQueue(struct Queue *Q) { 129 | struct ListNode *temp; 130 | while(Q->front) { 131 | temp = Q->front; 132 | printf("Element being deleted: %d\n", temp->data); 133 | Q->front = Q->front->next; 134 | free(temp); 135 | } 136 | free(Q); 137 | } 138 | 139 | 140 | int main() { 141 | /* Initializing Queue */ 142 | struct Queue *Q; 143 | Q = CreateQueue(); 144 | /* Adding elements in Queue */ 145 | enqueue(Q, 1); 146 | enqueue(Q, 3); 147 | enqueue(Q, 7); 148 | enqueue(Q, 5); 149 | enqueue(Q, 10); 150 | /* Printing Queue */ 151 | printQueue(Q); 152 | /* Printing size of Queue */ 153 | printf("\nSize of Queue : %d\n", size(Q)); 154 | /* Printing front and rear element of Queue */ 155 | printf("Front Element : %d\n", frontElement(Q)); 156 | printf("Rear Element : %d\n", rearElement(Q)); 157 | /* Removing Element from Queue */ 158 | dequeue(Q); 159 | dequeue(Q); 160 | dequeue(Q); 161 | dequeue(Q); 162 | dequeue(Q); 163 | dequeue(Q); 164 | enqueue(Q, 15); 165 | enqueue(Q, 100); 166 | /* Printing Queue */ 167 | printQueue(Q); 168 | /* Printing size of Queue */ 169 | printf("\nSize of Queue : %d\n", size(Q)); 170 | /* Printing front and rear element of Queue */ 171 | printf("Front Element : %d\n", frontElement(Q)); 172 | printf("Rear Element : %d\n", rearElement(Q)); 173 | /* Removing Queue */ 174 | deleteQueue(Q); 175 | return 0; 176 | } 177 | -------------------------------------------------------------------------------- /src/Chapter_04_Queues/SimpleQueue.c: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2008 CareerMonk Publications and others. 2 | // #E-Mail : info@careermonk.com 3 | // Creation Date : 2008-01-10 06:15:46 4 | // Created by : Narasimha Karumanchi 5 | // Book Title : Data Structures And Algorithms Made Easy 6 | // Warranty : This software is provided "as is" without any 7 | // warranty; without even the implied warranty of 8 | // merchantability or fitness for a particular purpose. 9 | 10 | #include 11 | #include 12 | #include 13 | 14 | struct Queue { 15 | int front, rear; 16 | int capacity; 17 | int size; 18 | int *array; 19 | }; 20 | 21 | // Create an empty queue 22 | struct Queue *createQueue(int capacity) { 23 | struct Queue *Q = malloc(sizeof(struct Queue)); 24 | if(!Q) 25 | return NULL; 26 | Q->capacity = capacity; 27 | Q->front = Q->rear = -1; 28 | Q->size = 0; 29 | Q->array= malloc(Q->capacity * sizeof(int)); 30 | 31 | if(!Q->array) 32 | return NULL; 33 | return Q; 34 | } 35 | 36 | // Returns queue size 37 | int size(struct Queue *Q) { 38 | return Q->size; 39 | } 40 | 41 | // Returns Frnt Element of the Queue 42 | int frontElement(struct Queue *Q) { 43 | return Q->array[Q->front]; 44 | } 45 | 46 | // Returns the Rear Element of the Queue 47 | int rearElement(struct Queue *Q) { 48 | return Q->array[Q->rear]; 49 | } 50 | 51 | // Check's if Queue is empty or not 52 | int isEmpty(struct Queue *Q) { 53 | // if the condition is true then 1 is returned else 0 is returned 54 | return (Q->size == 0); 55 | } 56 | 57 | // Check's if Queue is full or not 58 | int isFull(struct Queue *Q) { 59 | // if the condition is true then 1 is returned else 0 is returned 60 | return (Q->size == Q->capacity); 61 | } 62 | 63 | // Adding elements in Queue 64 | void enqueue(struct Queue *Q, int data) { 65 | if(isFull(Q)) 66 | printf("Queue overflow\n"); 67 | else { 68 | Q->rear = (Q->rear+1) % Q->capacity; 69 | Q->array[Q->rear]= data; 70 | if(Q->front == -1) 71 | Q->front = Q->rear; 72 | Q->size += 1; 73 | } 74 | } 75 | 76 | // Removes an element from front of the queue 77 | int dequeue(struct Queue *Q) { 78 | int data = INT_MIN; //or element which does not exist in Queue 79 | if(isEmpty(Q)){ 80 | printf("Queue is empty\n"); 81 | return data; 82 | } 83 | data = Q->array[Q->front]; 84 | if(Q->front == Q->rear) { 85 | Q->front = Q->rear = -1; 86 | Q->size = 0; 87 | } else { 88 | Q->front = (Q->front+1) % Q->capacity; 89 | Q->size -= 1; 90 | } 91 | return data; 92 | } 93 | 94 | void deleteQueue(struct Queue *Q) { 95 | if(Q) { 96 | if(Q->array) 97 | free(Q->array); 98 | free(Q); 99 | } 100 | } 101 | 102 | int main() { 103 | // Initializing Queue 104 | struct Queue *Q; 105 | Q = createQueue(4); 106 | // Adding elements in Queue 107 | enqueue(Q, 1); 108 | enqueue(Q, 3); 109 | enqueue(Q, 7); 110 | enqueue(Q, 5); 111 | enqueue(Q, 10); 112 | 113 | // Printing size of Queue 114 | printf("\nSize of queue : %d\n", size(Q)); 115 | 116 | // Printing front and rear element of Queue */ 117 | printf("Front element : %d\n", frontElement(Q)); 118 | printf("Rear element : %d\n", rearElement(Q)); 119 | 120 | // Removing Element from Queue 121 | printf("\nDequeued element : %d\n", dequeue(Q)); 122 | printf("Dequeued element : %d\n", dequeue(Q)); 123 | printf("Dequeued element : %d\n", dequeue(Q)); 124 | printf("Dequeued element : %d\n", dequeue(Q)); 125 | printf("Dequeued element : %d\n", dequeue(Q)); 126 | printf("Dequeued element : %d\n", dequeue(Q)); 127 | enqueue(Q, 15); 128 | enqueue(Q, 100); 129 | 130 | // Printing size of Queue 131 | printf("\nSize of queue : %d\n", size(Q)); 132 | 133 | // Printing front and rear element of Queue 134 | printf("Front element : %d\n", frontElement(Q)); 135 | printf("Rear element : %d\n", rearElement(Q)); 136 | 137 | // Removing Queue 138 | deleteQueue(Q); 139 | return 0; 140 | } 141 | 142 | -------------------------------------------------------------------------------- /src/Chapter_04_Stacks/DynamicStack.c: -------------------------------------------------------------------------------- 1 | /*Copyright (c) 2016 CareerMonk Publications and others. 2 | #E-Mail : info@careermonk.com 3 | #Creation Date : 2008-01-10 06:15:46 4 | #Created by : Narasimha Karumanchi 5 | #Book Title : Data Structures And Algorithms Made Easy 6 | #Warranty : This software is provided "as is" without any 7 | # warranty; without even the implied warranty of 8 | # merchantability or fitness for a particular purpose.*/ 9 | 10 | #include 11 | #include 12 | #include 13 | 14 | struct Stack { 15 | int top; 16 | int capacity; 17 | int *array; 18 | }; 19 | 20 | struct Stack *createStack(int capacity) { 21 | struct Stack *S = malloc(sizeof(struct Stack)); 22 | if(!S) 23 | return NULL; 24 | S->capacity = capacity; 25 | S->top = -1; 26 | S->array= malloc(S->capacity * sizeof(int)); 27 | if(!S->array) 28 | return NULL; 29 | return S; 30 | } 31 | 32 | int isEmpty(struct Stack *S) { 33 | return (S->top == -1); // if the condition is true then 1 is returned else 0 is returned 34 | } 35 | 36 | int size(struct Stack *S) { 37 | return (S->top + 1); 38 | } 39 | 40 | int isFull(struct Stack *S){ 41 | //if the condition is true then 1 is returned else 0 is returned 42 | return (S->top == S->capacity - 1); 43 | } 44 | 45 | void doubleStack(struct Stack *S){ 46 | S->capacity *= 2; 47 | S->array = realloc(S->array, S->capacity * sizeof(int)); 48 | } 49 | 50 | 51 | void push(struct Stack *S, int data){ 52 | if(isFull(S)) 53 | doubleStack(S); 54 | S->array[++S->top] = data; 55 | } 56 | 57 | int pop(struct Stack *S){ 58 | /* S->top == - 1 indicates empty stack*/ 59 | if(isEmpty(S)){ 60 | printf("Stack is Empty\n"); 61 | return INT_MIN; 62 | } 63 | else /* Removing element from ‘top’ of the array and reducing ‘top’ by 1*/ 64 | return (S->array[S->top--]); 65 | } 66 | 67 | int peek(struct Stack *S){ 68 | /* S->top == - 1 indicates empty stack*/ 69 | if(isEmpty(S)){ 70 | printf("Stack is Empty"); 71 | return INT_MIN;; 72 | } 73 | else 74 | return (S->array[S->top]); 75 | } 76 | 77 | void deleteStack(struct Stack *S){ 78 | if(S) { 79 | if(S->array) 80 | free(S->array); 81 | free(S); 82 | } 83 | } 84 | 85 | 86 | int main(){ 87 | int i = 0, capacity = 5; 88 | // create a stack of capacity 5 89 | struct Stack *stk = createStack(capacity); 90 | 91 | for(i = 0; i <= 2 * capacity; i++){ 92 | push(stk, i); 93 | } 94 | 95 | printf("Top element is %d\n", peek(stk)); 96 | printf("Stack size is %d\n", size(stk)); 97 | 98 | for (i = 0; i <= capacity; i++){ 99 | printf("Popped element is %d\n", pop(stk)); 100 | } 101 | 102 | if (isEmpty(stk)) 103 | printf("Stack is empty"); 104 | else 105 | printf("Stack is not empty"); 106 | 107 | deleteStack(stk); 108 | return 0; 109 | } 110 | -------------------------------------------------------------------------------- /src/Chapter_04_Stacks/QueueWithTwoStacks.c: -------------------------------------------------------------------------------- 1 | /*Copyright (c) 2016 CareerMonk Publications and others. 2 | #E-Mail : info@careermonk.com 3 | #Creation Date : 2008-01-10 06:15:46 4 | #Created by : Narasimha Karumanchi 5 | #Book Title : Data Structures And Algorithms Made Easy 6 | #Warranty : This software is provided "as is" without any 7 | # warranty; without even the implied warranty of 8 | # merchantability or fitness for a particular purpose.*/ 9 | 10 | #include 11 | #include 12 | #include 13 | 14 | struct Stack { 15 | int top; 16 | int capacity; 17 | int *array; 18 | }; 19 | 20 | struct Stack *createStack(int capacity) { 21 | struct Stack *S = malloc(sizeof(struct Stack)); 22 | if(!S) 23 | return NULL; 24 | S->capacity = capacity; 25 | S->top = -1; 26 | S->array= malloc(S->capacity * sizeof(int)); 27 | if(!S->array) 28 | return NULL; 29 | return S; 30 | } 31 | 32 | int isEmpty(struct Stack *S) { 33 | return (S->top == -1); // if the condition is true then 1 is returned else 0 is returned 34 | } 35 | 36 | int size(struct Stack *S) { 37 | return (S->top + 1); 38 | } 39 | 40 | int isFull(struct Stack *S){ 41 | //if the condition is true then 1 is returned else 0 is returned 42 | return (S->top == S->capacity - 1); 43 | } 44 | 45 | void doubleStack(struct Stack *S){ 46 | S->capacity *= 2; 47 | S->array = realloc(S->array, S->capacity * sizeof(int)); 48 | } 49 | 50 | 51 | void push(struct Stack *S, int data){ 52 | if(isFull(S)) 53 | doubleStack(S); 54 | S->array[++S->top] = data; 55 | } 56 | 57 | int pop(struct Stack *S){ 58 | /* S->top == - 1 indicates empty stack*/ 59 | if(isEmpty(S)){ 60 | printf("Stack is Empty\n"); 61 | return INT_MIN; 62 | } 63 | else /* Removing element from ‘top’ of the array and reducing ‘top’ by 1*/ 64 | return (S->array[S->top--]); 65 | } 66 | 67 | int peek(struct Stack *S){ 68 | /* S->top == - 1 indicates empty stack*/ 69 | if(isEmpty(S)){ 70 | printf("Stack is Empty"); 71 | return INT_MIN;; 72 | } 73 | else 74 | return (S->array[S->top]); 75 | } 76 | 77 | void deleteStack(struct Stack *S){ 78 | if(S) { 79 | if(S->array) 80 | free(S->array); 81 | free(S); 82 | } 83 | } 84 | 85 | struct Queue { 86 | struct Stack *S1; // for enQueue 87 | struct Stack *S2; // for deQueue 88 | }; 89 | 90 | int queueSize(struct Queue *Q) { 91 | return size(Q->S1); 92 | } 93 | 94 | struct Queue *createQueue(int capacity) { 95 | struct Stack *S1 = createStack(capacity); 96 | struct Stack *S2 = createStack(capacity); 97 | struct Queue *Q = malloc(sizeof(struct Queue)); 98 | if(!Q) 99 | return NULL; 100 | Q->S1 = S1; 101 | Q->S2 = S2; 102 | return Q; 103 | } 104 | 105 | void enQueue(struct Queue *Q, int data) { 106 | push(Q->S1, data); 107 | } 108 | 109 | int deQueue(struct Queue *Q) { 110 | if(!isEmpty(Q->S2)) 111 | return pop(Q->S2); 112 | else { 113 | while( !isEmpty(Q->S1) ) 114 | push(Q->S2, pop(Q->S1)); 115 | return pop(Q->S2); 116 | } 117 | } 118 | 119 | void deleteQueue(struct Queue *Q){ 120 | if(Q) { 121 | if(Q->S1) 122 | free(Q->S1); 123 | if(Q->S2) 124 | free(Q->S2); 125 | free(Q); 126 | } 127 | } 128 | 129 | int main(){ 130 | // Initializing Queue 131 | struct Queue *Q; 132 | Q = createQueue(6); 133 | 134 | // Adding elements in Queue 135 | enQueue(Q, 1); 136 | enQueue(Q, 3); 137 | enQueue(Q, 7); 138 | enQueue(Q, 5); 139 | enQueue(Q, 10); 140 | enQueue(Q, 19); 141 | 142 | // Printing size of Queue 143 | printf("\nSize of queue : %d\n", queueSize(Q)); 144 | 145 | // Removing Element from Queue 146 | printf("\nDequeued element : %d\n", deQueue(Q)); 147 | printf("Dequeued element : %d\n", deQueue(Q)); 148 | printf("Dequeued element : %d\n", deQueue(Q)); 149 | printf("Dequeued element : %d\n", deQueue(Q)); 150 | printf("Dequeued element : %d\n", deQueue(Q)); 151 | printf("Dequeued element : %d\n", deQueue(Q)); 152 | 153 | // Removing Queue 154 | deleteQueue(Q); 155 | return 0; 156 | } 157 | -------------------------------------------------------------------------------- /src/Chapter_04_Stacks/SimpleArrayImplementationofStack.c: -------------------------------------------------------------------------------- 1 | /*Copyright (c) 2016 CareerMonk Publications and others. 2 | #E-Mail : info@careermonk.com 3 | #Creation Date : 2008-01-10 06:15:46 4 | #Created by : Narasimha Karumanchi 5 | #Book Title : Data Structures And Algorithms Made Easy 6 | #Warranty : This software is provided "as is" without any 7 | # warranty; without even the implied warranty of 8 | # merchantability or fitness for a particular purpose.*/ 9 | #include 10 | #include 11 | #include 12 | 13 | #define MAXSIZE 5 14 | 15 | struct SimpleArrayStack { 16 | int top; 17 | int capacity; 18 | int *array; 19 | }; 20 | 21 | struct SimpleArrayStack *CreateStack(){ 22 | struct SimpleArrayStack *S = malloc(sizeof(struct SimpleArrayStack)); 23 | if(!S) 24 | return NULL; 25 | S->capacity = MAXSIZE; 26 | S->top = -1; 27 | S->array = malloc(S->capacity * sizeof(int)); // allocate an array of size 1 initially 28 | 29 | if(!S->array) 30 | return NULL; 31 | return S; 32 | } 33 | 34 | int IsFullStack(struct SimpleArrayStack *S){ 35 | return (S->top == S->capacity-1); 36 | } 37 | 38 | void Push(struct SimpleArrayStack *S, int x){ 39 | // No overflow in this implementation 40 | if(IsFullStack(S)){ 41 | printf("Overflow: Stack full"); 42 | return; 43 | } 44 | S->array[++S->top] = x; 45 | } 46 | 47 | int IsEmptyStack(struct SimpleArrayStack *S){ 48 | return S->top == -1; 49 | } 50 | 51 | int Top(struct SimpleArrayStack *S){ 52 | if(IsEmptyStack(S)) 53 | return INT_MIN; 54 | 55 | return S->array[S->top]; 56 | } 57 | 58 | int Pop(struct SimpleArrayStack *S){ 59 | if(IsEmptyStack(S)){ 60 | printf("Underflow: Stack empty"); 61 | return INT_MIN; 62 | } 63 | return S->array[S->top--]; 64 | } 65 | 66 | void DeleteStack(struct SimpleArrayStack *S){ 67 | if(S) { 68 | if(S->array) 69 | free(S->array); 70 | free(S); 71 | } 72 | } 73 | 74 | void testSimpleArrayStack(){ 75 | struct SimpleArrayStack *s = CreateStack(); 76 | Push(s, 10); 77 | Push(s, 1); 78 | Push(s, 11); 79 | Push(s, 2); 80 | Push(s, 10); 81 | Push(s, 50); 82 | while(!IsEmptyStack(s)){ 83 | printf("%d\n", Pop(s)); 84 | } 85 | DeleteStack(s); 86 | } 87 | -------------------------------------------------------------------------------- /src/Chapter_04_Stacks/StackWithLinkedLists.c: -------------------------------------------------------------------------------- 1 | /*Copyright (c) 2016 CareerMonk Publications and others. 2 | #E-Mail : info@careermonk.com 3 | #Creation Date : 2008-01-10 06:15:46 4 | #Created by : Narasimha Karumanchi 5 | #Book Title : Data Structures And Algorithms Made Easy 6 | #Warranty : This software is provided "as is" without any 7 | # warranty; without even the implied warranty of 8 | # merchantability or fitness for a particular purpose.*/ 9 | 10 | #include 11 | #include 12 | #include 13 | 14 | struct ListNode{ 15 | int data; 16 | struct ListNode *next; 17 | }; 18 | 19 | struct Stack{ 20 | struct ListNode *top; 21 | }; 22 | 23 | struct Stack *createStack(){ 24 | struct Stack *stk; 25 | stk = malloc(sizeof(struct Stack)); 26 | stk->top = NULL; 27 | return stk; 28 | } 29 | 30 | void push(struct Stack *stk, int data){ 31 | struct ListNode *temp; 32 | temp = malloc(sizeof(struct ListNode)); 33 | if(!temp){ 34 | printf("\nStack/Heap overflow"); 35 | return; 36 | } 37 | temp->data = data; 38 | temp->next = stk->top; 39 | stk->top = temp; 40 | } 41 | 42 | int size(struct Stack *stk){ 43 | // we can improve the size function by adding extra size variable in stack structure 44 | // and update it while push/pop operations 45 | int count = 0; 46 | struct ListNode *temp; 47 | if(isEmpty(stk)) 48 | return 0; 49 | temp = stk->top; 50 | while (temp){ 51 | count++; 52 | temp = temp->next; 53 | } 54 | return count; 55 | } 56 | 57 | int isEmpty(struct Stack *stk){ 58 | return stk->top == NULL; 59 | } 60 | 61 | int pop(struct Stack *stk){ 62 | int data; 63 | struct ListNode *temp; 64 | if(isEmpty(stk)) 65 | return INT_MIN; 66 | temp = stk->top; 67 | stk->top = stk->top->next; 68 | data = temp->data; 69 | free(temp); 70 | return data; 71 | } 72 | 73 | int peek(struct Stack * stk){ 74 | if(isEmpty(stk)) 75 | return INT_MIN; 76 | return stk->top->data; 77 | } 78 | 79 | void deleteStack(struct Stack *stk){ 80 | struct ListNode *temp, *p; 81 | p = stk->top; 82 | while( p) { 83 | temp = p->next; 84 | free(p); 85 | p = temp; 86 | } 87 | free(stk); 88 | } 89 | int main(){ 90 | int i = 0; 91 | struct Stack *stk = createStack(); 92 | 93 | for(i = 0; i <= 10; i++){ 94 | push(stk, i); 95 | } 96 | 97 | printf("Top element is %d\n", peek(stk)); 98 | printf("Stack size is %d\n", size(stk)); 99 | 100 | for (i = 0; i <= 10; i++){ 101 | printf("Popped element is %d\n", pop(stk)); 102 | } 103 | 104 | if (isEmpty(stk)) 105 | printf("Stack is empty"); 106 | else 107 | printf("Stack is not empty"); 108 | 109 | deleteStack(stk); 110 | return 0; 111 | } 112 | -------------------------------------------------------------------------------- /src/Chapter_04_Stacks/TwoStacksInOneArray.c: -------------------------------------------------------------------------------- 1 | /*Copyright (c) 2016 CareerMonk Publications and others. 2 | #E-Mail : info@careermonk.com 3 | #Creation Date : 2008-01-10 06:15:46 4 | #Created by : Narasimha Karumanchi 5 | #Book Title : Data Structures And Algorithms Made Easy 6 | #Warranty : This software is provided "as is" without any 7 | # warranty; without even the implied warranty of 8 | # merchantability or fitness for a particular purpose.*/ 9 | 10 | #include 11 | #include 12 | #include 13 | #include 14 | 15 | struct MultiStacks { 16 | int top1, top2; 17 | int capacity; 18 | char *array; 19 | }; 20 | 21 | struct MultiStacks *createStack(int capacity) { 22 | struct MultiStacks *twoStacks = malloc(sizeof(struct MultiStacks)); 23 | if(!twoStacks) 24 | return NULL; 25 | twoStacks->capacity = capacity; 26 | twoStacks->top1 = -1; 27 | twoStacks->top2 = capacity; 28 | twoStacks->array= malloc(twoStacks->capacity * sizeof(int)); 29 | if(!twoStacks->array) 30 | return NULL; 31 | return twoStacks; 32 | } 33 | 34 | int isEmpty(struct MultiStacks *twoStacks, int stackNumber) { 35 | if (stackNumber == 1){ 36 | return (twoStacks->top1 == -1); 37 | } else { 38 | return (twoStacks->top2 == twoStacks->capacity); 39 | } 40 | } 41 | 42 | int size(struct MultiStacks *twoStacks, int stackNumber) { 43 | if (stackNumber == 1){ 44 | return (twoStacks->top1 + 1); 45 | } else { 46 | return (twoStacks->capacity - twoStacks->top2); 47 | } 48 | } 49 | 50 | int isFull(struct MultiStacks *twoStacks){ 51 | return (size(twoStacks, 1) + size(twoStacks, 2) == twoStacks->capacity); 52 | } 53 | 54 | void push(struct MultiStacks *twoStacks, int stackNumber, char data){ 55 | if(isFull(twoStacks)){ 56 | printf("Stack overflow\n"); 57 | return; 58 | } 59 | if (stackNumber == 1){ 60 | twoStacks->array[++twoStacks->top1] = data; 61 | } else { 62 | twoStacks->array[--twoStacks->top2] = data; 63 | } 64 | } 65 | 66 | char pop(struct MultiStacks *twoStacks, int stackNumber){ 67 | /* twoStacks->top == - 1 indicates empty stack*/ 68 | if(isEmpty(twoStacks, stackNumber)){ 69 | printf("Stack is Empty\n"); 70 | return '\0'; 71 | } 72 | if (stackNumber == 1){ 73 | return (twoStacks->array[twoStacks->top1--]); 74 | } else { 75 | return (twoStacks->array[twoStacks->top2++]); 76 | } 77 | } 78 | 79 | int peek(struct MultiStacks *twoStacks, int stackNumber){ 80 | if(isEmpty(twoStacks, stackNumber)){ 81 | printf("Stack is Empty"); 82 | return INT_MIN;; 83 | } 84 | if (stackNumber == 1){ 85 | return (twoStacks->array[twoStacks->top1]); 86 | } else { 87 | return (twoStacks->array[twoStacks->top2]); 88 | } 89 | } 90 | 91 | void deleteStack(struct MultiStacks *twoStacks){ 92 | if(twoStacks) { 93 | if(twoStacks->array) 94 | free(twoStacks->array); 95 | free(twoStacks); 96 | } 97 | } 98 | 99 | int main(void){ 100 | int i = 0, capacity = 15; 101 | // create a stack of capacity 15 102 | struct MultiStacks *stk = createStack(capacity); 103 | 104 | for(i = 0; i <= capacity; i++){ 105 | printf("Pushing %d to %d\n", i, i%2+1); 106 | push(stk, i%2+1, i); 107 | } 108 | printf("Top element in first stack is %d\n", peek(stk, 1)); 109 | printf("Top element in second stack is %d\n", peek(stk, 2)); 110 | printf("Size of first stack is %d\n", size(stk,1)); 111 | printf("Size of second stack is %d\n", size(stk,2)); 112 | 113 | for (i = 0; i <= capacity; i++){ 114 | printf("Popped element from stack %d is %d\n", i%2+1, pop(stk, i%2+1)); 115 | } 116 | deleteStack(stk); 117 | return 0; 118 | } 119 | 120 | -------------------------------------------------------------------------------- /src/Chapter_04_Stacks/balanced parenthesis using stack: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #define size 100 5 | 6 | struct node 7 | { 8 | char data; 9 | struct node* link; 10 | }; 11 | int c=0; 12 | struct node * head; 13 | 14 | void push(char x) 15 | { 16 | struct node*p,*temp; 17 | temp=(struct node*)malloc(sizeof(struct node)); 18 | temp->data=x; 19 | if(head==NULL) 20 | { 21 | head=temp; 22 | p=head; 23 | p->link=NULL; 24 | c++; 25 | } 26 | else 27 | { 28 | temp->link=p; 29 | p=temp; 30 | head=p; 31 | c++; 32 | } 33 | 34 | } 35 | char pop(void) 36 | { 37 | char x; 38 | struct node*p=head; 39 | x=p->data; 40 | head=p->link; 41 | free(p); 42 | c--; 43 | return x; 44 | 45 | } 46 | 47 | int isBalanced(char *s) { //{[()]} 48 | int i=0;char x; 49 | while(s[i]!='\0') 50 | { 51 | if(s[i]=='{'||s[i]=='('||s[i]=='[') 52 | push(s[i]); 53 | else 54 | { 55 | if(c<=0) 56 | return 0; 57 | 58 | 59 | x=pop(); 60 | if( x=='{'&&s[i]!='}') 61 | return 0; 62 | if(x=='['&&s[i]!=']') 63 | return 0; 64 | if(x=='('&&s[i]!=')') 65 | return 0 ; 66 | }i++; 67 | } 68 | if(c==0) 69 | return 1; 70 | else 71 | return 0; 72 | } 73 | 74 | int main() { 75 | int t; 76 | scanf("%d",&t); 77 | for(int a0 = 0; a0 < t; a0++){ 78 | char s[size]; 79 | int result; 80 | scanf("%s",s); 81 | result = isBalanced(s); 82 | if(result==1) 83 | printf("\nYES"); 84 | else 85 | printf("\nNO"); 86 | 87 | } 88 | return 0; 89 | } 90 | -------------------------------------------------------------------------------- /src/Chapter_04_Stacks/find_spans.c: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2008 CareerMonk Publications and others. 2 | // #E-Mail : info@careermonk.com 3 | // Creation Date : 2008-01-10 06:15:46 4 | // Created by : Narasimha Karumanchi 5 | // Book Title : Data Structures And Algorithms Made Easy 6 | // Warranty : This software is provided "as is" without any 7 | // warranty; without even the implied warranty of 8 | // merchantability or fitness for a particular purpose. 9 | 10 | #include 11 | #include 12 | 13 | #define MAX_N 100000 14 | 15 | int stack[MAX_N], top = -1; 16 | 17 | int largest_rectangle_area(int heights[], int n) { 18 | int max_area = 0, i = 0; 19 | while (i < n) { 20 | if (top == -1 || heights[i] >= heights[stack[top]]) { 21 | stack[++top] = i++; 22 | } else { 23 | int top_index = stack[top--]; 24 | int area = heights[top_index] * (top == -1 ? i : i - stack[top] - 1); 25 | if (area > max_area) { 26 | max_area = area; 27 | } 28 | } 29 | } 30 | while (top != -1) { 31 | int top_index = stack[top--]; 32 | int area = heights[top_index] * (top == -1 ? i : i - stack[top] - 1); 33 | if (area > max_area) { 34 | max_area = area; 35 | } 36 | } 37 | return max_area; 38 | } 39 | 40 | int main() { 41 | int n, heights[MAX_N]; 42 | printf("Enter the number of bars in the histogram: "); 43 | scanf("%d", &n); 44 | printf("Enter the heights of the bars:\n"); 45 | for (int i = 0; i < n; i++) { 46 | scanf("%d", &heights[i]); 47 | } 48 | int max_area = largest_rectangle_area(heights, n); 49 | printf("The largest rectangle under the histogram has area %d\n", max_area); 50 | return 0; 51 | } 52 | -------------------------------------------------------------------------------- /src/Chapter_04_Stacks/findingSpan.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Author : Shivam Chauhan 3 | Date : Feb 28 , 2019 4 | Finding the Span 5 | */ 6 | 7 | #include 8 | using namespace std; 9 | void getSpan( int span[] , int n ) 10 | { 11 | stacks; 12 | int calculatedSpan[n] , price ; 13 | for ( int i = 0 ; i < n ; i++ ) 14 | { 15 | while( !s.empty() && span[s.top()] <= span[i] ) 16 | { 17 | s.pop(); 18 | } 19 | calculatedSpan[i] = i - ( s.empty() ? -1 : s.top() ) ; 20 | s.push(i); 21 | } 22 | for( int i = 0 ; i < n ; i++ ) 23 | { 24 | cout << calculatedSpan[i] << " "; 25 | } 26 | cout << endl ; 27 | } 28 | int main() 29 | { 30 | int n ; 31 | cin >> n ; 32 | int span[n]; 33 | for ( int i = 0 ; i < n ; i++ ) 34 | { 35 | cin >> span[i]; 36 | } 37 | getSpan(span,n); 38 | return 0 ; 39 | } -------------------------------------------------------------------------------- /src/Chapter_04_Stacks/getMinimum.c: -------------------------------------------------------------------------------- 1 | /*Copyright (c) 2016 CareerMonk Publications and others. 2 | #E-Mail : info@careermonk.com 3 | #Creation Date : 2008-01-10 06:15:46 4 | #Created by : Narasimha Karumanchi 5 | #Book Title : Data Structures And Algorithms Made Easy 6 | #Warranty : This software is provided "as is" without any 7 | # warranty; without even the implied warranty of 8 | # merchantability or fitness for a particular purpose.*/ 9 | 10 | #include 11 | #include 12 | #include 13 | 14 | struct Stack { 15 | int top; 16 | int capacity; 17 | int *array; 18 | }; 19 | 20 | struct Stack *createStack(int capacity) { 21 | struct Stack *S = malloc(sizeof(struct Stack)); 22 | if(!S) 23 | return NULL; 24 | S->capacity = capacity; 25 | S->top = -1; 26 | S->array= malloc(S->capacity * sizeof(int)); 27 | if(!S->array) 28 | return NULL; 29 | return S; 30 | } 31 | 32 | int isEmpty(struct Stack *S) { 33 | return (S->top == -1); // if the condition is true then 1 is returned else 0 is returned 34 | } 35 | 36 | int size(struct Stack *S) { 37 | return (S->top + 1); 38 | } 39 | 40 | int isFull(struct Stack *S){ 41 | //if the condition is true then 1 is returned else 0 is returned 42 | return (S->top == S->capacity - 1); 43 | } 44 | 45 | void doubleStack(struct Stack *S){ 46 | S->capacity *= 2; 47 | S->array = realloc(S->array, S->capacity * sizeof(int)); 48 | } 49 | 50 | 51 | void push(struct Stack *S, int data){ 52 | if(isFull(S)) 53 | doubleStack(S); 54 | S->array[++S->top] = data; 55 | } 56 | 57 | int pop(struct Stack *S){ 58 | /* S->top == - 1 indicates empty stack*/ 59 | if(isEmpty(S)){ 60 | printf("Stack is Empty\n"); 61 | return INT_MIN; 62 | } 63 | else /* Removing element from ‘top’ of the array and reducing ‘top’ by 1*/ 64 | return (S->array[S->top--]); 65 | } 66 | 67 | int peek(struct Stack *S){ 68 | /* S->top == - 1 indicates empty stack*/ 69 | if(isEmpty(S)){ 70 | printf("Stack is Empty"); 71 | return INT_MIN;; 72 | } 73 | else 74 | return (S->array[S->top]); 75 | } 76 | 77 | void deleteStack(struct Stack *S){ 78 | if(S) { 79 | if(S->array) 80 | free(S->array); 81 | free(S); 82 | } 83 | } 84 | struct AdvancedStack { 85 | struct Stack *elementStack; 86 | struct Stack *minStack; 87 | }; 88 | 89 | 90 | int isEmptyA(struct AdvancedStack *S) { 91 | return (S->elementStack->top == -1); // if the condition is true then 1 is returned else 0 is returned 92 | } 93 | 94 | int sizeA(struct AdvancedStack *S) { 95 | return (S->elementStack->top + 1); 96 | } 97 | 98 | int isFullA(struct AdvancedStack *S){ 99 | //if the condition is true then 1 is returned else 0 is returned 100 | return (S->elementStack->top == S->elementStack->capacity - 1); 101 | } 102 | 103 | void pushA(struct AdvancedStack *S, int data){ 104 | push(S->elementStack, data); 105 | 106 | if(isEmpty(S->minStack) || peek(S->minStack) >= data) 107 | push (S->minStack, data); 108 | } 109 | 110 | int popA(struct AdvancedStack *S ){ 111 | int temp; 112 | 113 | if(isEmpty(S->elementStack)) 114 | return INT_MIN; 115 | 116 | temp = peek(S->elementStack); 117 | 118 | if(peek(S->minStack) == pop(S->elementStack)) 119 | pop (S->minStack); 120 | return temp; 121 | } 122 | 123 | int peekA(struct AdvancedStack *S ){ 124 | return peek(S->elementStack); 125 | } 126 | 127 | int getMinimum(struct AdvancedStack *S){ 128 | return peek(S->minStack); 129 | } 130 | 131 | struct AdvancedStack * createAdvancedStack(int capacity){ 132 | struct AdvancedStack *S = malloc (sizeof (struct AdvancedStack)); 133 | 134 | if(!S) 135 | return NULL; 136 | 137 | S->elementStack = createStack(capacity); 138 | S->minStack = createStack(capacity); 139 | return S; 140 | } 141 | 142 | void deleteStackA(struct AdvancedStack *S){ 143 | if(S) { 144 | deleteStackA(S->elementStack); 145 | deleteStackA(S->minStack); 146 | free(S); 147 | } 148 | } 149 | 150 | int main(){ 151 | int i = 0, capacity = 5; 152 | // create a stack of capacity 5 153 | struct AdvancedStack *stk = createAdvancedStack(capacity); 154 | 155 | for(i = 0; i <= 2 * capacity; i++){ 156 | pushA(stk, i); 157 | } 158 | 159 | printf("Top element is %d\n", peekA(stk)); 160 | printf("Stack size is %d\n", sizeA(stk)); 161 | 162 | for (i = 0; i <= capacity; i++){ 163 | printf("Popped element is %d\n", popA(stk)); 164 | } 165 | 166 | if (isEmptyA(stk)) 167 | printf("Stack is empty"); 168 | else 169 | printf("Stack is not empty"); 170 | 171 | deleteStackA(stk); 172 | return 0; 173 | } 174 | -------------------------------------------------------------------------------- /src/Chapter_04_Stacks/getMinimums.c: -------------------------------------------------------------------------------- 1 | /*Copyright (c) 2016 CareerMonk Publications and others. 2 | #E-Mail : info@careermonk.com 3 | #Creation Date : 2008-01-10 06:15:46 4 | #Created by : Narasimha Karumanchi 5 | #Book Title : Data Structures And Algorithms Made Easy 6 | #Warranty : This software is provided "as is" without any 7 | # warranty; without even the implied warranty of 8 | # merchantability or fitness for a particular purpose.*/ 9 | 10 | #include 11 | #include 12 | #include 13 | 14 | struct Stack { 15 | int top; 16 | int capacity; 17 | int *array; 18 | }; 19 | 20 | struct Stack *createStack(int capacity) { 21 | struct Stack *S = malloc(sizeof(struct Stack)); 22 | if(!S) 23 | return NULL; 24 | S->capacity = capacity; 25 | S->top = -1; 26 | S->array= malloc(S->capacity * sizeof(int)); 27 | if(!S->array) 28 | return NULL; 29 | return S; 30 | } 31 | 32 | int isEmpty(struct Stack *S) { 33 | return (S->top == -1); // if the condition is true then 1 is returned else 0 is returned 34 | } 35 | 36 | int size(struct Stack *S) { 37 | return (S->top + 1); 38 | } 39 | 40 | int isFull(struct Stack *S){ 41 | //if the condition is true then 1 is returned else 0 is returned 42 | return (S->top == S->capacity - 1); 43 | } 44 | 45 | void doubleStack(struct Stack *S){ 46 | S->capacity *= 2; 47 | S->array = realloc(S->array, S->capacity * sizeof(int)); 48 | } 49 | 50 | 51 | void push(struct Stack *S, int data){ 52 | if(isFull(S)) 53 | doubleStack(S); 54 | S->array[++S->top] = data; 55 | } 56 | 57 | int pop(struct Stack *S){ 58 | /* S->top == - 1 indicates empty stack*/ 59 | if(isEmpty(S)){ 60 | printf("Stack is Empty\n"); 61 | return INT_MIN; 62 | } 63 | else /* Removing element from ‘top’ of the array and reducing ‘top’ by 1*/ 64 | return (S->array[S->top--]); 65 | } 66 | 67 | int peek(struct Stack *S){ 68 | /* S->top == - 1 indicates empty stack*/ 69 | if(isEmpty(S)){ 70 | printf("Stack is Empty"); 71 | return INT_MIN;; 72 | } 73 | else 74 | return (S->array[S->top]); 75 | } 76 | 77 | void deleteStack(struct Stack *S){ 78 | if(S) { 79 | if(S->array) 80 | free(S->array); 81 | free(S); 82 | } 83 | } 84 | struct AdvancedStack { 85 | struct Stack *elementStack; 86 | struct Stack *minStack; 87 | }; 88 | 89 | 90 | int isEmptyA(struct AdvancedStack *S) { 91 | return (S->elementStack->top == -1); // if the condition is true then 1 is returned else 0 is returned 92 | } 93 | 94 | int sizeA(struct AdvancedStack *S) { 95 | return (S->elementStack->top + 1); 96 | } 97 | 98 | int isFullA(struct AdvancedStack *S){ 99 | //if the condition is true then 1 is returned else 0 is returned 100 | return (S->elementStack->top == S->elementStack->capacity - 1); 101 | } 102 | 103 | void pushA(struct AdvancedStack *S, int data){ 104 | push(S->elementStack, data); 105 | 106 | if(isEmpty(S->minStack) || peek(S->minStack) >= data) 107 | push(S->minStack, data); 108 | 109 | } 110 | 111 | int popA(struct AdvancedStack *S ){ 112 | int temp; 113 | if(isEmpty(S->elementStack)) 114 | return -1; 115 | 116 | temp = peek(S->elementStack); 117 | if(peek(S->minStack) == pop(S->elementStack)) 118 | pop(S->minStack); 119 | return temp; 120 | } 121 | 122 | int peekA(struct AdvancedStack *S ){ 123 | return peek(S->elementStack); 124 | } 125 | 126 | int getMinimum(struct AdvancedStack *S){ 127 | return peek(S->minStack); 128 | } 129 | 130 | struct AdvancedStack * createAdvancedStack(int capacity){ 131 | struct AdvancedStack *S = malloc (sizeof (struct AdvancedStack)); 132 | 133 | if(!S) 134 | return NULL; 135 | 136 | S->elementStack = createStack(capacity); 137 | S->minStack = createStack(capacity); 138 | return S; 139 | } 140 | 141 | void deleteStackA(struct AdvancedStack *S){ 142 | if(S) { 143 | deleteStackA(S->elementStack); 144 | deleteStackA(S->minStack); 145 | free(S); 146 | } 147 | } 148 | 149 | int main(){ 150 | int i = 0, capacity = 5; 151 | // create a stack of capacity 5 152 | struct AdvancedStack *stk = createAdvancedStack(capacity); 153 | 154 | for(i = 0; i <= 2 * capacity; i++){ 155 | pushA(stk, (7*i)%4); 156 | } 157 | 158 | printf("Top element is %d\n", peekA(stk)); 159 | printf("Stack size is %d\n", sizeA(stk)); 160 | 161 | for (i = 0; i <= capacity; i++){ 162 | printf("Popped element is %d\n", popA(stk)); 163 | printf("Minimum element is %d\n", getMinimum(stk)); 164 | } 165 | 166 | if (isEmptyA(stk)) 167 | printf("Stack is empty"); 168 | else 169 | printf("Stack is not empty"); 170 | 171 | deleteStackA(stk); 172 | return 0; 173 | } 174 | -------------------------------------------------------------------------------- /src/Chapter_04_Stacks/infixToPostfix.c: -------------------------------------------------------------------------------- 1 | /*Copyright (c) 2016 CareerMonk Publications and others. 2 | #E-Mail : info@careermonk.com 3 | #Creation Date : 2008-01-10 06:15:46 4 | #Created by : Narasimha Karumanchi 5 | #Book Title : Data Structures And Algorithms Made Easy 6 | #Warranty : This software is provided "as is" without any 7 | # warranty; without even the implied warranty of 8 | # merchantability or fitness for a particular purpose.*/ 9 | 10 | #include 11 | #include 12 | #include 13 | 14 | struct Stack { 15 | int top; 16 | int capacity; 17 | int *array; 18 | }; 19 | 20 | struct Stack *createStack(int capacity) { 21 | struct Stack *S = malloc(sizeof(struct Stack)); 22 | if(!S) 23 | return NULL; 24 | S->capacity = capacity; 25 | S->top = -1; 26 | S->array= malloc(S->capacity * sizeof(int)); 27 | if(!S->array) 28 | return NULL; 29 | return S; 30 | } 31 | 32 | int isEmpty(struct Stack *S) { 33 | return (S->top == -1); // if the condition is true then 1 is returned else 0 is returned 34 | } 35 | 36 | int size(struct Stack *S) { 37 | return (S->top + 1); 38 | } 39 | 40 | int isFull(struct Stack *S){ 41 | //if the condition is true then 1 is returned else 0 is returned 42 | return (S->top == S->capacity - 1); 43 | } 44 | 45 | void doubleStack(struct Stack *S){ 46 | S->capacity *= 2; 47 | S->array = realloc(S->array, S->capacity * sizeof(int)); 48 | } 49 | 50 | 51 | void push(struct Stack *S, int data){ 52 | if(isFull(S)) 53 | doubleStack(S); 54 | S->array[++S->top] = data; 55 | } 56 | 57 | int pop(struct Stack *S){ 58 | /* S->top == - 1 indicates empty stack*/ 59 | if(isEmpty(S)){ 60 | printf("Stack is Empty\n"); 61 | return INT_MIN; 62 | } 63 | else /* Removing element from ‘top’ of the array and reducing ‘top’ by 1*/ 64 | return (S->array[S->top--]); 65 | } 66 | 67 | int peek(struct Stack *S){ 68 | /* S->top == - 1 indicates empty stack*/ 69 | if(isEmpty(S)){ 70 | printf("Stack is Empty"); 71 | return INT_MIN;; 72 | } 73 | else 74 | return (S->array[S->top]); 75 | } 76 | 77 | void deleteStack(struct Stack *S){ 78 | if(S) { 79 | if(S->array) 80 | free(S->array); 81 | free(S); 82 | } 83 | } 84 | struct AdvancedStack { 85 | struct Stack *elementStack; 86 | struct Stack *minStack; 87 | }; 88 | 89 | 90 | int isEmptyA(struct AdvancedStack *S) { 91 | return (S->elementStack->top == -1); // if the condition is true then 1 is returned else 0 is returned 92 | } 93 | 94 | int sizeA(struct AdvancedStack *S) { 95 | return (S->elementStack->top + 1); 96 | } 97 | 98 | int isFullA(struct AdvancedStack *S){ 99 | //if the condition is true then 1 is returned else 0 is returned 100 | return (S->elementStack->top == S->elementStack->capacity - 1); 101 | } 102 | 103 | void pushA(struct AdvancedStack *S, int data){ 104 | push(S->elementStack, data); 105 | 106 | if(isEmpty(S->minStack) || peek(S->minStack) >= data) 107 | push (S->minStack, data); 108 | else push (S->minStack, peek(S->minStack)); 109 | } 110 | 111 | int popA(struct AdvancedStack *S ){ 112 | int temp; 113 | 114 | if(isEmpty(S->elementStack)) 115 | return INT_MIN; 116 | 117 | temp = peek(S->elementStack); 118 | 119 | if(peek(S->minStack) == pop(S->elementStack)) 120 | pop (S->minStack); 121 | return temp; 122 | } 123 | 124 | int peekA(struct AdvancedStack *S ){ 125 | return peek(S->elementStack); 126 | } 127 | 128 | int getMinimum(struct AdvancedStack *S){ 129 | return peek(S->minStack); 130 | } 131 | 132 | struct AdvancedStack * createAdvancedStack(int capacity){ 133 | struct AdvancedStack *S = malloc (sizeof (struct AdvancedStack)); 134 | 135 | if(!S) 136 | return NULL; 137 | 138 | S->elementStack = createStack(capacity); 139 | S->minStack = createStack(capacity); 140 | return S; 141 | } 142 | 143 | int main(){ 144 | int i = 0, capacity = 5; 145 | // create a stack of capacity 5 146 | struct AdvancedStack *stk = createAdvancedStack(capacity); 147 | 148 | for(i = 0; i <= 2 * capacity; i++){ 149 | pushA(stk, (7*i)%4); 150 | } 151 | 152 | printf("Top element is %d\n", peekA(stk)); 153 | printf("Stack size is %d\n", sizeA(stk)); 154 | 155 | for (i = 0; i <= capacity; i++){ 156 | printf("Popped element is %d\n", popA(stk)); 157 | printf("Minimum element is %d\n", getMinimum(stk)); 158 | } 159 | 160 | if (isEmptyA(stk)) 161 | printf("Stack is empty"); 162 | else 163 | printf("Stack is not empty"); 164 | 165 | deleteStack(stk); 166 | return 0; 167 | } 168 | -------------------------------------------------------------------------------- /src/Chapter_04_Stacks/infixToPostfix.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Author : Shivam Chauhan 3 | Date : Feb 27 , 2019 4 | Infix to Postfix Implementation 5 | */ 6 | #include 7 | using namespace std ; 8 | int getPriority(char ch ) 9 | { 10 | switch(ch) 11 | { 12 | case '+' : 13 | case '-' : return 1; 14 | break; 15 | case '*' : 16 | case '/' : return 2; 17 | break; 18 | 19 | case '^' : return 3; 20 | break; 21 | 22 | default : return 0 ; 23 | break ; 24 | 25 | } 26 | } 27 | string infix_to_postfix(string str ) 28 | { 29 | stacks; 30 | string result = ""; 31 | for ( auto c : str) 32 | { 33 | if( ( c >= 'a' && c <= 'z' ) || (c >= 'A' && c <= 'Z') ) 34 | { 35 | result += c ; 36 | } 37 | else if ( c == ')') 38 | { 39 | while ( !s.empty() && s.top() != '(' ) 40 | { 41 | result += s.top(); 42 | s.pop(); 43 | } 44 | if( !s.empty() && s.top() == '(' ) s.pop() ; 45 | } 46 | else 47 | { 48 | while( !s.empty() && getPriority(s.top()) >= getPriority(c) && c != '(') 49 | { 50 | result += s.top(); 51 | s.pop(); 52 | } 53 | s.push(c); 54 | } 55 | } 56 | while(!s.empty()) 57 | { 58 | result += s.top(); 59 | s.pop(); 60 | } 61 | return result ; 62 | } 63 | 64 | int main() 65 | { 66 | string str = "(A+B)/(C+D)"; 67 | cout << infix_to_postfix(str) << endl ; 68 | return 0 ; 69 | } -------------------------------------------------------------------------------- /src/Chapter_04_Stacks/isPalindrome.c: -------------------------------------------------------------------------------- 1 | /*Copyright (c) 2016 CareerMonk Publications and others. 2 | #E-Mail : info@careermonk.com 3 | #Creation Date : 2008-01-10 06:15:46 4 | #Created by : Narasimha Karumanchi 5 | #Book Title : Data Structures And Algorithms Made Easy 6 | #Warranty : This software is provided "as is" without any 7 | # warranty; without even the implied warranty of 8 | # merchantability or fitness for a particular purpose.*/ 9 | #include 10 | #include 11 | 12 | int isPalindrome(char str[]){ 13 | //the first index 14 | int i = 0; 15 | //the last index 16 | int j = strlen(str)-1; 17 | 18 | while(i < j && str[i] == str[j]){ 19 | //increment start index and decrement last index 20 | i++; 21 | j--; 22 | } 23 | 24 | if(i < j){ 25 | //did not reach the center 26 | printf("Not a palindrome\n"); 27 | return 0; 28 | } 29 | else{ 30 | //reached the center 31 | printf("Palindrome\n"); 32 | return 1; 33 | } 34 | } 35 | 36 | int main(void){ 37 | isPalindrome("ababaXababa"); 38 | isPalindrome("ababababXbababbbbabba"); 39 | return 0; 40 | } 41 | -------------------------------------------------------------------------------- /src/Chapter_04_Stacks/isPalindrome2.c: -------------------------------------------------------------------------------- 1 | /*Copyright (c) 2016 CareerMonk Publications and others. 2 | #E-Mail : info@careermonk.com 3 | #Creation Date : 2008-01-10 06:15:46 4 | #Created by : Narasimha Karumanchi 5 | #Book Title : Data Structures And Algorithms Made Easy 6 | #Warranty : This software is provided "as is" without any 7 | # warranty; without even the implied warranty of 8 | # merchantability or fitness for a particular purpose.*/ 9 | 10 | #include 11 | #include 12 | #include 13 | #include 14 | 15 | struct Stack { 16 | int top; 17 | int capacity; 18 | char *array; 19 | }; 20 | 21 | struct Stack *createStack(int capacity) { 22 | struct Stack *S = malloc(sizeof(struct Stack)); 23 | if(!S) 24 | return NULL; 25 | S->capacity = capacity; 26 | S->top = -1; 27 | S->array= malloc(S->capacity * sizeof(int)); 28 | if(!S->array) 29 | return NULL; 30 | return S; 31 | } 32 | 33 | int isEmpty(struct Stack *S) { 34 | return (S->top == -1); // if the condition is true then 1 is returned else 0 is returned 35 | } 36 | 37 | int size(struct Stack *S) { 38 | return (S->top + 1); 39 | } 40 | 41 | int isFull(struct Stack *S){ 42 | //if the condition is true then 1 is returned else 0 is returned 43 | return (S->top == S->capacity - 1); 44 | } 45 | 46 | void doubleStack(struct Stack *S){ 47 | S->capacity *= 2; 48 | S->array = realloc(S->array, S->capacity * sizeof(int)); 49 | } 50 | 51 | 52 | void push(struct Stack *S, char data){ 53 | if(isFull(S)) 54 | doubleStack(S); 55 | S->array[++S->top] = data; 56 | } 57 | 58 | char pop(struct Stack *S){ 59 | /* S->top == - 1 indicates empty stack*/ 60 | if(isEmpty(S)){ 61 | printf("Stack is Empty\n"); 62 | return '\0'; 63 | } 64 | else /* Removing element from ‘top’ of the array and reducing ‘top’ by 1*/ 65 | return (S->array[S->top--]); 66 | } 67 | 68 | int peek(struct Stack *S){ 69 | /* S->top == - 1 indicates empty stack*/ 70 | if(isEmpty(S)){ 71 | printf("Stack is Empty"); 72 | return INT_MIN;; 73 | } 74 | else 75 | return (S->array[S->top]); 76 | } 77 | 78 | void deleteStack(struct Stack *S){ 79 | if(S) { 80 | if(S->array) 81 | free(S->array); 82 | free(S); 83 | } 84 | } 85 | 86 | int isPalindrome(char A[]){ 87 | int i=0; 88 | struct Stack *stk = createStack(strlen(A)); 89 | while(A[i] && A[i] != 'X') { 90 | push(stk, A[i]); 91 | i++; 92 | } 93 | i++; 94 | while(A[i]) { 95 | if(isEmpty(stk) || A[i] != pop(stk)) { 96 | printf("Not a palindrome\n"); 97 | return 0; 98 | } 99 | i++; 100 | } 101 | printf("Palindrome\n"); 102 | return 1; 103 | } 104 | 105 | int main(void){ 106 | isPalindrome("ababaXababa"); 107 | isPalindrome("ababababXbababbbbabba"); 108 | return 0; 109 | } 110 | 111 | -------------------------------------------------------------------------------- /src/Chapter_04_Stacks/largestHistrogram_n^2.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int largestHistrogram(vector &A) { 6 | int maxArea = 0; 7 | for (int i = 0; i < A.size(); i++) { 8 | for (int j = i, minimum_height = A[i]; j < A.size(); j++) { 9 | minimum_height = min(minimum_height, A[j]); 10 | maxArea = max(maxArea, (j-i+1) * minimum_height); 11 | } 12 | } 13 | return maxArea; 14 | } 15 | 16 | int main() { 17 | vector A; 18 | A.push_back(6); 19 | A.push_back(2); 20 | A.push_back(5); 21 | A.push_back(4); 22 | A.push_back(5); 23 | A.push_back(1); 24 | A.push_back(6); 25 | printf("largestRectangleArea: %d", largestHistrogram(A)); 26 | return 0; 27 | } 28 | -------------------------------------------------------------------------------- /src/Chapter_04_Stacks/largestHistrogram_n^3.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | int findMin(vector &A, int i, int j){ 5 | int min = A[i]; 6 | while(i <= j){ 7 | if (min > A[i]) 8 | min = A[i]; 9 | i++; 10 | } 11 | return min; 12 | } 13 | int largestHistrogram(vector &A) { 14 | int maxArea = 0; 15 | for (int i = 0; i < A.size(); i++) { 16 | for (int j = i, minimum_height = A[i]; j < A.size(); j++) { 17 | minimum_height = findMin(A, i, j); 18 | maxArea = max(maxArea, (j-i+1) * minimum_height); 19 | } 20 | } 21 | return maxArea; 22 | } 23 | 24 | int main() { 25 | vector A; 26 | A.push_back(6); 27 | A.push_back(2); 28 | A.push_back(5); 29 | A.push_back(4); 30 | A.push_back(5); 31 | A.push_back(1); 32 | A.push_back(6); 33 | printf("largestRectangleArea: %d", largestHistrogram(A)); 34 | return 0; 35 | } 36 | -------------------------------------------------------------------------------- /src/Chapter_04_Stacks/largestHistrogram_nlogn.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // Function returning the max area under the histogram 5 | int largestArea(int hist[],int n) 6 | { 7 | stack index ; 8 | int currentArea , maxArea = -1 ; 9 | int left , top ; 10 | for ( int i = 0 ; i <= n ; i++) 11 | { 12 | while( !index.empty() && (i == n || hist[index.top()] > hist[i]) ) 13 | { 14 | // Calculating the nearest smallest pillar 15 | if ( index.size() > 1 ) 16 | { 17 | top = index.top(); 18 | index.pop(); 19 | left = index.top(); 20 | } 21 | // Case of only one element 22 | else 23 | { 24 | left = -1 ; 25 | top = index.top() ; 26 | index.pop(); 27 | } 28 | currentArea = hist[top] * ( i - left - 1) ; 29 | // Updating the maxArea if condition evaluates out to be true 30 | maxArea = maxArea < currentArea ? currentArea : maxArea ; 31 | } 32 | if( i < n ) 33 | { 34 | index.push(i); 35 | } 36 | } 37 | return maxArea ; 38 | } 39 | 40 | int main() 41 | { 42 | // Array containing the heights of the various histogram 43 | int arr[] = { 3, 2, 5, 6, 1, 4, 4 }; 44 | // sizeof(arr)/sizeof(arr[0]) gives the size of the array i.e. 7 in this case 45 | cout << largestArea(arr,sizeof(arr)/sizeof(arr[0])) << endl ; 46 | return 0 ; 47 | } 48 | -------------------------------------------------------------------------------- /src/Chapter_04_Stacks/postfixEvaluation.c: -------------------------------------------------------------------------------- 1 | /*Copyright (c) 2016 CareerMonk Publications and others. 2 | #E-Mail : info@careermonk.com 3 | #Creation Date : 2008-01-10 06:15:46 4 | #Created by : Narasimha Karumanchi 5 | #Book Title : Data Structures And Algorithms Made Easy 6 | #Warranty : This software is provided "as is" without any 7 | # warranty; without even the implied warranty of 8 | # merchantability or fitness for a particular purpose.*/ 9 | 10 | #include 11 | #include 12 | 13 | struct Stack { 14 | int top; 15 | int capacity; 16 | int *array; 17 | }; 18 | 19 | struct Stack *createStack(int capacity) { 20 | struct Stack *S = malloc(sizeof(struct Stack)); 21 | if(!S) 22 | return NULL; 23 | S->capacity = capacity; 24 | S->top = -1; 25 | S->array= malloc(S->capacity * sizeof(int)); 26 | if(!S->array) 27 | return NULL; 28 | return S; 29 | } 30 | 31 | int isEmpty(struct Stack *S) { 32 | return (S->top == -1); // if the condition is true then 1 is returned else 0 is returned 33 | } 34 | 35 | int isFull(struct Stack *S){ 36 | //if the condition is true then 1 is returned else 0 is returned 37 | return (S->top == S->capacity - 1); 38 | } 39 | 40 | void doubleStack(struct Stack *S){ 41 | S->capacity *= 2; 42 | S->array = realloc(S->array, S->capacity * sizeof(int)); 43 | } 44 | 45 | void push(struct Stack *S, char data){ 46 | if(isFull(S)) 47 | doubleStack(S); 48 | S->array[++S->top] = data; 49 | } 50 | 51 | int peek(struct Stack *S){ 52 | /* S->top == - 1 indicates empty stack*/ 53 | if(isEmpty(S)){ 54 | printf("Stack is Empty"); 55 | return '\0'; 56 | } 57 | else 58 | return (S->array[S->top]); 59 | } 60 | 61 | char pop(struct Stack *S){ 62 | /* S->top == - 1 indicates empty stack*/ 63 | if(isEmpty(S)){ 64 | printf("Stack is Empty\n"); 65 | return '\0'; 66 | } 67 | else /* Removing element from ‘top’ of the array and reducing ‘top’ by 1*/ 68 | return (S->array[S->top--]); 69 | } 70 | 71 | void deleteStack(struct Stack *S){ 72 | if(S) { 73 | if(S->array) 74 | free(S->array); 75 | free(S); 76 | } 77 | } 78 | 79 | int postfixEvaluation(char expression[]){ 80 | // Create a Stack of capacity equal to expression size 81 | struct Stack* stk = createStack(strlen(expression)); 82 | int i; 83 | 84 | // Scan all characters one by one 85 | for (i = 0; expression[i]; ++i){ 86 | // If the scanned character is an operand (number here), 87 | // push it to the Stack. 88 | if (isdigit(expression[i])) 89 | push(stk, expression[i] - '0'); 90 | 91 | // If the scanned character is an operator, pop top two 92 | // elements from stack apply the operator 93 | else{ 94 | int topElement = pop(stk); 95 | int secondTopElement = pop(stk); 96 | switch (expression[i]){ 97 | case '+': push(stk, secondTopElement + topElement); break; 98 | case '-': push(stk, secondTopElement - topElement); break; 99 | case '*': push(stk, secondTopElement * topElement); break; 100 | case '/': push(stk, secondTopElement/topElement); break; 101 | } 102 | } 103 | } 104 | return pop(stk); 105 | } 106 | 107 | // test code 108 | int main() { 109 | printf ("postfix evaluation: %d", postfixEvaluation("123*+5-")); 110 | return 0; 111 | } 112 | -------------------------------------------------------------------------------- /src/Chapter_04_Stacks/postfixEvaluation.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Author : Shivam Chauhan 3 | Date : Feb 27 , 2019 4 | Postfix Expression Evalutaion 5 | */ 6 | #include 7 | using namespace std ; 8 | int postfix_evaluator( string str) 9 | { 10 | stacks; 11 | for ( auto c : str ) 12 | { 13 | int n1 , n2 ; 14 | if ( c >= '0' && c <= '9' ) 15 | { 16 | s.push(c-'0'); 17 | } 18 | else 19 | { 20 | if ( s.size() >= 2 ) 21 | { 22 | n1 = s.top() ; s.pop() ; 23 | n2 = s.top() ; s.pop() ; 24 | switch(c) 25 | { 26 | case '+' : s.push(n2+n1); 27 | break; 28 | case '-' : s.push(n2-n1); 29 | break; 30 | case '/' : s.push(n2/n1); 31 | break; 32 | case '*' : s.push(n2*n1); 33 | break; 34 | } 35 | } 36 | } 37 | } 38 | int tmp = s.top(); 39 | s.pop(); 40 | return tmp ; 41 | 42 | } 43 | int main() 44 | { 45 | string str = "95+4-"; 46 | cout << postfix_evaluator(str) << endl ; 47 | return 0 ; 48 | } -------------------------------------------------------------------------------- /src/Chapter_04_Stacks/reverseStack.c: -------------------------------------------------------------------------------- 1 | /*Copyright (c) 2016 CareerMonk Publications and others. 2 | #E-Mail : info@careermonk.com 3 | #Creation Date : 2008-01-10 06:15:46 4 | #Created by : Narasimha Karumanchi 5 | #Book Title : Data Structures And Algorithms Made Easy 6 | #Warranty : This software is provided "as is" without any 7 | # warranty; without even the implied warranty of 8 | # merchantability or fitness for a particular purpose.*/ 9 | 10 | #include 11 | #include 12 | #include 13 | #include 14 | 15 | struct Stack { 16 | int top; 17 | int capacity; 18 | char *array; 19 | }; 20 | 21 | struct Stack *createStack(int capacity) { 22 | struct Stack *S = malloc(sizeof(struct Stack)); 23 | if(!S) 24 | return NULL; 25 | S->capacity = capacity; 26 | S->top = -1; 27 | S->array= malloc(S->capacity * sizeof(int)); 28 | if(!S->array) 29 | return NULL; 30 | return S; 31 | } 32 | 33 | int isEmpty(struct Stack *S) { 34 | return (S->top == -1); // if the condition is true then 1 is returned else 0 is returned 35 | } 36 | 37 | int size(struct Stack *S) { 38 | return (S->top + 1); 39 | } 40 | 41 | int isFull(struct Stack *S){ 42 | //if the condition is true then 1 is returned else 0 is returned 43 | return (S->top == S->capacity - 1); 44 | } 45 | 46 | void doubleStack(struct Stack *S){ 47 | S->capacity *= 2; 48 | S->array = realloc(S->array, S->capacity * sizeof(int)); 49 | } 50 | 51 | 52 | void push(struct Stack *S, char data){ 53 | if(isFull(S)) 54 | doubleStack(S); 55 | S->array[++S->top] = data; 56 | } 57 | 58 | char pop(struct Stack *S){ 59 | /* S->top == - 1 indicates empty stack*/ 60 | if(isEmpty(S)){ 61 | printf("Stack is Empty\n"); 62 | return '\0'; 63 | } 64 | else /* Removing element from ‘top’ of the array and reducing ‘top’ by 1*/ 65 | return (S->array[S->top--]); 66 | } 67 | 68 | int peek(struct Stack *S){ 69 | /* S->top == - 1 indicates empty stack*/ 70 | if(isEmpty(S)){ 71 | printf("Stack is Empty"); 72 | return INT_MIN;; 73 | } 74 | else 75 | return (S->array[S->top]); 76 | } 77 | 78 | void deleteStack(struct Stack *S){ 79 | if(S) { 80 | if(S->array) 81 | free(S->array); 82 | free(S); 83 | } 84 | } 85 | 86 | void reverseStack(struct Stack *S){ 87 | char data; 88 | 89 | if(isEmpty(S)) 90 | return; 91 | 92 | data = pop(S); 93 | reverseStack(S); 94 | insertAtBottom(S, data); 95 | } 96 | 97 | void insertAtBottom(struct Stack *S, char data){ 98 | char temp; 99 | 100 | if(isEmpty(S)) { 101 | push(S, data); 102 | return; 103 | } 104 | 105 | temp = pop(S); 106 | insertAtBottom(S, data); 107 | push(S, temp); 108 | } 109 | 110 | 111 | int main(void){ 112 | int i = 0, capacity = 2; 113 | // create a stack of capacity 2 114 | struct Stack *stk = createStack(capacity); 115 | 116 | for(i = 0; i <= capacity; i++){ 117 | push(stk, i); 118 | } 119 | reverseStack(stk); 120 | printf("Top element is %d\n", peek(stk)); 121 | printf("Stack size is %d\n", size(stk)); 122 | 123 | for (i = 0; i <= capacity; i++){ 124 | printf("Popped element is %d\n", pop(stk)); 125 | } 126 | 127 | deleteStack(stk); 128 | return 0; 129 | 130 | return 0; 131 | } 132 | 133 | -------------------------------------------------------------------------------- /src/Chapter_06_Trees/BinaryTree.c: -------------------------------------------------------------------------------- 1 | /*Copyright (c) 2016 CareerMonk Publications and others. 2 | #E-Mail : info@careermonk.com 3 | #Creation Date : 2008-01-10 06:15:46 4 | #Created by : Narasimha Karumanchi 5 | #Book Title : Data Structures And Algorithms Made Easy 6 | #Warranty : This software is provided "as is" without any 7 | # warranty; without even the implied warranty of 8 | # merchantability or fitness for a particular purpose.*/ 9 | 10 | #include 11 | #include 12 | struct BinaryTreeNode{ 13 | int data; 14 | struct BinaryTreeNode *left; 15 | struct BinaryTreeNode *right; 16 | }; 17 | struct BinaryTreeNode* createNewNode(int data){ 18 | struct BinaryTreeNode* node = (struct BinaryTreeNode*)malloc(sizeof(struct BinaryTreeNode)); 19 | node->data = data; 20 | node->left = NULL; 21 | node->right = NULL; 22 | return node; 23 | } -------------------------------------------------------------------------------- /src/Chapter_06_Trees/FindMaxUsingLevelOrder.c: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2008 CareerMonk Publications and others. 2 | // #E-Mail : info@careermonk.com 3 | // Creation Date : 2008-01-10 06:15:46 4 | // Created by : Narasimha Karumanchi 5 | // Book Title : Data Structures And Algorithms Made Easy 6 | // Warranty : This software is provided "as is" without any 7 | // warranty; without even the implied warranty of 8 | // merchantability or fitness for a particular purpose. 9 | 10 | #include 11 | #include 12 | #include 13 | 14 | struct BinaryTreeNode { 15 | int data; 16 | struct BinaryTreeNode *left; 17 | struct BinaryTreeNode *right; 18 | }; 19 | 20 | struct ListNode { 21 | struct BinaryTreeNode *data; 22 | struct ListNode *next; 23 | }; 24 | 25 | 26 | struct Queue { 27 | struct ListNode *front; 28 | struct ListNode *rear; 29 | }; 30 | 31 | /* Create an empty queue */ 32 | struct Queue *createQueue() { 33 | struct Queue *Q; 34 | Q = malloc(sizeof(struct Queue)); 35 | if(!Q) 36 | return NULL; 37 | 38 | Q->front = Q->rear = NULL; 39 | return Q; 40 | } 41 | 42 | /* Returns queue size */ 43 | int size(struct Queue *Q) { 44 | struct ListNode *temp = Q->front; 45 | int count = 0; 46 | 47 | if(Q->front == NULL && Q->rear == NULL) 48 | return 0; 49 | 50 | while(temp != Q->rear){ 51 | count++; 52 | temp = temp->next; 53 | } 54 | if(temp == Q->rear) 55 | count++; 56 | 57 | return count; 58 | } 59 | 60 | /* Returns Frnt Element of the Queue */ 61 | struct BinaryTreeNode* frontElement(struct Queue *Q) { 62 | return Q->front->data; 63 | } 64 | 65 | /* Returns the Rear Element of the Queue */ 66 | struct BinaryTreeNode* rearElement(struct Queue *Q) { 67 | return Q->rear->data; 68 | } 69 | 70 | /* 71 | Check's if Queue is empty or not 72 | */ 73 | int isEmpty(struct Queue *Q) { 74 | if (Q->front == NULL && Q->rear == NULL) 75 | return 1; 76 | else 77 | return 0; 78 | } 79 | /* 80 | Adding elements in Queue 81 | */ 82 | void enQueue(struct Queue *Q, struct BinaryTreeNode *node) { 83 | struct ListNode *temp; 84 | temp = (struct ListNode *)malloc(sizeof(struct ListNode)); 85 | temp->data = node; 86 | temp->next = NULL; 87 | 88 | if (Q->rear == NULL) { 89 | Q->front = Q->rear = temp; 90 | } else { 91 | Q->rear->next = temp; 92 | Q->rear = temp; 93 | } 94 | } 95 | 96 | /* 97 | Removes an element from front of the queue 98 | */ 99 | struct BinaryTreeNode* deQueue(struct Queue *Q) { 100 | struct ListNode *temp; 101 | if (Q->front == NULL) { 102 | printf("\nQueue is Empty \n"); 103 | return NULL; 104 | } else { 105 | temp = Q->front; 106 | Q->front = Q->front->next; 107 | if(Q->front == NULL){ 108 | Q->rear = NULL; 109 | } 110 | return temp->data; 111 | } 112 | } 113 | 114 | /* 115 | Print's Queue 116 | */ 117 | void printQueue(struct Queue *Q) { 118 | struct ListNode *temp = Q->front; 119 | 120 | if ((Q->front == NULL) && (Q->rear == NULL)) { 121 | printf("Queue is Empty\n"); 122 | return; 123 | } 124 | 125 | while (temp != NULL) { 126 | printf("%d", temp->data->data); 127 | temp = temp->next; 128 | if(temp != NULL) 129 | printf("-->"); 130 | } 131 | } 132 | 133 | void deleteQueue(struct Queue *Q) { 134 | struct ListNode *temp; 135 | while(Q->front) { 136 | temp = Q->front; 137 | printf("Element being deleted: %d\n", temp->data->data); 138 | Q->front = Q->front->next; 139 | free(temp); 140 | } 141 | free(Q); 142 | } 143 | 144 | 145 | 146 | struct BinaryTreeNode* createNewNode(int data){ // creating new node 147 | struct BinaryTreeNode* newNode = (struct BinaryTreeNode*)malloc(sizeof(struct BinaryTreeNode)); 148 | newNode->data = data; 149 | newNode->left = NULL; 150 | newNode->right = NULL; 151 | 152 | return(newNode); 153 | } 154 | 155 | int findMaxUsingLevelOrder(struct BinaryTreeNode *root){ 156 | struct BinaryTreeNode *temp; 157 | int max = INT_MIN; 158 | struct Queue *Q = createQueue(); 159 | 160 | enQueue(Q,root); 161 | 162 | while(!isEmpty(Q)) { 163 | temp = deQueue(Q); 164 | // largest of the three values 165 | if(max < temp->data) 166 | max = temp->data; 167 | if(temp->left) 168 | enQueue (Q, temp->left); 169 | if(temp->right) 170 | enQueue (Q, temp->right); 171 | } 172 | deleteQueue(Q); 173 | return max; 174 | } 175 | 176 | 177 | int main() { 178 | //**same BinaryTreeNode is builted as shown in example** 179 | struct BinaryTreeNode *root = createNewNode(2); 180 | root->left= createNewNode(7); 181 | root->right= createNewNode(5); 182 | root->right->right=createNewNode(19); 183 | root->right->right->left=createNewNode(4); 184 | root->left->left=createNewNode(2); 185 | root->left->right=createNewNode(6); 186 | root->left->right->left=createNewNode(5); 187 | root->left->right->right=createNewNode(11); 188 | 189 | printf("Maximum in tree is %d", findMaxUsingLevelOrder(root)); 190 | ; 191 | return 0; 192 | } 193 | -------------------------------------------------------------------------------- /src/Chapter_06_Trees/InorderTraversalIterative.c: -------------------------------------------------------------------------------- 1 | /*Copyright (c) 2016 CareerMonk Publications and others. 2 | #E-Mail : info@careermonk.com 3 | #Creation Date : 2008-01-10 06:15:46 4 | #Created by : Narasimha Karumanchi 5 | #Book Title : Data Structures And Algorithms Made Easy 6 | #Warranty : This software is provided "as is" without any 7 | # warranty; without even the implied warranty of 8 | # merchantability or fitness for a particular purpose.*/ 9 | 10 | #include 11 | #include 12 | struct BinaryTreeNode{ 13 | int data; 14 | struct BinaryTreeNode *left; 15 | struct BinaryTreeNode *right; 16 | }; 17 | 18 | void inOrderNonRecursive(struct BinaryTreeNode *root){ 19 | struct Stack *S = CreateStack(); 20 | while(1) { 21 | while(root) { 22 | Push(S,root); 23 | //Got left subtree and keep on adding to stack 24 | root = root->left; 25 | } 26 | if(IsEmptyStack(S)) 27 | break; 28 | root = Pop(S); 29 | 30 | printf("%d ", root->data); //After popping, process the current node 31 | //Indicates completion of left subtree and current node, now go to right subtree 32 | root = root->right; 33 | } 34 | DeleteStack(S); 35 | } 36 | 37 | 38 | int testInOrderIterative(){ 39 | /* Sample binary tree is 40 | 9 41 | / \ 42 | 19 1 43 | \ / \ 44 | 3 6 10 45 | */ 46 | struct BinaryTreeNode* root = createNewNode(9); 47 | root->left = createNewNode(19); 48 | root->right = createNewNode(1); 49 | struct BinaryTreeNode* temp = root->left; 50 | temp->right = createNewNode(3); 51 | temp = root->right; 52 | temp->left = createNewNode(6); 53 | temp->left = createNewNode(10); 54 | inOrderNonRecursive(root); 55 | return 0; 56 | } -------------------------------------------------------------------------------- /src/Chapter_06_Trees/InorderTraversalRecursive.c: -------------------------------------------------------------------------------- 1 | /*Copyright (c) 2016 CareerMonk Publications and others. 2 | #E-Mail : info@careermonk.com 3 | #Creation Date : 2008-01-10 06:15:46 4 | #Created by : Narasimha Karumanchi 5 | #Book Title : Data Structures And Algorithms Made Easy 6 | #Warranty : This software is provided "as is" without any 7 | # warranty; without even the implied warranty of 8 | # merchantability or fitness for a particular purpose.*/ 9 | 10 | #include 11 | #include 12 | struct BinaryTreeNode{ 13 | int data; 14 | struct BinaryTreeNode *left; 15 | struct BinaryTreeNode *right; 16 | }; 17 | 18 | void inOrder(struct BinaryTreeNode* root){ 19 | if (root == NULL) // or if (!root) 20 | return; 21 | 22 | inOrder(root->left); 23 | printf("%d ", root->data); 24 | inOrder(root->right); 25 | } 26 | 27 | int testInOrder(){ 28 | /* Sample binary tree is 29 | 9 30 | / \ 31 | 19 1 32 | \ / 33 | 3 6 34 | */ 35 | struct BinaryTreeNode* root = createNewNode(9); 36 | root->left = createNewNode(19); 37 | root->right = createNewNode(1); 38 | struct BinaryTreeNode* temp = root->left; 39 | temp->right = createNewNode(3); 40 | temp = root->right; 41 | temp->left = createNewNode(6); 42 | inOrder(root); 43 | return 0; 44 | } -------------------------------------------------------------------------------- /src/Chapter_06_Trees/LevelOrder.c: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2008 CareerMonk Publications and others. 2 | // #E-Mail : info@careermonk.com 3 | // Creation Date : 2008-01-10 06:15:46 4 | // Created by : Narasimha Karumanchi 5 | // Book Title : Data Structures And Algorithms Made Easy 6 | // Warranty : This software is provided "as is" without any 7 | // warranty; without even the implied warranty of 8 | // merchantability or fitness for a particular purpose. 9 | 10 | #include 11 | #include 12 | 13 | 14 | struct BinaryTreeNode { 15 | int data; 16 | struct BinaryTreeNode *left; 17 | struct BinaryTreeNode *right; 18 | }; 19 | 20 | struct ListNode { 21 | struct BinaryTreeNode *data; 22 | struct ListNode *next; 23 | }; 24 | 25 | 26 | struct Queue { 27 | struct ListNode *front; 28 | struct ListNode *rear; 29 | }; 30 | 31 | /* Create an empty queue */ 32 | struct Queue *createQueue() { 33 | struct Queue *Q; 34 | Q = malloc(sizeof(struct Queue)); 35 | if(!Q) 36 | return NULL; 37 | 38 | Q->front = Q->rear = NULL; 39 | return Q; 40 | } 41 | 42 | /* Returns queue size */ 43 | int size(struct Queue *Q) { 44 | struct ListNode *temp = Q->front; 45 | int count = 0; 46 | 47 | if(Q->front == NULL && Q->rear == NULL) 48 | return 0; 49 | 50 | while(temp != Q->rear){ 51 | count++; 52 | temp = temp->next; 53 | } 54 | if(temp == Q->rear) 55 | count++; 56 | 57 | return count; 58 | } 59 | 60 | /* Returns Frnt Element of the Queue */ 61 | struct BinaryTreeNode* frontElement(struct Queue *Q) { 62 | return Q->front->data; 63 | } 64 | 65 | /* Returns the Rear Element of the Queue */ 66 | struct BinaryTreeNode* rearElement(struct Queue *Q) { 67 | return Q->rear->data; 68 | } 69 | 70 | /* 71 | Check's if Queue is empty or not 72 | */ 73 | int isEmpty(struct Queue *Q) { 74 | if (Q->front == NULL && Q->rear == NULL) 75 | return 1; 76 | else 77 | return 0; 78 | } 79 | /* 80 | Adding elements in Queue 81 | */ 82 | void enQueue(struct Queue *Q, struct BinaryTreeNode *node) { 83 | struct ListNode *temp; 84 | temp = (struct ListNode *)malloc(sizeof(struct ListNode)); 85 | temp->data = node; 86 | temp->next = NULL; 87 | 88 | if (Q->rear == NULL) { 89 | Q->front = Q->rear = temp; 90 | } else { 91 | Q->rear->next = temp; 92 | Q->rear = temp; 93 | } 94 | } 95 | 96 | /* 97 | Removes an element from front of the queue 98 | */ 99 | struct BinaryTreeNode* deQueue(struct Queue *Q) { 100 | struct ListNode *temp; 101 | if (Q->front == NULL) { 102 | printf("\nQueue is Empty \n"); 103 | return NULL; 104 | } else { 105 | temp = Q->front; 106 | Q->front = Q->front->next; 107 | if(Q->front == NULL){ 108 | Q->rear = NULL; 109 | } 110 | return temp->data; 111 | } 112 | } 113 | 114 | /* 115 | Print's Queue 116 | */ 117 | void printQueue(struct Queue *Q) { 118 | struct ListNode *temp = Q->front; 119 | 120 | if ((Q->front == NULL) && (Q->rear == NULL)) { 121 | printf("Queue is Empty\n"); 122 | return; 123 | } 124 | 125 | while (temp != NULL) { 126 | printf("%d", temp->data->data); 127 | temp = temp->next; 128 | if(temp != NULL) 129 | printf("-->"); 130 | } 131 | } 132 | 133 | void deleteQueue(struct Queue *Q) { 134 | struct ListNode *temp; 135 | while(Q->front) { 136 | temp = Q->front; 137 | printf("Element being deleted: %d\n", temp->data->data); 138 | Q->front = Q->front->next; 139 | free(temp); 140 | } 141 | free(Q); 142 | } 143 | 144 | 145 | 146 | struct BinaryTreeNode* createNewNode(int data){ // creating new node 147 | struct BinaryTreeNode* newNode = (struct BinaryTreeNode*)malloc(sizeof(struct BinaryTreeNode)); 148 | newNode->data = data; 149 | newNode->left = NULL; 150 | newNode->right = NULL; 151 | 152 | return(newNode); 153 | } 154 | 155 | void levelOrder(struct BinaryTreeNode *root){ 156 | struct BinaryTreeNode *temp; 157 | struct Queue *Q = createQueue(); 158 | 159 | if(!root) 160 | return; 161 | 162 | enQueue(Q, root); 163 | while(!isEmpty(Q)){ 164 | temp = deQueue(Q); 165 | //Process current node 166 | printf("\n%d", temp->data); 167 | if(temp->left) 168 | enQueue(Q, temp->left); 169 | if(temp->right) 170 | enQueue(Q, temp->right); 171 | } 172 | deleteQueue(Q); 173 | } 174 | 175 | 176 | int main() { 177 | //**same BinaryTreeNode is builted as shown in example** 178 | struct BinaryTreeNode *root = createNewNode(2); 179 | root->left= createNewNode(7); 180 | root->right= createNewNode(5); 181 | root->right->right=createNewNode(9); 182 | root->right->right->left=createNewNode(4); 183 | root->left->left=createNewNode(2); 184 | root->left->right=createNewNode(6); 185 | root->left->right->left=createNewNode(5); 186 | root->left->right->right=createNewNode(11); 187 | 188 | printf("Level Order traversal of binary BinaryTreeNode is :"); 189 | levelOrder(root); 190 | return 0; 191 | } 192 | -------------------------------------------------------------------------------- /src/Chapter_06_Trees/PostorderTraversalIterative.c: -------------------------------------------------------------------------------- 1 | /*Copyright (c) 2016 CareerMonk Publications and others. 2 | #E-Mail : info@careermonk.com 3 | #Creation Date : 2008-01-10 06:15:46 4 | #Created by : Narasimha Karumanchi 5 | #Book Title : Data Structures And Algorithms Made Easy 6 | #Warranty : This software is provided "as is" without any 7 | # warranty; without even the implied warranty of 8 | # merchantability or fitness for a particular purpose.*/ 9 | 10 | 11 | #include 12 | #include 13 | #define MAXSIZE 10 14 | 15 | struct SimpleArrayStack { 16 | int top; 17 | int capacity; 18 | unsigned int *addresses; //storing node addresses in array 19 | }; 20 | struct BinaryTreeNode{ 21 | int data; 22 | struct BinaryTreeNode *left; 23 | struct BinaryTreeNode *right; 24 | }; 25 | struct SimpleArrayStack *CreateStack(){ 26 | struct SimpleArrayStack *S = malloc(sizeof(struct SimpleArrayStack)); 27 | if(!S) 28 | return NULL; 29 | S->capacity = MAXSIZE; 30 | S->top = -1; 31 | S->addresses = malloc(S->capacity * sizeof(unsigned int)); 32 | 33 | if(!S->addresses) 34 | return NULL; 35 | return S; 36 | } 37 | 38 | int IsFullStack(struct SimpleArrayStack *S){ 39 | return (S->top == S->capacity-1); 40 | } 41 | 42 | void Push(struct SimpleArrayStack *S, struct BinaryTreeNode *data){ 43 | // No overflow in this implementation 44 | if(IsFullStack(S)) { 45 | printf("Overflow: Stack full"); 46 | return; 47 | } 48 | ++S->top; 49 | S->addresses[S->top] = data; 50 | } 51 | 52 | int IsEmptyStack(struct SimpleArrayStack *S){ 53 | return S->top == -1; 54 | } 55 | 56 | struct BinaryTreeNode *Top(struct SimpleArrayStack *S){ 57 | if(IsEmptyStack(S)) 58 | return NULL; 59 | 60 | return S->addresses[S->top]; 61 | } 62 | 63 | struct BinaryTreeNode *Pop(struct SimpleArrayStack *S){ 64 | if(IsEmptyStack(S)){ 65 | printf("Underflow: Stack empty"); 66 | return NULL; 67 | } 68 | return S->addresses[S->top--]; 69 | } 70 | 71 | void DeleteStack(struct SimpleArrayStack *S){ 72 | if(S) { 73 | if(S->addresses) 74 | free(S->addresses); 75 | free(S); 76 | } 77 | } 78 | 79 | void postOrderIterative(struct BinaryTreeNode* root){ 80 | struct SimpleArrayStack *S = CreateStack(); 81 | struct BinaryTreeNode *previous = NULL; 82 | do{ 83 | while (root!=NULL){ 84 | Push(S, root); 85 | root = root->left; 86 | } 87 | while(root == NULL && !IsEmptyStack(S)){ 88 | root = Top(S); 89 | if(root->right == NULL || root->right == previous){ 90 | printf("%d ", root->data); 91 | Pop(S); 92 | previous = root; 93 | root = NULL; 94 | } 95 | else 96 | root = root->right; 97 | } 98 | }while(!IsEmptyStack(S)); 99 | } 100 | 101 | int testPostOrderIterative(){ 102 | /* Sample binary tree is 103 | 9 104 | / \ 105 | 19 1 106 | \ / \ 107 | 3 6 10 108 | */ 109 | struct BinaryTreeNode* root = createNewNode(9); 110 | root->left = createNewNode(19); 111 | root->right = createNewNode(1); 112 | struct BinaryTreeNode* temp = root->left; 113 | temp->right = createNewNode(3); 114 | temp = root->right; 115 | temp->left = createNewNode(6); 116 | temp->right = createNewNode(10); 117 | postOrderIterative(root); 118 | return 0; 119 | } -------------------------------------------------------------------------------- /src/Chapter_06_Trees/PostorderTraversalRecursive.c: -------------------------------------------------------------------------------- 1 | /*Copyright (c) 2016 CareerMonk Publications and others. 2 | #E-Mail : info@careermonk.com 3 | #Creation Date : 2008-01-10 06:15:46 4 | #Created by : Narasimha Karumanchi 5 | #Book Title : Data Structures And Algorithms Made Easy 6 | #Warranty : This software is provided "as is" without any 7 | # warranty; without even the implied warranty of 8 | # merchantability or fitness for a particular purpose.*/ 9 | 10 | #include 11 | #include 12 | struct BinaryTreeNode{ 13 | int data; 14 | struct BinaryTreeNode *left; 15 | struct BinaryTreeNode *right; 16 | }; 17 | 18 | void postOrder(struct BinaryTreeNode* root){ 19 | if (root == NULL) // or if (!root) 20 | return; 21 | 22 | postOrder(root->left); 23 | postOrder(root->right); 24 | printf("%d ", root->data); 25 | } 26 | 27 | int testPostOrder(){ 28 | /* Sample binary tree is 29 | 9 30 | / \ 31 | 19 1 32 | \ / 33 | 3 6 34 | */ 35 | struct BinaryTreeNode* root = createNewNode(9); 36 | root->left = createNewNode(19); 37 | root->right = createNewNode(1); 38 | struct BinaryTreeNode* temp = root->left; 39 | temp->right = createNewNode(3); 40 | temp = root->right; 41 | temp->left = createNewNode(6); 42 | postOrder(root); 43 | return 0; 44 | } -------------------------------------------------------------------------------- /src/Chapter_06_Trees/PreorderTraversalIterative.c: -------------------------------------------------------------------------------- 1 | /*Copyright (c) 2016 CareerMonk Publications and others. 2 | #E-Mail : info@careermonk.com 3 | #Creation Date : 2008-01-10 06:15:46 4 | #Created by : Narasimha Karumanchi 5 | #Book Title : Data Structures And Algorithms Made Easy 6 | #Warranty : This software is provided "as is" without any 7 | # warranty; without even the implied warranty of 8 | # merchantability or fitness for a particular purpose.*/ 9 | 10 | #include 11 | #include 12 | struct BinaryTreeNode{ 13 | int data; 14 | struct BinaryTreeNode *left; 15 | struct BinaryTreeNode *right; 16 | }; 17 | void preOrderNonRecursive(struct BinaryTreeNode *root){ 18 | struct DynArrayStack *S = CreateStack(); 19 | while(1) { 20 | while(root) { 21 | //Process current node 22 | printf("%d ", root->data); 23 | Push(S, root); 24 | //If left subtree exists, add to stack 25 | root = root->left; 26 | } 27 | if(IsEmptyStack(S)) 28 | break; 29 | root = Pop(S); 30 | //Indicates completion of left subtree and current node, now go to right subtree 31 | root = root->right; 32 | } 33 | DeleteStack(S); 34 | } 35 | 36 | int testPreOrderNonRecursive(){ 37 | /* Sample binary tree is 38 | 9 39 | / \ 40 | 19 1 41 | \ / \ 42 | 3 6 19 43 | */ 44 | struct BinaryTreeNode* root = createNewNode(9); 45 | root->left = createNewNode(19); 46 | root->right = createNewNode(1); 47 | struct BinaryTreeNode* temp = root->left; 48 | temp->right = createNewNode(3); 49 | temp = root->right; 50 | temp->left = createNewNode(6); 51 | temp->right = createNewNode(19); 52 | preOrderNonRecursive(root); 53 | return 0; 54 | } -------------------------------------------------------------------------------- /src/Chapter_06_Trees/PreorderTraversalRecursive.c: -------------------------------------------------------------------------------- 1 | /*Copyright (c) 2016 CareerMonk Publications and others. 2 | #E-Mail : info@careermonk.com 3 | #Creation Date : 2008-01-10 06:15:46 4 | #Created by : Narasimha Karumanchi 5 | #Book Title : Data Structures And Algorithms Made Easy 6 | #Warranty : This software is provided "as is" without any 7 | # warranty; without even the implied warranty of 8 | # merchantability or fitness for a particular purpose.*/ 9 | 10 | #include 11 | #include 12 | struct BinaryTreeNode{ 13 | int data; 14 | struct BinaryTreeNode *left; 15 | struct BinaryTreeNode *right; 16 | }; 17 | 18 | void preOrder(struct BinaryTreeNode* root){ 19 | if (root == NULL) // or if (!root) 20 | return; 21 | printf("%d ", root->data); 22 | preOrder(root->left); 23 | preOrder(root->right); 24 | } 25 | 26 | int testPreOrder(){ 27 | /* Sample binary tree is 28 | 9 29 | / \ 30 | 19 1 31 | \ / 32 | 3 6 33 | */ 34 | struct BinaryTreeNode* root = createNewNode(9); 35 | root->left = createNewNode(19); 36 | root->right = createNewNode(1); 37 | struct BinaryTreeNode* temp = root->left; 38 | temp->right = createNewNode(3); 39 | temp = root->right; 40 | temp->left = createNewNode(6); 41 | preOrder(root); 42 | return 0; 43 | } -------------------------------------------------------------------------------- /src/Chapter_09_Graph_Algorithms/AdjacencyMatrix.c: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2008 CareerMonk Publications and others. 2 | // E-Mail : info@careermonk.com 3 | // Creation Date : 2008-01-10 06:15:46 4 | // Created by : Narasimha Karumanchi 5 | // Book Title : Data Structures And Algorithms Made Easy 6 | // Warranty : This software is provided "as is" without any 7 | // warranty; without even the implied warranty of 8 | // merchantability or fitness for a particular purpose. 9 | 10 | #include 11 | #include 12 | #include 13 | #include 14 | #define MAX_VERTICES 50 // max number of vertices for our graph 15 | #define MAX_DEGREE 50 // max degree for a vertex 16 | 17 | struct graph{ 18 | int V; // number of vertices 19 | int E; // number of edges 20 | int **adjMatrix; // adjacency matrix 21 | }; 22 | 23 | struct edge{ 24 | int source; 25 | int destination; 26 | }; 27 | 28 | void rand_init(void){ 29 | // Initializes the random generator rand() 30 | time_t t; 31 | srand((unsigned) time(&t)); 32 | } 33 | 34 | struct graph* createGraph(const int numVertices){ 35 | assert(numVertices >= 0); 36 | // Create an empty graph with numVertices 37 | int i, j; 38 | struct graph* G = (struct graph *) malloc(sizeof( struct graph)); 39 | G->V = numVertices; 40 | G->E = 0; 41 | // allocate memory for each row 42 | G->adjMatrix = malloc(numVertices * sizeof(int *)); 43 | assert(G != NULL); 44 | // allocate memory for each column and initialise with 0 45 | for (i = 0; i < numVertices; i++) { 46 | G->adjMatrix[i] = calloc(numVertices, sizeof(int)); 47 | assert(G->adjMatrix[i] != NULL); 48 | } 49 | return G; 50 | } 51 | 52 | void displayGraph(const struct graph* G){ 53 | // Display the graph (adjMatrix) 54 | int i,j, v; 55 | v = G->V; 56 | printf("%d vertices; %d edges.\n", G->V, G->E); 57 | for(i=0; i< v; i++){ 58 | for(j=0; j < v; j++) printf("%3d ",(G->adjMatrix)[i][j]); 59 | printf("\n"); 60 | } 61 | } 62 | 63 | void displayEdges(const struct graph* G){ 64 | int v,i,j; 65 | v = G->V; 66 | for(i=0; i < v; i++){ 67 | for(j=i+1; j < v; j++){ 68 | if(G->adjMatrix[i][j]==1) printf("%d-%d ",i,j); 69 | } 70 | } 71 | } 72 | 73 | void insertEdge(struct graph* G, const struct edge E){ 74 | int v, x, y; 75 | v = G->V; 76 | x = E.source; 77 | y = E.destination; 78 | if(x >= v || y >= v) { 79 | printf("Error when adding edge."); 80 | exit(EXIT_FAILURE); 81 | } 82 | if (G->adjMatrix[x][y] == 0){ // For undirected graphs set both the bits 83 | G->adjMatrix[x][y] = 1; 84 | G->adjMatrix[y][x] = 1; 85 | (G->E)++; 86 | } 87 | } 88 | 89 | void removeEdge(struct graph* G, const struct edge E){ 90 | int v, x, y; 91 | v = G->V; 92 | x = E.source; 93 | y = E.destination; 94 | if(x >= v || y >= v) { 95 | printf("Error when deleting edge."); 96 | exit(EXIT_FAILURE); 97 | } 98 | if (G->adjMatrix[x][y] == 1){ 99 | G->adjMatrix[x][y] = 0; 100 | G->adjMatrix[y][x] = 0; 101 | (G->E)--; 102 | } 103 | } 104 | 105 | void destroyGraph(struct graph* G){ // to free memory 106 | if (G){ 107 | if (G->adjMatrix){ 108 | int i; 109 | for (i = 0; i < G->V; i++) 110 | free(G->adjMatrix[i]); 111 | free(G->adjMatrix); 112 | } 113 | free(G); 114 | } 115 | } 116 | 117 | struct edge newEdge(int x, int y){ 118 | // return an edge with ends x and y 119 | struct edge e; 120 | e.source = x; 121 | e.destination = y; 122 | return e; 123 | } 124 | 125 | struct graph* randomGraph(const int N, const float p){ 126 | // A random graph with N vertices and probability p for each edge 127 | int i, j; 128 | struct edge E; 129 | struct graph* G = createGraph(N); 130 | rand_init(); 131 | for (i=0; i < N; i++) for(j=i+1; j < N; j++) { 132 | if (rand() < p * RAND_MAX) { // rand() returns an integer between 0 and RAND_MAX 133 | E = newEdge(i,j); 134 | insertEdge(G, E); 135 | } 136 | } 137 | return G; 138 | } 139 | 140 | 141 | 142 | void main(void){ 143 | // Test code 144 | struct edge E; 145 | struct graph* G = randomGraph(10, 0.15); 146 | displayGraph(G); 147 | E = newEdge(5,6); 148 | insertEdge(G, E); 149 | displayGraph(G); 150 | printf("\n"); 151 | displayEdges(G); 152 | removeEdge(G, E); 153 | displayGraph(G); 154 | printf("\n"); 155 | displayEdges(G); 156 | destroyGraph(G); 157 | } 158 | -------------------------------------------------------------------------------- /src/Chapter_09_Graph_Algorithms/AdjacentList.c: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2008 CareerMonk Publications and others. 2 | // E-Mail : info@careermonk.com 3 | // Creation Date : 2008-01-10 06:15:46 4 | // Created by : Narasimha Karumanchi 5 | // Book Title : Data Structures And Algorithms Made Easy 6 | // Warranty : This software is provided "as is" without any 7 | // warranty; without even the implied warranty of 8 | // merchantability or fitness for a particular purpose. 9 | 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | 16 | struct ListNode { 17 | int vertex; 18 | struct ListNode *next; 19 | }; 20 | 21 | struct edge{ 22 | int source; 23 | int destination; 24 | }; 25 | 26 | struct graph{ 27 | int V; // number of vertices 28 | int E; // number of edges 29 | struct ListNode *adjList[]; // adjacency matrix 30 | }; 31 | 32 | void rand_init(void){ 33 | // Initializes the random generator rand() 34 | time_t t; 35 | srand((unsigned) time(&t)); 36 | } 37 | 38 | 39 | int insertEdge(struct graph* G, const struct edge E) { 40 | int n, from, to; 41 | n = G->V; 42 | from = E.source; 43 | to = E.destination; 44 | 45 | if (0 > from || from > n || 0 > to || to > n) return -1; 46 | 47 | struct ListNode *prev = NULL, *ptr = G->adjList[from]; 48 | while (ptr != NULL) { 49 | if (ptr->vertex == to) return 0; 50 | else { 51 | prev = ptr; 52 | ptr = ptr->next; 53 | } 54 | } 55 | if (ptr==NULL) { 56 | struct ListNode *newNode = (struct ListNode *) malloc(sizeof(struct ListNode)); 57 | newNode->vertex = to; 58 | newNode->next = NULL; 59 | 60 | if (prev == NULL) { 61 | G->adjList[from] = newNode; 62 | } else { 63 | prev->next = newNode; 64 | } 65 | } 66 | return 1; 67 | } 68 | 69 | int removeEdge(struct graph* G, const struct edge E) { 70 | int n, from, to; 71 | n = G->V; 72 | from = E.source; 73 | to = E.destination; 74 | if (0 > from || from > n || 0 > to || to > n) return -1; 75 | struct ListNode *prev = NULL, *ptr = G->adjList[from]; 76 | while (ptr != NULL) { 77 | if (ptr->vertex == to) { 78 | if (prev == NULL) { 79 | G->adjList[from] = ptr->next; 80 | free(ptr); 81 | } else { 82 | prev->next = ptr->next; 83 | free(ptr); 84 | } 85 | return 1; 86 | } else { 87 | prev = ptr; 88 | ptr = ptr->next; 89 | } 90 | } 91 | return 0; 92 | } 93 | 94 | struct graph* createGraph(const int numVertices) { 95 | assert(numVertices >= 0); 96 | // Create an empty graph with numVertices 97 | int i, j; 98 | struct graph* G = (struct graph *) malloc(sizeof( struct graph)); 99 | assert(G != NULL); 100 | G->V = numVertices; 101 | G->E = 0; 102 | 103 | // allocate memory for each column and initialise with 0 104 | struct ListNode *newNode, *last; 105 | for (int i = 0; i < G->V; i++) { 106 | G->adjList[i] = (struct ListNode *) malloc(sizeof(struct ListNode)); 107 | assert(G->adjList[i] != NULL); 108 | G->adjList[i]->vertex = i; 109 | G->adjList[i]->next = NULL; 110 | } 111 | return G; 112 | } 113 | 114 | struct edge newEdge(int x, int y){ 115 | // return an edge with ends x and y 116 | struct edge e; 117 | e.source = x; 118 | e.destination = y; 119 | return e; 120 | } 121 | 122 | struct graph* randomGraph(const int N, const float p){ 123 | // A random graph with N vertices and probability p for each edge 124 | int i, j; 125 | struct edge E; 126 | struct graph* G = createGraph(N); 127 | rand_init(); 128 | for (i=0; i < N; i++) for(j=i+1; j < N; j++) { 129 | if (rand() < p * RAND_MAX) { // rand() returns an integer between 0 and RAND_MAX 130 | E = newEdge(i,j); 131 | insertEdge(G, E); 132 | } 133 | } 134 | return G; 135 | } 136 | 137 | void displayGraph(struct graph* G) { 138 | struct ListNode *ptr; 139 | int i; 140 | for (i = 0; i < G->V; i++) { 141 | ptr = G->adjList[i]; 142 | printf("\nnode %d neighbors:", i); 143 | while (ptr != NULL) { 144 | printf(" %d", ptr->vertex); 145 | ptr = ptr->next; 146 | } 147 | } 148 | } 149 | 150 | void destroyGraph(struct graph* G) { 151 | int i; 152 | struct ListNode *temp, *ptr; 153 | for (i = 0; i < G->V; i++) { 154 | ptr = G->adjList[i]; 155 | while (ptr != NULL) { 156 | temp = ptr; 157 | ptr = ptr->next; 158 | free(temp); 159 | } 160 | G->adjList[i] = NULL; 161 | } 162 | printf("\nGraph is deleted"); 163 | } 164 | 165 | int main(int argc, char *args[]) { 166 | // Test code 167 | struct edge E; 168 | struct graph* G = randomGraph(10, 0.15); 169 | displayGraph(G); 170 | 171 | E = newEdge(5,6); 172 | insertEdge(G, E); 173 | displayGraph(G); 174 | printf("\n"); 175 | 176 | removeEdge(G, E); 177 | displayGraph(G); 178 | printf("\n"); 179 | destroyGraph(G); 180 | return 0; 181 | } 182 | -------------------------------------------------------------------------------- /src/Chapter_09_Graph_Algorithms/DFS.c: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2008 CareerMonk Publications and others. 2 | // E-Mail : info@careermonk.com 3 | // Creation Date : 2008-01-10 06:15:46 4 | // Created by : Narasimha Karumanchi 5 | // Book Title : Data Structures And Algorithms Made Easy 6 | // Warranty : This software is provided "as is" without any 7 | // warranty; without even the implied warranty of 8 | // merchantability or fitness for a particular purpose. 9 | 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | 16 | struct ListNode { 17 | int vertex; 18 | struct ListNode *next; 19 | }; 20 | 21 | struct edge{ 22 | int source; 23 | int destination; 24 | }; 25 | 26 | struct graph{ 27 | int V; // number of vertices 28 | int E; // number of edges 29 | struct ListNode *adjList[]; // adjacency matrix 30 | }; 31 | 32 | void rand_init(void){ 33 | // Initializes the random generator rand() 34 | time_t t; 35 | srand((unsigned) time(&t)); 36 | } 37 | 38 | 39 | int insertEdge(struct graph* G, const struct edge E) { 40 | int n, from, to; 41 | n = G->V; 42 | from = E.source; 43 | to = E.destination; 44 | 45 | if (0 > from || from > n || 0 > to || to > n) return -1; 46 | 47 | struct ListNode *prev = NULL, *ptr = G->adjList[from]; 48 | while (ptr != NULL) { 49 | if (ptr->vertex == to) return 0; 50 | else { 51 | prev = ptr; 52 | ptr = ptr->next; 53 | } 54 | } 55 | if (ptr==NULL) { 56 | struct ListNode *newNode = (struct ListNode *) malloc(sizeof(struct ListNode)); 57 | newNode->vertex = to; 58 | newNode->next = NULL; 59 | 60 | if (prev == NULL) { 61 | G->adjList[from] = newNode; 62 | } else { 63 | prev->next = newNode; 64 | } 65 | } 66 | return 1; 67 | } 68 | 69 | int removeEdge(struct graph* G, const struct edge E) { 70 | int n, from, to; 71 | n = G->V; 72 | from = E.source; 73 | to = E.destination; 74 | if (0 > from || from > n || 0 > to || to > n) return -1; 75 | struct ListNode *prev = NULL, *ptr = G->adjList[from]; 76 | while (ptr != NULL) { 77 | if (ptr->vertex == to) { 78 | if (prev == NULL) { 79 | G->adjList[from] = ptr->next; 80 | free(ptr); 81 | } else { 82 | prev->next = ptr->next; 83 | free(ptr); 84 | } 85 | return 1; 86 | } else { 87 | prev = ptr; 88 | ptr = ptr->next; 89 | } 90 | } 91 | return 0; 92 | } 93 | 94 | struct graph* createGraph(const int numVertices) { 95 | assert(numVertices >= 0); 96 | // Create an empty graph with numVertices 97 | int i, j; 98 | struct graph* G = (struct graph *) malloc(sizeof( struct graph)); 99 | assert(G != NULL); 100 | G->V = numVertices; 101 | G->E = 0; 102 | 103 | // allocate memory for each column and initialise with 0 104 | struct ListNode *newNode, *last; 105 | for (int i = 0; i < G->V; i++) { 106 | G->adjList[i] = (struct ListNode *) malloc(sizeof(struct ListNode)); 107 | assert(G->adjList[i] != NULL); 108 | G->adjList[i]->vertex = i; 109 | G->adjList[i]->next = NULL; 110 | } 111 | return G; 112 | } 113 | 114 | struct edge newEdge(int x, int y){ 115 | // return an edge with ends x and y 116 | struct edge e; 117 | e.source = x; 118 | e.destination = y; 119 | return e; 120 | } 121 | 122 | struct graph* randomGraph(const int N, const float p){ 123 | // A random graph with N vertices and probability p for each edge 124 | int i, j; 125 | struct edge E; 126 | struct graph* G = createGraph(N); 127 | rand_init(); 128 | for (i=0; i < N; i++) for(j=i+1; j < N; j++) { 129 | if (rand() < p * RAND_MAX) { // rand() returns an integer between 0 and RAND_MAX 130 | E = newEdge(i,j); 131 | insertEdge(G, E); 132 | } 133 | } 134 | return G; 135 | } 136 | 137 | void displayGraph(struct graph* G) { 138 | struct ListNode *ptr; 139 | int i; 140 | for (i = 0; i < G->V; i++) { 141 | ptr = G->adjList[i]; 142 | printf("\nnode %d neighbors:", i); 143 | while (ptr != NULL) { 144 | printf(" %d", ptr->vertex); 145 | ptr = ptr->next; 146 | } 147 | } 148 | } 149 | 150 | void destroyGraph(struct graph* G) { 151 | int i; 152 | struct ListNode *temp, *ptr; 153 | for (i = 0; i < G->V; i++) { 154 | ptr = G->adjList[i]; 155 | while (ptr != NULL) { 156 | temp = ptr; 157 | ptr = ptr->next; 158 | free(temp); 159 | } 160 | G->adjList[i] = NULL; 161 | } 162 | printf("\nGraph is deleted"); 163 | } 164 | 165 | void DFS_iterative(struct graph* G, int visited[], int start){ 166 | int stack[G->V]; 167 | int top = -1, i; 168 | visited[start] = 1; 169 | stack[++top] = start; 170 | struct ListNode *p = NULL; 171 | while (top != -1) { 172 | start = stack[top--]; 173 | printf("%d ", start); 174 | p = G->adjList[start]; 175 | while (p) { 176 | i = p->vertex; 177 | if (visited[i] == 0) { 178 | stack[++top] = i; 179 | visited[i] = 1; 180 | } 181 | p = p->next; 182 | } 183 | } 184 | } 185 | 186 | void DFS_recursive(struct graph* G, int visited[], int start){ 187 | int i; 188 | struct ListNode *p = NULL; 189 | visited[start] = 1; 190 | printf("%d ", start); 191 | p = G->adjList[start]; 192 | while (p) { 193 | i = p->vertex; 194 | if (visited[i] == 0) { 195 | DFS_recursive(G, visited, i); 196 | } 197 | p = p->next; 198 | } 199 | } 200 | 201 | int main(int argc, char *args[]) { 202 | // Test code 203 | struct edge E; 204 | int n = 10; 205 | struct graph* G = randomGraph(n, 0.15); 206 | displayGraph(G); 207 | 208 | // initialization of visited array 209 | int i; 210 | int visited[n]; 211 | for (i = 0; i < n; i++) visited[i] = 0; 212 | printf("\nDFS recursive order:\n"); 213 | // DFS start from 0 214 | DFS_recursive(G, visited, 0); 215 | printf("\nvisited by DFS:\n"); 216 | for (i=0; i 7 | using namespace std ; 8 | class Graph 9 | { 10 | public : 11 | int V ; 12 | list *adj ; 13 | Graph(int V); 14 | void add_edge( int u , int v); 15 | void print_graph(); 16 | }; 17 | 18 | Graph::Graph( int V ) 19 | { 20 | this -> V = V ; 21 | this -> adj = new list [V] ; 22 | } 23 | 24 | void Graph::add_edge( int u , int v) 25 | { 26 | this -> adj[u].push_back(v); 27 | } 28 | 29 | void Graph::print_graph() 30 | { 31 | cout << "The Graph formed is : " << endl ; 32 | for ( int i = 0 ; i < this -> V ; i++ ) 33 | { 34 | cout << i << " -> " ; 35 | for ( auto it = this -> adj[i].begin() ; it != this -> adj[i].end() ; it++ ) 36 | { 37 | cout << *it << " " ; 38 | } 39 | cout << endl ; 40 | } 41 | } 42 | 43 | int main () 44 | { 45 | Graph graph(4); 46 | graph.add_edge(0, 1); 47 | graph.add_edge(0, 2); 48 | graph.add_edge(1, 2); 49 | graph.add_edge(2, 0); 50 | graph.add_edge(2, 3); 51 | graph.add_edge(3, 3); 52 | graph.print_graph(); 53 | return 0; 54 | } 55 | -------------------------------------------------------------------------------- /src/Chapter_09_Graph_Algorithms/GraphUsingAdjacencyMatrix.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Author : Shivam Chauhan 3 | Date : March 28 , 2019 4 | Graph using Adjacency Matrix 5 | */ 6 | #include 7 | using namespace std ; 8 | class Graph 9 | { 10 | public : 11 | int V ; 12 | int *adj_mat; 13 | Graph(int V); 14 | void add_edge( int u , int v); 15 | void print_graph(); 16 | }; 17 | 18 | Graph::Graph( int V ) 19 | { 20 | this -> V = V ; 21 | /* 22 | Using 1-D array as 2-D in place of arr[i][j] -> arr[ i * row_size + j ] is used 23 | */ 24 | adj_mat = new int[V*V](); // default initialise array with 0 , don't use (0) 25 | 26 | } 27 | 28 | void Graph::add_edge( int u , int v) 29 | { 30 | adj_mat[u * V + v] = 1 ; 31 | } 32 | 33 | void Graph::print_graph() 34 | { 35 | cout << "The Graph formed is : " << endl ; 36 | for ( int i = 0 ; i < this -> V ; i++ ) 37 | { 38 | for ( int j = 0 ; j < this -> V ; j++ ) 39 | { 40 | cout << this -> adj_mat[i*V+j] << " " ; 41 | } 42 | cout << endl ; 43 | } 44 | } 45 | 46 | int main () 47 | { 48 | Graph graph(4); 49 | graph.add_edge(0, 1); 50 | graph.add_edge(0, 2); 51 | graph.add_edge(1, 2); 52 | graph.add_edge(2, 0); 53 | graph.add_edge(2, 3); 54 | graph.add_edge(3, 3); 55 | graph.print_graph(); 56 | return 0; 57 | } 58 | -------------------------------------------------------------------------------- /src/Chapter_09_Graph_Algorithms/TopologicalSort.c: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2008 CareerMonk Publications and others. 2 | // E-Mail : info@careermonk.com 3 | // Creation Date : 2008-01-10 06:15:46 4 | // Created by : Narasimha Karumanchi 5 | // Book Title : Data Structures And Algorithms Made Easy 6 | // Warranty : This software is provided "as is" without any 7 | // warranty; without even the implied warranty of 8 | // merchantability or fitness for a particular purpose. 9 | #include 10 | #include 11 | #include 12 | #include 13 | #define MAX_VERTICES 50 // max number of vertices for our graph 14 | #define MAX_DEGREE 50 // max degree for a vertex 15 | 16 | struct graph{ 17 | int V; // number of vertices 18 | int E; // number of edges 19 | int **adjMatrix; // adjacency matrix 20 | }; 21 | 22 | struct edge{ 23 | int source; 24 | int destination; 25 | }; 26 | 27 | void rand_init(void){ 28 | // Initializes the random generator rand() 29 | time_t t; 30 | srand((unsigned) time(&t)); 31 | } 32 | 33 | struct graph* createGraph(const int numVertices){ 34 | assert(numVertices >= 0); 35 | // Create an empty graph with numVertices 36 | int i, j; 37 | struct graph* G = (struct graph *) malloc(sizeof( struct graph)); 38 | G->V = numVertices; 39 | G->E = 0; 40 | // allocate memory for each row 41 | G->adjMatrix = malloc(numVertices * sizeof(int *)); 42 | assert(G != NULL); 43 | // allocate memory for each column and initialise with 0 44 | for (i = 0; i < numVertices; i++) { 45 | G->adjMatrix[i] = calloc(numVertices, sizeof(int)); 46 | assert(G->adjMatrix[i] != NULL); 47 | } 48 | return G; 49 | } 50 | 51 | void displayGraph(const struct graph* G){ 52 | // Display the graph (adjMatrix) 53 | int i, j, v; 54 | v = G->V; 55 | printf("%d vertices; %d edges.\n", G->V, G->E); 56 | for(i=0; i< v; i++){ 57 | for(j=0; j < v; j++) printf("%3d ",(G->adjMatrix)[i][j]); 58 | printf("\n"); 59 | } 60 | } 61 | 62 | void displayEdges(const struct graph* G){ 63 | int v,i,j; 64 | v = G->V; 65 | for(i=0; i < v; i++){ 66 | for(j=i+1; j < v; j++){ 67 | if(G->adjMatrix[i][j]==1) printf("%d-%d ",i,j); 68 | } 69 | } 70 | } 71 | 72 | void insertEdge(struct graph* G, const struct edge E){ 73 | int v, x, y; 74 | v = G->V; 75 | x = E.source; 76 | y = E.destination; 77 | if(x >= v || y >= v) { 78 | printf("Error when adding edge."); 79 | exit(EXIT_FAILURE); 80 | } 81 | if (G->adjMatrix[x][y] == 0){ // For undirected graphs set both the bits 82 | G->adjMatrix[x][y] = 1; 83 | (G->E)++; 84 | } 85 | } 86 | 87 | void removeEdge(struct graph* G, const struct edge E){ 88 | int v, x, y; 89 | v = G->V; 90 | x = E.source; 91 | y = E.destination; 92 | if(x >= v || y >= v) { 93 | printf("Error when deleting edge."); 94 | exit(EXIT_FAILURE); 95 | } 96 | if (G->adjMatrix[x][y] == 1){ 97 | G->adjMatrix[x][y] = 0; 98 | G->adjMatrix[y][x] = 0; 99 | (G->E)--; 100 | } 101 | } 102 | 103 | void destroyGraph(struct graph* G){ // to free memory 104 | if (G){ 105 | if (G->adjMatrix){ 106 | int i; 107 | for (i = 0; i < G->V; i++) 108 | free(G->adjMatrix[i]); 109 | free(G->adjMatrix); 110 | } 111 | free(G); 112 | } 113 | } 114 | 115 | struct edge newEdge(int x, int y){ 116 | // return an edge with ends x and y 117 | struct edge e; 118 | e.source = x; 119 | e.destination = y; 120 | return e; 121 | } 122 | 123 | struct graph* randomGraph(const int N, const float p){ 124 | // A random graph with N vertices and probability p for each edge 125 | int i, j; 126 | struct edge E; 127 | struct graph* G = createGraph(N); 128 | rand_init(); 129 | for (i=0; i < N; i++) for(j=i+1; j < N; j++) { 130 | if (rand() < p * RAND_MAX) { // rand() returns an integer between 0 and RAND_MAX 131 | E = newEdge(i,j); 132 | insertEdge(G, E); 133 | } 134 | } 135 | return G; 136 | } 137 | 138 | int queue[MAX_VERTICES], front = -1, rear = -1; 139 | 140 | int findIndegree(struct graph* G, int node) { 141 | int i, indegree = 0; 142 | for (i = 0; i < G->V; i++) { 143 | if (G->adjMatrix[i][node] == 1) 144 | indegree++; 145 | } 146 | return indegree; 147 | } 148 | 149 | void insertQueue(int node) { 150 | if (rear == MAX_VERTICES) 151 | printf("\nOVERFLOW "); 152 | else { 153 | if (front == -1) /*If queue is initially empty */ 154 | front = 0; 155 | queue[++rear] = node; 156 | } 157 | } 158 | 159 | int deleteQueue() { 160 | int del_node; 161 | if (front == -1 || front > rear) { 162 | printf("\nUNDERFLOW %d %d", front, rear); 163 | return -1; 164 | } else { 165 | del_node = queue[front++]; 166 | return del_node; 167 | } 168 | } 169 | 170 | void topologicalSort( struct graph *G ) { 171 | int topsort[G->V], indeg[G->V]; 172 | 173 | /*Find the in-degree of each node*/ 174 | int i; 175 | for (i = 0; i < G->V; i++) { 176 | indeg[i] = findIndegree(G, i); 177 | if (indeg[i] == 0) 178 | insertQueue(i); 179 | } 180 | 181 | int j=0; 182 | int del_node; 183 | while (front <= rear){ /*Continue loop until queue is empty */ 184 | del_node = deleteQueue(); 185 | topsort[j] = del_node; /*Add the deleted node to topsort*/ 186 | j++; 187 | 188 | /*Delete the del_node edges */ 189 | for (i = 0; i < G->V; i++) { 190 | if (G->adjMatrix[del_node][i] == 1) { 191 | G->adjMatrix[del_node][i] = 0; 192 | indeg[i] = indeg[i] - 1; 193 | if (indeg[i] == 0) 194 | insertQueue(i); 195 | } 196 | } 197 | } 198 | 199 | printf("The topological sorting can be given as:\n"); 200 | for (i=0; i 11 | using namespace std; 12 | void sortedSquaredArray(int A[], int n) { 13 | int result[n]; 14 | for (int i = 0; i < n; ++i) 15 | result[i] = A[i] * A[i]; 16 | 17 | sort(result, result+n); 18 | 19 | cout << "\nSorted squares array " << endl; 20 | for (int i = 0 ; i < n ; i++) 21 | cout << result[i] << " " ; 22 | } 23 | 24 | int main(){ 25 | int A[] = { -4, -3, -1, 3, 4, 5 }; 26 | int n = sizeof(A)/sizeof(A[0]); 27 | 28 | cout << "Given sorted array " << endl; 29 | for (int i = 0; i < n; i++) 30 | cout << A[i] << " " ; 31 | sortedSquaredArray(A, n); 32 | return 0; 33 | } 34 | -------------------------------------------------------------------------------- /src/Chapter_10_Sorting/SortedSquaredArray2.cpp: -------------------------------------------------------------------------------- 1 | /*Copyright (c) 2016 CareerMonk Publications and others. 2 | #E-Mail : info@careermonk.com 3 | #Creation Date : 2008-01-10 06:15:46 4 | #Created by : Narasimha Karumanchi 5 | #Book Title : Data Structures And Algorithms Made Easy 6 | #Warranty : This software is provided "as is" without any 7 | # warranty; without even the implied warranty of 8 | # merchantability or fitness for a particular purpose.*/ 9 | 10 | #include 11 | using namespace std; 12 | void sortedSquaredArray(int A[], int n) { 13 | int result[n]; 14 | int j = 0; 15 | // Find the last index of the negative numbers 16 | while (j < n && A[j] < 0) 17 | j++; 18 | 19 | // i points to the last index of negative numbers 20 | int i = j-1; 21 | 22 | int t = 0; 23 | // j points to the first index of the positive numbers 24 | while (i >= 0 && j < n) { 25 | if (A[i] * A[i] < A[j] * A[j]) { 26 | result[t++] = A[i] * A[i]; 27 | i--; 28 | } else { 29 | result[t++] = A[j] * A[j]; 30 | j++; 31 | } 32 | } 33 | // add the remaining negative numbers squares to result 34 | while (i >= 0) { 35 | result[t++] = A[i] * A[i]; 36 | i--; 37 | } 38 | 39 | // add the remaining positive numbers squares to result 40 | while (j < n) { 41 | result[t++] = A[j] * A[j]; 42 | j++; 43 | } 44 | cout << "\nSorted squares array " << endl; 45 | for (int i = 0 ; i < n ; i++) 46 | cout << result[i] << " " ; 47 | } 48 | 49 | int main(){ 50 | int A[] = { -4, -3, -1, 3, 4, 5 }; 51 | int n = sizeof(A)/sizeof(A[0]); 52 | 53 | cout << "Given sorted array " << endl; 54 | for (int i = 0; i < n; i++) 55 | cout << A[i] << " " ; 56 | sortedSquaredArray(A, n); 57 | return 0; 58 | } 59 | -------------------------------------------------------------------------------- /src/Chapter_10_Sorting/bubbleSort.c: -------------------------------------------------------------------------------- 1 | /*Copyright (c) 2008 CareerMonk Publications and others. 2 | #E-Mail : info@careermonk.com 3 | #Creation Date : 2008-01-10 06:15:46 4 | #Created by : Narasimha Karumanchi 5 | #Book Title : Data Structures And Algorithms Made Easy 6 | #Warranty : This software is provided "as is" without any 7 | # warranty; without even the implied warranty of 8 | # merchantability or fitness for a particular purpose.*/ 9 | 10 | // Bubble Sort in C 11 | #include 12 | 13 | void bubbleSortImproved(int data[], int size) { 14 | int pass, i, temp, swapped = 1; 15 | for (pass = size - 1; pass >= 0 && swapped; pass--) { 16 | swapped = 0; 17 | for (i = 0; i <= pass - 1 ; i++) { 18 | if(data[i] > data[i+1]) { 19 | // swap elements 20 | temp = data[i]; 21 | data[i] = data[i+1]; 22 | data[i+1] = temp; 23 | swapped = 1; 24 | } 25 | } 26 | } 27 | } 28 | 29 | void bubbleSort(int data[], int size){ 30 | for(int step=0; step to <. 33 | if (data[i]>data[i+1]){ 34 | int temp = data[i]; 35 | data[i] = data[i+1]; 36 | data[i+1]= temp; 37 | } 38 | } 39 | } 40 | } 41 | void printArray(int data[], int size){ 42 | for(int i=0; i 12 | 13 | void insertionSort(int data[], int size) { 14 | int i, j, key; 15 | for (i = 1; i <= size - 1; i++) { 16 | key = data[i]; 17 | j = i; 18 | while (j >= 1 && data[j-1] > key) { 19 | data[j] = data[j-1]; 20 | j--; 21 | } 22 | data[j] = key; 23 | } 24 | } 25 | 26 | 27 | void printArray(int data[], int size){ 28 | for(int i=0; i 12 | 13 | int MinIndex(int A[], int N) 14 | { 15 | int min = A[0], minindex = 0; 16 | 17 | for (int i = 1; i < N; i++) 18 | { 19 | if (min > A[i]) 20 | { 21 | min = A[i]; 22 | minindex = i; 23 | } 24 | } 25 | return minindex; 26 | } 27 | 28 | void sort(int A[], int N) 29 | { 30 | int t, minindex = MinIndex(A, N); 31 | 32 | if (N > 1) 33 | { 34 | t = A[0]; 35 | A[0] = A[minindex]; 36 | A[minindex] = t; 37 | 38 | sort(&A[1], N - 1); 39 | } 40 | } 41 | 42 | void main() 43 | { 44 | int N; 45 | 46 | printf("Enter N numbers to sort: "); 47 | scanf("%d", &N); 48 | 49 | int A[N]; 50 | 51 | for (int i = 0; i < N; i++) 52 | scanf("%d", &A[i]); 53 | 54 | sort(A, N); 55 | 56 | for (int i = 0; i < N; i++) 57 | printf("%d ", A[i]); 58 | 59 | printf("\n"); 60 | } 61 | -------------------------------------------------------------------------------- /src/Chapter_11_Searching/BinarySearch.c: -------------------------------------------------------------------------------- 1 | /*Copyright (c) 2016 CareerMonk Publications and others. 2 | #E-Mail : info@careermonk.com 3 | #Creation Date : 2008-01-10 06:15:46 4 | #Created by : Narasimha Karumanchi 5 | #Book Title : Data Structures And Algorithms Made Easy 6 | #Warranty : This software is provided "as is" without any 7 | # warranty; without even the implied warranty of 8 | # merchantability or fitness for a particular purpose.*/ 9 | 10 | #include 11 | #include 12 | 13 | //Iterative Binary Search Algorithm 14 | int binarySearchIterative(int A[], int n, int data) { 15 | int mid; 16 | int low = 0; 17 | int high = n-1; 18 | while (low <= high) { 19 | mid = low + (high-low)/2; //To avoid overflow 20 | if(A[mid] == data) 21 | return mid; 22 | else if(A[mid] < data) 23 | low = mid + 1; 24 | else high = mid - 1; 25 | } 26 | return -1; 27 | } 28 | 29 | //Recursive Binary Search Algorithm 30 | int binarySearchRecursive(int A[], int low, int high, int data) { 31 | int mid = low + (high-low)/2; //To avoid overflow 32 | if (low>high) 33 | return -1; 34 | if(A[mid] == data) 35 | return mid; 36 | else if(A[mid] < data) 37 | return binarySearchRecursive (A, mid + 1, high, data); 38 | else return binarySearchRecursive (A, low, mid - 1 , data); 39 | return -1; 40 | } 41 | 42 | void binarySearch_test(){ 43 | int n, data, A[10]={3,6,19,25,33,39,55,78,99,100}; 44 | n =10; 45 | data =20; 46 | printf("\nElement %d is at location: %d (-1 indicates not present in array)", data, binarySearchIterative(A, n, data)); 47 | printf("\nElement %d is at location: %d (-1 indicates not present in array)", data, binarySearchRecursive(A, 0, n-1, data)); 48 | data =39; 49 | printf("\nElement %d is at location: %d (-1 indicates not present in array)", data, binarySearchIterative(A, n, data)); 50 | printf("\nElement %d is at location: %d (-1 indicates not present in array)", data, binarySearchRecursive(A, 0, n-1, data)); 51 | 52 | } 53 | 54 | -------------------------------------------------------------------------------- /src/Chapter_11_Searching/InterpolationSearch.c: -------------------------------------------------------------------------------- 1 | /*Copyright (c) 2016 CareerMonk Publications and others. 2 | #E-Mail : info@careermonk.com 3 | #Creation Date : 2008-01-10 06:15:46 4 | #Created by : Narasimha Karumanchi 5 | #Book Title : Data Structures And Algorithms Made Easy 6 | #Warranty : This software is provided "as is" without any 7 | # warranty; without even the implied warranty of 8 | # merchantability or fitness for a particular purpose.*/ 9 | 10 | #include 11 | 12 | int interpolationSearch(int A[], int n, int data) { 13 | int low = 0, mid, high = n-1; 14 | while (low <= high) { 15 | mid = low + (((data - A[low]) * (high - low))/(A[high] - A[low])); 16 | if (data == A[mid]) 17 | return mid + 1; 18 | if (data < A[mid]) 19 | high = mid - 1; 20 | else 21 | low = mid + 1; 22 | } 23 | return -1; 24 | } 25 | void interpolationSearch_test(){ 26 | int n, data, A[10]={3,6,9,12,15,18,21,24,27,30}; 27 | n =10; 28 | data =20; 29 | printf("\nElement %d is at location: %d (-1 indicates not present in array)", data, interpolationSearch(A, n, data)); 30 | data =30; 31 | printf("\nElement %d is at location: %d (-1 indicates not present in array)", data, interpolationSearch(A, n, data)); 32 | } 33 | -------------------------------------------------------------------------------- /src/Chapter_11_Searching/OrderedLinearSearch.c: -------------------------------------------------------------------------------- 1 | /*Copyright (c) 2016 CareerMonk Publications and others. 2 | #E-Mail : info@careermonk.com 3 | #Creation Date : 2008-01-10 06:15:46 4 | #Created by : Narasimha Karumanchi 5 | #Book Title : Data Structures And Algorithms Made Easy 6 | #Warranty : This software is provided "as is" without any 7 | # warranty; without even the implied warranty of 8 | # merchantability or fitness for a particular purpose.*/ 9 | 10 | 11 | int orderedLinearSearch(int A[], int n, int data) { 12 | for (int i = 0; i < n; i++) { 13 | if(A[i] == data) 14 | return i; 15 | else if(A[i] > data) 16 | return -1; 17 | } 18 | return -1; 19 | } 20 | 21 | void orderedLinearSearch_test(){ 22 | int n, data, A[10]={3,6,19,25,33,39,55,78,99,100}; 23 | n =10; 24 | data =20; 25 | printf("\nElement %d is at location: %d (-1 indicates not present in array)", data, orderedLinearSearch(A, n, data)); 26 | data =39; 27 | printf("\nElement %d is at location: %d (-1 indicates not present in array)", data, orderedLinearSearch(A, n, data)); 28 | 29 | } -------------------------------------------------------------------------------- /src/Chapter_11_Searching/UnorderedLinearSearch.c: -------------------------------------------------------------------------------- 1 | /*Copyright (c) 2016 CareerMonk Publications and others. 2 | #E-Mail : info@careermonk.com 3 | #Creation Date : 2008-01-10 06:15:46 4 | #Created by : Narasimha Karumanchi 5 | #Book Title : Data Structures And Algorithms Made Easy 6 | #Warranty : This software is provided "as is" without any 7 | # warranty; without even the implied warranty of 8 | # merchantability or fitness for a particular purpose.*/ 9 | 10 | 11 | int unorderedLinearSearch(int A[], int n, int data) { 12 | for (int i = 0; i < n; i++) { 13 | if(A[i] == data) 14 | return i; 15 | } 16 | return -1; 17 | } 18 | 19 | void unorderedLinearSearch_test(){ 20 | int n, data, A[10]={3,6,19,25,33,39,55,78,99,100}; 21 | n =10; 22 | data =20; 23 | printf("\nElement %d is at location: %d (-1 indicates not present in array)", data, unorderedLinearSearch(A, n, data)); 24 | data =39; 25 | printf("\nElement %d is at location: %d (-1 indicates not present in array)", data, unorderedLinearSearch(A, n, data)); 26 | 27 | } -------------------------------------------------------------------------------- /src/Chapter_14_Hashing/LinearChainingImplementation.c: -------------------------------------------------------------------------------- 1 | /*Copyright (c) 2016 CareerMonk Publications and others. 2 | #E-Mail : info@careermonk.com 3 | #Creation Date : 2008-01-10 06:15:46 4 | #Created by : Narasimha Karumanchi 5 | #Book Title : Data Structures And Algorithms Made Easy 6 | #Warranty : This software is provided "as is" without any 7 | # warranty; without even the implied warranty of 8 | # merchantability or fitness for a particular purpose.*/ 9 | 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | 16 | /* elements */ 17 | struct element { 18 | int key; /* key */ 19 | int value; /* data */ 20 | }; 21 | typedef struct element* element; 22 | 23 | struct list { 24 | element data; 25 | struct list* next; 26 | }; 27 | typedef struct list* list; 28 | /* linked lists may be NULL (= end of list) and we do not check for circularity */ 29 | 30 | struct chain { 31 | list list; 32 | }; 33 | 34 | /* Chains, implemented as linked lists */ 35 | typedef struct chain* chain; 36 | 37 | struct table { 38 | int capacity; 39 | int size; 40 | chain* buckets; 41 | }; 42 | 43 | /* Hash table interface */ 44 | typedef struct table* table; 45 | table newHashTable (int capacity); 46 | element put(table H, element e); 47 | element get(table H, int key); 48 | void deleteHashTable(table H); 49 | chain newChain (); 50 | element insertInChain(table H, chain C, element e); 51 | element searchInChain(table H, chain C, int key); 52 | void deleteChain(chain C); 53 | 54 | void* xmalloc(size_t capacity) { 55 | void* p = malloc(capacity); 56 | if (p == NULL) { 57 | fprintf(stderr, "allocation failed\n"); 58 | abort(); 59 | } 60 | return p; 61 | } 62 | 63 | void* xcalloc(size_t nobj, size_t capacity) { 64 | void* p = calloc(nobj, capacity); 65 | if (p == NULL) { 66 | fprintf(stderr, "allocation failed\n"); 67 | abort(); 68 | } 69 | return p; 70 | } 71 | 72 | void deleteList(list p) { 73 | list q; 74 | while (p != NULL) { 75 | if (p->data != NULL) 76 | /* free element, if such a function is supplied */ 77 | free(p->data); 78 | q = p->next; 79 | free(p); 80 | p = q; 81 | } 82 | } 83 | 84 | chain newChain(){ 85 | chain C = xmalloc(sizeof(struct chain)); 86 | C->list = NULL; 87 | return C; 88 | } 89 | 90 | // findInChain(p, key) returns list element whosecdata field has key key, or NULL if none exists 91 | list findInChain(table H, chain C, int key){ 92 | list p = C->list; 93 | while (p != NULL) { 94 | if (key == p->data->key) 95 | return p; 96 | p = p->next; 97 | } 98 | return NULL; 99 | } 100 | 101 | element insertInChain(table H, chain C, element e){ 102 | list p = findInChain(H, C, e->key); 103 | if (p == NULL) { 104 | /* insert new element at the beginning */ 105 | list new_item = xmalloc(sizeof(struct list)); 106 | new_item->data = e; 107 | new_item->next = C->list; 108 | C->list = new_item; 109 | return NULL; /* did not overwrite entry */ 110 | } else { 111 | /* overwrite existing entry with given key */ 112 | element oldElement = p->data; 113 | p->data = e; 114 | return oldElement; /* return old entry */ 115 | } 116 | } 117 | 118 | element searchInChain(table H, chain C, int key){ 119 | list p = findInChain(H, C, key); 120 | if (p == NULL) return NULL; 121 | else return p->data; 122 | } 123 | 124 | void deleteChain(chain C){ 125 | deleteList(C->list); 126 | free(C); 127 | } 128 | 129 | /* hash function */ 130 | int hash(int key, int capacity){ 131 | return key % capacity; 132 | } 133 | 134 | /* Hash table implementation */ 135 | table newHashTable(int capacity){ 136 | chain* A = xcalloc(capacity, sizeof(chain)); 137 | table H = xmalloc(sizeof(struct table)); 138 | H->capacity = capacity; 139 | H->size = 0; 140 | H->buckets = A; /* all initialized to NULL; */ 141 | return H; 142 | } 143 | 144 | element put(table H, element e){ 145 | element oldElement; 146 | int key = e->key; 147 | int h = hash(key, H->capacity); 148 | if (H->buckets[h] == NULL) 149 | H->buckets[h] = newChain(); 150 | oldElement = insertInChain(H, H->buckets[h], e); 151 | if (oldElement != NULL) return oldElement; 152 | H->size++; 153 | return NULL; 154 | } 155 | 156 | element get(table H, int key){ 157 | int h = hash(key, H->capacity); 158 | if (H->buckets[h] == NULL) return NULL; 159 | element e = searchInChain(H, H->buckets[h], key); 160 | return e; 161 | } 162 | 163 | void deleteHashTable(table H){ 164 | int i; 165 | for (i = 0; i < H->capacity; i++) { 166 | chain C = H->buckets[i]; 167 | if (C != NULL) deleteChain(C); 168 | } 169 | free(H->buckets); 170 | free(H); 171 | } 172 | 173 | void deleteElement(element e) { 174 | free(e); 175 | } 176 | 177 | int main () { 178 | int n = 100; 179 | int capacity = 5; 180 | int num_tests = 5; 181 | int i; int j; 182 | 183 | printf("Testing buckets of capacity %d with %d values, %d times\n", capacity, n, num_tests); 184 | for (j = 0; j < num_tests; j++) { 185 | table H = newHashTable(capacity); 186 | for (i = 0; i < n; i++) { 187 | element e = xmalloc(sizeof(struct element)); 188 | e->key = j*n+i; 189 | e->value = j*n+i; 190 | put(H, e); 191 | } 192 | for (i = 0; i < n; i++) { 193 | int key = j*n+i; 194 | assert(((element)get(H, key))->value == j*n+i); /* "missed existing element" */ 195 | } 196 | for (i = 0; i < n; i++) { 197 | int key = (j+1)*n+i; 198 | assert(get(H, key) == NULL); /* "found nonexistent element" */ 199 | } 200 | deleteHashTable(H); 201 | } 202 | printf("All tests passed!\n"); 203 | return 0; 204 | } 205 | -------------------------------------------------------------------------------- /src/Chapter_22_Miscellaneous_Bitwise_Hacking/CountingNumberofOnesIn1toN.c: -------------------------------------------------------------------------------- 1 | /*Copyright (c) 2016 CareerMonk Publications and others. 2 | #E-Mail : info@careermonk.com 3 | #Creation Date : 2008-01-10 06:15:46 4 | #Created by : Narasimha Karumanchi 5 | #Book Title : Data Structures And Algorithms Made Easy 6 | #Warranty : This software is provided "as is" without any 7 | # warranty; without even the implied warranty of 8 | # merchantability or fitness for a particular purpose.*/ 9 | 10 | int countingNumberofOnesIn1toN(unsigned int n){ 11 | int count =0; 12 | int i = 0, j; 13 | for (i = 1; i <= n; i++){ 14 | j = i; 15 | while(j){ 16 | j = j & (j-1); 17 | count++; 18 | } 19 | } 20 | return count; 21 | } 22 | void countingNumberofOnesIn1toN_test(){ 23 | int n=5; 24 | printf("Number of set bits in all numbers from 1 to %d is/are %d\n",n, countingNumberofOnesIn1toN(n)); 25 | n = 5; 26 | printf("Number of set bits in all numbers from 1 to %d is/are %d\n",n, countingNumberofOnesIn1toN(n)); 27 | n = 100; 28 | printf("Number of set bits in all numbers from 1 to %d is/are %d\n",n, countingNumberofOnesIn1toN(n)); 29 | n = 1; 30 | printf("Number of set bits in all numbers from 1 to %d is/are %d\n",n, countingNumberofOnesIn1toN(n)); 31 | n = 0; 32 | printf("Number of set bits in all numbers from 1 to %d is/are %d\n",n, countingNumberofOnesIn1toN(n)); 33 | } -------------------------------------------------------------------------------- /src/Chapter_22_Miscellaneous_Bitwise_Hacking/CountingNumberofOneswithBitwiseAND.c: -------------------------------------------------------------------------------- 1 | /*Copyright (c) 2016 CareerMonk Publications and others. 2 | #E-Mail : info@careermonk.com 3 | #Creation Date : 2008-01-10 06:15:46 4 | #Created by : Narasimha Karumanchi 5 | #Book Title : Data Structures And Algorithms Made Easy 6 | #Warranty : This software is provided "as is" without any 7 | # warranty; without even the implied warranty of 8 | # merchantability or fitness for a particular purpose.*/ 9 | 10 | #include 11 | 12 | int countingNumberofOneswithBitwiseAND(unsigned int n){ 13 | int count =0; 14 | while(n){ 15 | if(n&1){ 16 | count++; 17 | } 18 | n=n>>1; 19 | } 20 | return count; 21 | } 22 | void countingNumberofOneswithBitwiseAND_test(){ 23 | int i=10; 24 | printf("Number of one's in %d is/are %d\n",i, countingNumberofOneswithBitwiseAND(i)); 25 | i = 5; 26 | printf("Number of one's in %d is/are %d\n",i, countingNumberofOneswithBitwiseAND(i)); 27 | i = 100; 28 | printf("Number of one's in %d is/are %d\n",i, countingNumberofOneswithBitwiseAND(i)); 29 | i = 1; 30 | printf("Number of one's in %d is/are %d\n",i, countingNumberofOneswithBitwiseAND(i)); 31 | i = 0; 32 | printf("Number of one's in %d is/are %d\n",i, countingNumberofOneswithBitwiseAND(i)); 33 | } 34 | -------------------------------------------------------------------------------- /src/Chapter_22_Miscellaneous_Bitwise_Hacking/CountingNumberofOneswithModuloOperator.c: -------------------------------------------------------------------------------- 1 | /*Copyright (c) 2016 CareerMonk Publications and others. 2 | #E-Mail : info@careermonk.com 3 | #Creation Date : 2008-01-10 06:15:46 4 | #Created by : Narasimha Karumanchi 5 | #Book Title : Data Structures And Algorithms Made Easy 6 | #Warranty : This software is provided "as is" without any 7 | # warranty; without even the implied warranty of 8 | # merchantability or fitness for a particular purpose.*/ 9 | 10 | int countingNumberofOneswithModuloOperator(unsigned int n){ 11 | int count =0; 12 | while(n){ 13 | if(n%2 == 1){ 14 | count++; 15 | } 16 | n=n/2; 17 | } 18 | return count; 19 | } 20 | void countingNumberofOneswithModuloOperator_test(){ 21 | int i=10; 22 | printf("Number of one's in %d is/are %d\n",i, countingNumberofOneswithModuloOperator(i)); 23 | i = 5; 24 | printf("Number of one's in %d is/are %d\n",i, countingNumberofOneswithModuloOperator(i)); 25 | i = 100; 26 | printf("Number of one's in %d is/are %d\n",i, countingNumberofOneswithModuloOperator(i)); 27 | i = 1; 28 | printf("Number of one's in %d is/are %d\n",i, countingNumberofOneswithModuloOperator(i)); 29 | i = 0; 30 | printf("Number of one's in %d is/are %d\n",i, countingNumberofOneswithModuloOperator(i)); 31 | } -------------------------------------------------------------------------------- /src/Chapter_22_Miscellaneous_Bitwise_Hacking/CountingNumberofOneswithPreprocessing.c: -------------------------------------------------------------------------------- 1 | /*Copyright (c) 2016 CareerMonk Publications and others. 2 | #E-Mail : info@careermonk.com 3 | #Creation Date : 2008-01-10 06:15:46 4 | #Created by : Narasimha Karumanchi 5 | #Book Title : Data Structures And Algorithms Made Easy 6 | #Warranty : This software is provided "as is" without any 7 | # warranty; without even the implied warranty of 8 | # merchantability or fitness for a particular purpose.*/ 9 | 10 | int table[256]; 11 | void buildTable(void){ 12 | int i; 13 | for(i = 0; i < 256; i++){ 14 | unsigned char t = i; 15 | table[i] = 0; 16 | for(int j = 0; j < 8; j++){ 17 | if(t & 1) table[i]++; 18 | t >>= 1; 19 | } 20 | } 21 | } 22 | int countingNumberofOneswithPreprocessing(unsigned int n){ 23 | int count = 0; 24 | for(; n; n >>= 4) 25 | count = count + table[n & 0xf]; 26 | return count; 27 | } 28 | void countingNumberofOneswithPreprocessing_test(){ 29 | buildTable(); 30 | int i=10; 31 | printf("Number of one's in %d is/are %d\n",i, countingNumberofOneswithPreprocessing(i)); 32 | i = 5; 33 | printf("Number of one's in %d is/are %d\n",i, countingNumberofOneswithPreprocessing(i)); 34 | i = 100; 35 | printf("Number of one's in %d is/are %d\n",i, countingNumberofOneswithPreprocessing(i)); 36 | i = 1; 37 | printf("Number of one's in %d is/are %d\n",i, countingNumberofOneswithPreprocessing(i)); 38 | i = 0; 39 | printf("Number of one's in %d is/are %d\n",i, countingNumberofOneswithPreprocessing(i)); 40 | } -------------------------------------------------------------------------------- /src/Chapter_22_Miscellaneous_Bitwise_Hacking/CountingNumberofOneswithTogglingApproach.c: -------------------------------------------------------------------------------- 1 | /*Copyright (c) 2016 CareerMonk Publications and others. 2 | #E-Mail : info@careermonk.com 3 | #Creation Date : 2008-01-10 06:15:46 4 | #Created by : Narasimha Karumanchi 5 | #Book Title : Data Structures And Algorithms Made Easy 6 | #Warranty : This software is provided "as is" without any 7 | # warranty; without even the implied warranty of 8 | # merchantability or fitness for a particular purpose.*/ 9 | 10 | int countingNumberofOneswithTogglingApproach(unsigned int n){ 11 | int count =0; 12 | while(n){ 13 | n = n & (n-1); 14 | count++; 15 | } 16 | return count; 17 | } 18 | void countingNumberofOneswithTogglingApproach_test(){ 19 | int i=10; 20 | printf("Number of one's in %d is/are %d\n",i, countingNumberofOneswithTogglingApproach(i)); 21 | i = 5; 22 | printf("Number of one's in %d is/are %d\n",i, countingNumberofOneswithTogglingApproach(i)); 23 | i = 100; 24 | printf("Number of one's in %d is/are %d\n",i, countingNumberofOneswithTogglingApproach(i)); 25 | i = 1; 26 | printf("Number of one's in %d is/are %d\n",i, countingNumberofOneswithTogglingApproach(i)); 27 | i = 0; 28 | printf("Number of one's in %d is/are %d\n",i, countingNumberofOneswithTogglingApproach(i)); 29 | } -------------------------------------------------------------------------------- /src/Chapter_22_Miscellaneous_Bitwise_Hacking/DecimaltoBinary.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void main(void){ 4 | long num, remainder, base = 1, binary = 0; 5 | 6 | num = 1910; 7 | while (num > 0){ 8 | remainder = num % 2; 9 | binary = binary + remainder * base; 10 | num = num / 2; 11 | base = base * 10; 12 | } 13 | printf("Given number is = %d\n", num); 14 | printf("Its binary equivalent is = %ld\n", binary); 15 | } 16 | -------------------------------------------------------------------------------- /src/Chapter_22_Miscellaneous_Bitwise_Hacking/DecimaltoBinary.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int main(){ 6 | long num, decimal_num, remainder, base = 1, binary = 0; 7 | 8 | num = 34; 9 | decimal_num = num; 10 | while (num > 0){ 11 | remainder = num % 2; 12 | binary = binary + remainder * base; 13 | num = num / 2; 14 | base = base * 10; 15 | } 16 | cout<<"Given number is = "<< decimal_num << endl; 17 | cout<<"Its binary equivalent is = "<< binary < 2 | using namespace std; 3 | 4 | int main() { 5 | int a[7] = {1,2,1,3,1,2,1}, i, res=0; 6 | 7 | for(i=0;i<7;i++) 8 | res^=a[i]; 9 | cout< 2 | //Note: i and j indicates the position of bits from right to left starting with 1 3 | int swapbits(int n, int i, int j){ 4 | // We can simply use the XOR operator to toggle the bits. 5 | n ^= (1 << i-1); 6 | n ^= (1 << j-1); 7 | return n; 8 | } 9 | int main(void) { 10 | int num = 34; //Binary Number: 00100010 11 | int i = 3, j = 6; 12 | printf ("\nGiven Number: %d", num); 13 | printf ("\nBinary representation of given number: 00100010"); 14 | num = swapbits (num, i, j); 15 | printf ("\nGiven Number after swapping %d and %d bits: %d", i, j, num); 16 | return 0; 17 | } 18 | -------------------------------------------------------------------------------- /src/Chapter_22_Miscellaneous_Bitwise_Hacking/SwapBits.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | //Note: i and j indicates the position of bits from right to left starting with 1 6 | int swapbits(int n, int i, int j){ 7 | // We can simply use the XOR operator to toggle the bits. 8 | n ^= (1 << i-1); 9 | n ^= (1 << j-1); 10 | return n; 11 | } 12 | 13 | int main() { 14 | int num = 34; //Binary Number: 00100010 15 | int i = 3, j = 6; 16 | cout << "Given Number: " << num << endl; 17 | cout << "Binary representation of given number: 00100010" << endl; 18 | num = swapbits (num, i, j); 19 | cout << "Given Number after swapping " << i <<" and " << j << " bits: " << num << endl; 20 | 21 | return 0; 22 | } 23 | -------------------------------------------------------------------------------- /src/Chapter_22_Miscellaneous_Bitwise_Hacking/countSetBitsMethod1.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | /* Code to find the number of 1s in binary 4 | representation of an integer. */ 5 | unsigned int countSetBitsMethod1(int n){ 6 | unsigned int count = 0; 7 | while (n) { 8 | n &= (n-1) ; 9 | count++; 10 | } 11 | return count; 12 | } 13 | 14 | /* Test Code */ 15 | int main(){ 16 | int i = 5; 17 | printf("Number of 1s in %d are %d", i, countSetBitsMethod1(i)); 18 | return 0; 19 | } 20 | -------------------------------------------------------------------------------- /src/Chapter_22_Miscellaneous_Bitwise_Hacking/isPowerof2.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | bool isPowerof2(int n){ 6 | if(!(n&(n-1))) 7 | return true; 8 | else 9 | return false; 10 | } 11 | int main() { 12 | int n=32; 13 | cout<