diff --git a/.gitignore b/.gitignore index 65cb58a..a3f6672 100644 --- a/.gitignore +++ b/.gitignore @@ -3,3 +3,4 @@ /dist/ /build/ /.gitignore/ +*.exe diff --git a/src/Chapter_02_Recursion_and_Backtracking/binaryNumber.cpp b/src/Chapter_02_Recursion_and_Backtracking/binaryNumber.cpp new file mode 100644 index 0000000..9756346 --- /dev/null +++ b/src/Chapter_02_Recursion_and_Backtracking/binaryNumber.cpp @@ -0,0 +1,29 @@ +#include +#include + +using namespace std; +void binary(int n,vector v,int i) +{ + if(i==n) + { + for(int x:v) + { + cout< v(n); + binary(n,v,0); + return 0; +} \ No newline at end of file diff --git a/src/Chapter_02_Recursion_and_Backtracking/connectedCells.cpp b/src/Chapter_02_Recursion_and_Backtracking/connectedCells.cpp new file mode 100644 index 0000000..964db79 --- /dev/null +++ b/src/Chapter_02_Recursion_and_Backtracking/connectedCells.cpp @@ -0,0 +1,51 @@ +#include +#include +using namespace std; +int getVal(vector> &a,int i,int j,int H,int L) +{ + if(i<0 || j<0 || i>=L || j>=H) + return 0; + else + return a[i][j]; +} +void connectedCells(vector> &a,int i,int j,int maxRow,int maxCol,int size,vector> &cnt,int &mxSize){ + if(i>=maxRow || j>= maxCol) + return ; + cnt[i][j]=1; + size++;//we have encountered one + mxSize=max(size,mxSize); + int directions[][2]={{-1,-1},{-1,0},{-1,+1},{0,-1},{0,+1},{+1,-1},{+1,0},{+1,+1}}; + //check its neighbours + for(int z=0;z<8;z++) + { + int new_i=i+directions[z][0]; + int new_j=j+directions[z][1]; + int val=getVal(a,new_i,new_j,maxRow,maxCol); + if(val>0 && cnt[new_i][new_j]==0){ + connectedCells(a,new_i,new_j,maxRow,maxCol,size,cnt,mxSize); + } + } + cnt[i][j]=0; +} +int maxOnes(vector> &a,int maxRow,int maxCol) +{ + int size=0; + int mxSize=0; + vector> cnt( maxRow , vector (maxCol, 0)); + 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}}; + cout< +#include +using namespace std; +void k_strings(int requiredStringLen, int givenLen,vector v,int i) +{ + //backtrack + if(i==requiredStringLen) + { + for(int x:v) + cout< a(n); + k_strings(n,3,a,0); + return 0; +} \ No newline at end of file diff --git a/src/Chapter_03_Linked_Lists/AlternatingSplit.c b/src/Chapter_03_Linked_Lists/AlternatingSplit.c new file mode 100644 index 0000000..501ae46 --- /dev/null +++ b/src/Chapter_03_Linked_Lists/AlternatingSplit.c @@ -0,0 +1,126 @@ +/*Copyright (c) 2008 CareerMonk Publications and others. +#E-Mail : info@careermonk.com +#Creation Date : 2008-01-10 06:15:46 +#Created by : Narasimha Karumanchi +#Book Title : Data Structures And Algorithms Made Easy +#Warranty : This software is provided "as is" without any +# warranty; without even the implied warranty of +# merchantability or fitness for a particular purpose.*/ + +#include +#include + +/* A structure of linked list ListNode */ +struct ListNode { + int data; + struct ListNode *next; +} *head; + +void initialize(){ + head = NULL; +} + +/* +Given a Inserts a ListNode in pTemp of a singly linked list. +*/ +void insert(int data) { + /* Create a new Linked List ListNode */ + struct ListNode* newNode = (struct ListNode*) malloc(sizeof(struct ListNode)); + newNode->data = data; + /* Next pointer of new ListNode will point to head ListNode of linked list */ + newNode->next = head; + /* make new ListNode as new head of linked list */ + head = newNode; + printf("Inserted Element : %d\n", data); +} + +int getLength(struct ListNode *head){ + /* Input Validation */ + if (head == NULL) { + printf("Error : Invalid ListNode pointer !!!\n"); + return 0; + } + + int length =0; + while(head != NULL){ + head = head->next; + length++; + } + return length; +} + +struct ListNode * middleNode(struct ListNode *head){ + /* Input Validation */ + if(head == NULL){ + printf("Error: List is empty!\n"); + return NULL; + } + struct ListNode *slow, *fast; + slow = fast = head; + /* In every iteration, slow pointer will move one node whereas fast pointer will move two ListNodes. + When fast pointer reaches last ListNode then slow pointer will be pointing to middle ListNode */ + while(fast != NULL && fast->next != NULL) { + fast = fast->next->next; + slow = slow->next; + } + return slow; +} + +/* +Prints a linked list from head ListNode till tail ListNode +*/ +void printLinkedList(struct ListNode *ListNodePtr) { + while (ListNodePtr != NULL) { + printf("%d", ListNodePtr->data); + ListNodePtr = ListNodePtr->next; + if(ListNodePtr != NULL) + printf("-->"); + } +} + +void alternatingSplit(struct ListNode* head, struct ListNode** head1, struct ListNode** head2) { + struct ListNode* a = NULL; // Split the nodes to these 'a' and 'b' lists + struct ListNode* b = NULL; + struct ListNode* current = head; + while (current != NULL) { + // Move a ListNode to 'a' + struct ListNode* newNode = current; // the front current node + current = newNode->next; // Advance the current pointer + newNode->next = a; // Link the node with the head of list a + a = newNode; + + // Move a ListNode to 'b' + if (current != NULL) { + struct ListNode* newNode = current; // the front source node + current = newNode->next; // Advance the source pointer + newNode->next = b; // Link the node with the head of list b + b = newNode; + } + } + *head1 = a; + *head2 = b; +} + +int main() { + struct ListNode *head1, *head2; + initialize(); + /* Creating a linked List*/ + insert(3); + insert(8); + insert(12); + insert(0); + insert(35); + insert(6); + insert(10); + insert(350); + insert(16); + insert(19); + printf("\nLinked List\n"); + printLinkedList(head); + alternatingSplit(head, &head1, &head2); + printf("\nLinked List1\n"); + printLinkedList(head1); + printf("\nLinked List2\n"); + printLinkedList(head2); + return 0; +} diff --git a/src/Chapter_03_Linked_Lists/DoublyLinkedList.c b/src/Chapter_03_Linked_Lists/DoublyLinkedList.c index 60d972a..fb3e007 100644 --- a/src/Chapter_03_Linked_Lists/DoublyLinkedList.c +++ b/src/Chapter_03_Linked_Lists/DoublyLinkedList.c @@ -1,102 +1,238 @@ -#include -#include -struct listNode{ - int data; - struct listNode *prev; - struct listNode *next; +/*Copyright (c) 2016 CareerMonk Publications and others. +#E-Mail : info@careermonk.com +#Creation Date : 2008-01-10 06:15:46 +#Created by : Narasimha Karumanchi +#Book Title : Data Structures And Algorithms Made Easy +#Warranty : This software is provided "as is" without any +# warranty; without even the implied warranty of +# merchantability or fitness for a particular purpose.*/ + +#include +#include + +struct DLLNode { + int data; + struct DLLNode *prev; + struct DLLNode *next; }; -int doublyListLength(struct listNode *head){ - int count; - while(head!=NULL){ - count++; - head=head->next; - } - return count; + +//length of the list +int length(struct DLLNode *head) { + struct DLLNode *current = head; + int count = 0; + if(head == NULL) + return 0; + + while (current != NULL){ + current = current->next; + count++; + } + return count; +} + +// display list using iteration +void printList(struct DLLNode *head) { + struct DLLNode *current = head; + if(head == NULL) + return; + while (current != NULL){ + printf ("%d-->", current->data); + current = current->next; + } +} + + +// Insert at the beginning of the list +void insertAtBeginning(struct DLLNode **head, int data){ + struct DLLNode *current = *head; + struct DLLNode *newNode = (struct DLLNode *) (malloc(sizeof(struct DLLNode))); + if(!newNode) { + printf("Memory Error"); + return; + } + newNode->prev = NULL; + newNode->data = data; + newNode->next = NULL; + if(current == NULL){ + *head = newNode; + return; + } + + newNode->next = *head; + (*head)->prev = newNode; + *head = newNode; } -void insertInLinkedList(struct listNode **head, int data, int pos){ - int k=1; - struct listNode *p, *q, *newNode; - newNode=(struct listNode *)malloc(sizeof(struct listNode)); - if(!newNode){ + +// insert item at the end of the list +void insertAtEnd(struct DLLNode **head, int data){ + struct DLLNode *current = *head; + struct DLLNode *newNode = (struct DLLNode *)(malloc(sizeof(struct DLLNode))); + if(!newNode) { printf("Memory Error"); return; } - newNode->data=data; - if(pos==1 || *head==NULL){ - newNode->next=*head; - newNode->prev=NULL; - if(*head){ - (*head)->prev=newNode; - } - *head=newNode; - } - else{ - p=*head; - while(p!=NULL && knext; - } - newNode->next=p; - newNode->prev=q; - q->next=newNode; - if(p){ - p->prev=newNode; - } - } -} -void deleteNodeFromDLLinkedList(struct listNode **head, int pos){ - int k=1; - struct listNode *temp, *q, *p; - if(!head){ - printf("List empty"); + newNode->prev = NULL; + newNode->data = data; + newNode->next = NULL; + if(*head ==NULL){ + *head = newNode; return; } - if(pos==1){ - temp=*head; - *head=(*head)->next; - if(*head){ - (*head)->prev=NULL; - } - free(temp); - } - else{ - p=*head; - while(p!=NULL && knext; - } - if(p==NULL){ - printf("No such position exist"); - return; - } - temp=p; - q->next=p->next; - if(p->next){ - p->next->prev=q; - } - free(temp); - } + + while (current->next != NULL) + current = current->next; + + // current points to tail node + newNode->prev = current; + current->next = newNode; } -void printDLList(struct listNode *head){ - while(head!=NULL){ - printf("%d ",head->data); - head=head->next; - } - printf("\n"); + +void insert(struct DLLNode **head, int data, int position) { + int k = 1; + struct DLLNode *temp, *newNode; + newNode = (struct DLLNode *) malloc(sizeof ( struct DLLNode )); + if(!newNode) { //Always check for memory errors + printf ("Memory Error"); + return; + } + newNode->prev = NULL; + newNode->data = data; + newNode->next = NULL; + + if(position == 1) { //Inserting a node at the beginning + newNode->next = *head; + newNode->prev = NULL; + + if(*head) + (*head)->prev = newNode; + + *head = newNode; + return; + } + temp = *head; + while (k < position-1 && temp->next != NULL) { + temp = temp->next; + k++; + } + + if(k < position-1){ + printf("Desired position does not exist\n"); + return; + } + + newNode->next = temp->next; + newNode->prev = temp; + + if(temp->next) + temp->next->prev = newNode; + + temp->next = newNode; + return; +} + + +void deleteLastNode(struct DLLNode **head) { + struct DLLNode *temp = *head, *current = *head; + + if(*head == NULL) { + printf( "List empty!"); + return; + } + while (current->next != NULL){ + current = current->next; + } + temp = current->prev; + temp->next = current->next; + free(current); + return; +} + +void deleteFrontNode (struct DLLNode **head) { + struct DLLNode *temp = *head; + + if(*head == NULL) { + printf("List empty"); + return; + } + temp = *head; + *head = (*head)->next; + (*head)->prev = NULL; + free(temp); + return; +} + +void delete(struct DLLNode **head, int position) { + struct DLLNode *temp2, *temp = *head; + int k = 1; + if(*head == NULL) { + printf("List is empty"); + return; + } + if(position == 1) { + *head = (*head)->next; + + if(*head != NULL) + (*head)->prev = NULL; + free(temp); + return; + } + while(k < position && temp->next!=NULL) { + temp = temp->next; + k++; + } + if(k < position-1){ + printf("Desired position does not exist\n"); + return; + } + + temp2 = temp->prev; + temp2->next = temp->next; + + if(temp->next) // Deletion from Intermediate Node + temp->next->prev = temp2; + + free(temp); + return; } -int DoublyLinkedList_test(){ - struct listNode *head; - printf("Elements in list are :%d\n",doublyListLength(head)); - printDLList(head); - insertInLinkedList(&head,2,3); - insertInLinkedList(&head,5,3); - insertInLinkedList(&head,9,1); - insertInLinkedList(&head,10,3); - printf("Elements in list are :%d\n",doublyListLength(head)); - printDLList(head); - deleteNodeFromDLLinkedList(&head,3); - printDLList(head); - return 0; + + +int main(){ + struct DLLNode *head = NULL; + printf("%d \n",length(head)); + insertAtBeginning(&head, 30); + insertAtBeginning(&head, 20); + insertAtBeginning(&head, 10); + printf("List length is %d \n",length(head)); + printList(head); + printf("\n"); + insertAtEnd(&head, 40); + insertAtEnd(&head, 50); + insertAtEnd(&head, 60); + printf("List length is %d \n",length(head)); + printList(head); + printf("\n"); + insert(&head, 15, 2); + insert(&head, 35, 4); + insert(&head, 55, 6); + insert(&head, 115, 12); + printf("List length is %d \n",length(head)); + printList(head); + printf("\n"); + deleteFrontNode(&head); + printf("List length is %d \n",length(head)); + printList(head); + printf("\n"); + deleteLastNode(&head); + printf("List length is %d \n",length(head)); + printList(head); + printf("\n"); + delete(&head, 7); + printf("List length is %d \n",length(head)); + printList(head); + printf("\n"); + delete(&head, 2); + printf("List length is %d \n",length(head)); + printList(head); + printf("\n"); + return 0; } diff --git a/src/Chapter_03_Linked_Lists/LoopLength.c b/src/Chapter_03_Linked_Lists/LoopLength.c new file mode 100644 index 0000000..2320733 --- /dev/null +++ b/src/Chapter_03_Linked_Lists/LoopLength.c @@ -0,0 +1,122 @@ +/*Copyright (c) 2008 CareerMonk Publications and others. +#E-Mail : info@careermonk.com +#Creation Date : 2008-01-10 06:15:46 +#Created by : Narasimha Karumanchi +#Book Title : Data Structures And Algorithms Made Easy +#Warranty : This software is provided "as is" without any +# warranty; without even the implied warranty of +# merchantability or fitness for a particular purpose.*/ +#include +#include + +/* A structure of linked list ListNode */ +struct ListNode { + int data; + struct ListNode *next; +} *head; + +void initialize(){ + head = NULL; +} + +/* +Given a Inserts a ListNode in pTemp of a singly linked list. +*/ +void insert(int data) { + /* Create a new Linked List ListNode */ + struct ListNode* newNode = (struct ListNode*) malloc(sizeof(struct ListNode)); + newNode->data = data; + /* Next pointer of new ListNode will point to head ListNode of linked list */ + newNode->next = head; + /* make new ListNode as new head of linked list */ + head = newNode; + printf("Inserted Element : %d\n", data); +} + +int getLength(struct ListNode *head){ + /* Input Validation */ + if (head == NULL) { + printf("Error : Invalid ListNode pointer !!!\n"); + return 0; + } + + int length =0; + while(head != NULL){ + head = head->next; + length++; + } + return length; +} + + +int checkLoop(struct ListNode *head) { + struct ListNode *slow, *fast; + slow = fast = head; + + while(fast && fast->next) { + /* Slow pointer will move one node per iteration whereas fast node will move two nodes per iteration */ + slow = slow->next; + fast = fast->next->next; + if (slow == fast) { + printf("\n Linked list contains a loop\n"); + return 1; + } + } + printf("\n No loop in linked list\n"); + return 0; +} + +int loopLength(struct ListNode * head) { + struct ListNode *slow = head, *fast = head; + int loopExists = 0, counter = 0; + while (fast && fast->next) { + slow = slow->next; + fast = fast->next->next; + if (slow == fast){ + loopExists = 1; + break; + } + } + if(loopExists) { + counter = 1; + fast = fast->next; + while(slow != fast) { + fast = fast->next; + counter++; + } + return counter; + } + return 0; +} + +/* +Prints a linked list from head ListNode till tail ListNode +*/ +void printLinkedList(struct ListNode *ListNodePtr) { + while (ListNodePtr != NULL) { + printf("%d", ListNodePtr->data); + ListNodePtr = ListNodePtr->next; + if(ListNodePtr != NULL) + printf("-->"); + } +} + +int main() { + struct ListNode *temp; + initialize(); + /* Creating a linked List*/ + insert(8); + insert(3); + insert(2); + insert(7); + insert(9); + + printf("\nLinked List\n"); + printLinkedList(head); + checkLoop(head); + /* Create loop in linked list. Set next pointer of last node to second node from head */ + head->next->next->next->next->next = head->next->next; + checkLoop(head); + printf ("\n Loop length is %d", loopLength(head)); + return 0; +} diff --git a/src/Chapter_03_Linked_Lists/SinglyLinkedList.c b/src/Chapter_03_Linked_Lists/SinglyLinkedList.c index ee78814..16e511b 100644 --- a/src/Chapter_03_Linked_Lists/SinglyLinkedList.c +++ b/src/Chapter_03_Linked_Lists/SinglyLinkedList.c @@ -5,7 +5,7 @@ struct listNode{ struct listNode *next; }; int singlyListLength(struct listNode *head){ - int count; + int count=0; struct listNode *current=head; while(current!=NULL){ count++; diff --git a/src/Chapter_03_Linked_Lists/checkLoop.c b/src/Chapter_03_Linked_Lists/checkLoop.c new file mode 100644 index 0000000..4de7151 --- /dev/null +++ b/src/Chapter_03_Linked_Lists/checkLoop.c @@ -0,0 +1,98 @@ +/*Copyright (c) 2008 CareerMonk Publications and others. +#E-Mail : info@careermonk.com +#Creation Date : 2008-01-10 06:15:46 +#Created by : Narasimha Karumanchi +#Book Title : Data Structures And Algorithms Made Easy +#Warranty : This software is provided "as is" without any +# warranty; without even the implied warranty of +# merchantability or fitness for a particular purpose.*/ + +#include +#include + +/* A structure of linked list ListNode */ +struct ListNode { + int data; + struct ListNode *next; +} *head; + +void initialize(){ + head = NULL; +} + +/* +Given a Inserts a ListNode in pTemp of a singly linked list. +*/ +void insert(int data) { + /* Create a new Linked List ListNode */ + struct ListNode* newNode = (struct ListNode*) malloc(sizeof(struct ListNode)); + newNode->data = data; + /* Next pointer of new ListNode will point to head ListNode of linked list */ + newNode->next = head; + /* make new ListNode as new head of linked list */ + head = newNode; + printf("Inserted Element : %d\n", data); +} + +int getLength(struct ListNode *head){ + /* Input Validation */ + if (head == NULL) { + printf("Error : Invalid ListNode pointer !!!\n"); + return 0; + } + + int length =0; + while(head != NULL){ + head = head->next; + length++; + } + return length; +} + + +int checkLoop(struct ListNode *head) { + struct ListNode *slow, *fast; + slow = fast = head; + + while(fast && fast->next) { + /* Slow pointer will move one node per iteration whereas fast node will move two nodes per iteration */ + slow = slow->next; + fast = fast->next->next; + if (slow == fast) { + printf("\n Linked list contains a loop\n"); + return 1; + } + } + printf("\n No loop in linked list\n"); + return 0; +} +/* +Prints a linked list from head ListNode till tail ListNode +*/ +void printLinkedList(struct ListNode *ListNodePtr) { + while (ListNodePtr != NULL) { + printf("%d", ListNodePtr->data); + ListNodePtr = ListNodePtr->next; + if(ListNodePtr != NULL) + printf("-->"); + } +} + +int main() { + struct ListNode *middle; + initialize(); + /* Creating a linked List*/ + insert(8); + insert(3); + insert(2); + insert(7); + insert(9); + + printf("\nLinked List\n"); + printLinkedList(head); + checkLoop(head); + /* Create loop in linked list. Set next pointer of last node to second node from head */ + head->next->next->next->next->next = head->next; + checkLoop(head); + return 0; +} diff --git a/src/Chapter_03_Linked_Lists/circular linked list.c b/src/Chapter_03_Linked_Lists/circular linked list.c new file mode 100644 index 0000000..df955cb --- /dev/null +++ b/src/Chapter_03_Linked_Lists/circular linked list.c @@ -0,0 +1,148 @@ +/*Copyright (c) 2016 CareerMonk Publications and others. +#E-Mail : info@careermonk.com +#Creation Date : 2008-01-10 06:15:46 +#Created by : Narasimha Karumanchi +#Book Title : Data Structures And Algorithms Made Easy +#Warranty : This software is provided "as is" without any +# warranty; without even the implied warranty of +# merchantability or fitness for a particular purpose.*/ + +#include +#include + +struct CLLNode{ + int data; + struct CLLNode* next; +}; + +struct CLLNode *head = NULL; + +//length of the list +int length(struct CLLNode *head) { + struct CLLNode *current = head; + int count = 0; + if(head == NULL) + return 0; + + do { + current = current->next; + count++; + } while (current != head); + + return count; +} + +// display list using iteration +void printList(struct CLLNode *head) { + struct CLLNode *current = head; + if(head == NULL) + return; + + do { + printf ("%d-->", current->data); + current = current->next; + } while(current != head); +} + +// Insert at the beginning of the list +void insertAtBeginInCLL (struct CLLNode **head, int data){ + struct CLLNode *current = *head; + struct CLLNode *newNode = (struct CLLNode *) (malloc(sizeof(struct CLLNode))); + if(!newNode) { + printf("Memory Error"); + return; + } + newNode->data = data; + newNode->next = newNode; + if(current == NULL){ + *head = newNode; + return; + } + + while (current->next != *head) + current = current->next; + + newNode->next = *head; + current->next = newNode; + *head = newNode; +} + +// insert item at the end of the list +void insertAtEndInCLL(struct CLLNode **head, int data){ + struct CLLNode *current = *head; + struct CLLNode *newNode = (struct CLLNode *) (malloc(sizeof(struct CLLNode))); + if(!newNode) { + printf("Memory Error"); + return; + } + newNode->data = data; + while (current->next != *head) + current = current->next; + + newNode->next = newNode; + + if(*head ==NULL) + *head = newNode; + else { + newNode->next = *head; + current->next = newNode; + } +} + +void deleteLastNodeFromCLL (struct CLLNode **head) { + struct CLLNode *temp = *head, *current = *head; + + if(*head == NULL) { + printf( "List empty!"); + return; + } + while (current->next != *head) { + temp = current; + current = current->next; + } + temp->next = current->next; + free(current); + return; +} +void deleteFrontNodeFromCLL (struct CLLNode **head) { + struct CLLNode *temp = *head; + struct CLLNode *current = *head; + + if(*head == NULL) { + printf("List empty"); + return; + } + + while (current->next != *head) + current = current->next; + + current->next = (*head)->next; + *head = (*head)->next; + + free(temp); + return; +} + + +int main(){ + struct CLLNode *head = NULL; + printf("%d \n",length(head)); + insertAtBeginInCLL(&head, 30); + insertAtBeginInCLL(&head, 20); + insertAtBeginInCLL(&head, 10); + printf("List length is %d \n",length(head)); + printList(head); + printf("\n"); + insertAtEndInCLL(&head, 40); + insertAtEndInCLL(&head, 50); + insertAtEndInCLL(&head, 60); + printf("List length is %d \n",length(head)); + printList(head); + deleteLastNodeFromCLL(&head); + printf("List length is %d \n",length(head)); + printList(head); + deleteFrontNodeFromCLL(&head); + printf("List length is %d \n",length(head)); + printList(head); + return 0; +} diff --git a/src/Chapter_03_Linked_Lists/findLoopBeginning.c b/src/Chapter_03_Linked_Lists/findLoopBeginning.c new file mode 100644 index 0000000..a754e7b --- /dev/null +++ b/src/Chapter_03_Linked_Lists/findLoopBeginning.c @@ -0,0 +1,123 @@ +/*Copyright (c) 2008 CareerMonk Publications and others. +#E-Mail : info@careermonk.com +#Creation Date : 2008-01-10 06:15:46 +#Created by : Narasimha Karumanchi +#Book Title : Data Structures And Algorithms Made Easy +#Warranty : This software is provided "as is" without any +# warranty; without even the implied warranty of +# merchantability or fitness for a particular purpose.*/ + +#include +#include + +/* A structure of linked list ListNode */ +struct ListNode { + int data; + struct ListNode *next; +} *head; + +void initialize(){ + head = NULL; +} + +/* +Given a Inserts a ListNode in pTemp of a singly linked list. +*/ +void insert(int data) { + /* Create a new Linked List ListNode */ + struct ListNode* newNode = (struct ListNode*) malloc(sizeof(struct ListNode)); + newNode->data = data; + /* Next pointer of new ListNode will point to head ListNode of linked list */ + newNode->next = head; + /* make new ListNode as new head of linked list */ + head = newNode; + printf("Inserted Element : %d\n", data); +} + +int getLength(struct ListNode *head){ + /* Input Validation */ + if (head == NULL) { + printf("Error : Invalid ListNode pointer !!!\n"); + return 0; + } + + int length =0; + while(head != NULL){ + head = head->next; + length++; + } + return length; +} + + +int checkLoop(struct ListNode *head) { + struct ListNode *slow, *fast; + slow = fast = head; + + while(fast && fast->next) { + /* Slow pointer will move one node per iteration whereas fast node will move two nodes per iteration */ + slow = slow->next; + fast = fast->next->next; + if (slow == fast) { + printf("\n Linked list contains a loop\n"); + return 1; + } + } + printf("\n No loop in linked list\n"); + return 0; +} + +struct ListNode * findLoopBeginning(struct ListNode * head) { + struct ListNode *slow = head, *fast = head; + int loopExists = 0; + while (fast && fast->next) { + slow = slow->next; + fast = fast->next->next; + if (slow == fast){ + loopExists = 1; + break; + } + } + if(loopExists) { + slow = head; + while(slow != fast) { + fast = fast->next; + slow = slow->next; + } + return slow; + } + return NULL; +} + +/* +Prints a linked list from head ListNode till tail ListNode +*/ +void printLinkedList(struct ListNode *ListNodePtr) { + while (ListNodePtr != NULL) { + printf("%d", ListNodePtr->data); + ListNodePtr = ListNodePtr->next; + if(ListNodePtr != NULL) + printf("-->"); + } +} + +int main() { + struct ListNode *temp; + initialize(); + /* Creating a linked List*/ + insert(8); + insert(3); + insert(2); + insert(7); + insert(9); + + printf("\nLinked List\n"); + printLinkedList(head); + checkLoop(head); + /* Create loop in linked list. Set next pointer of last node to second node from head */ + head->next->next->next->next->next = head->next->next; + checkLoop(head); + temp = findLoopBeginning(head); + printf ("\n Loop beginning is %d", temp->data); + return 0; +} diff --git a/src/Chapter_03_Linked_Lists/intersectingListNode.c b/src/Chapter_03_Linked_Lists/intersectingListNode.c new file mode 100644 index 0000000..c85aa5a --- /dev/null +++ b/src/Chapter_03_Linked_Lists/intersectingListNode.c @@ -0,0 +1,148 @@ +// Copyright (c) 2008 CareerMonk Publications and others. +// #E-Mail : info@careermonk.com +// Creation Date : 2008-01-10 06:15:46 +// Created by : Narasimha Karumanchi +// Book Title : Data Structures And Algorithms Made Easy +// Warranty : This software is provided "as is" without any +// warranty; without even the implied warranty of +// merchantability or fitness for a particular purpose. + +#include +#include + +/* A structure of linked list ListNode */ +struct ListNode { + int data; + struct ListNode *next; +} *head1, *head2; + +void initialize(){ + head1 = NULL; + head2 = NULL; +} + +/* +Given a Inserts a ListNode in pTemp of a singly linked list. +*/ +void insert(struct ListNode **head, int data) { + /* Create a new Linked List ListNode */ + struct ListNode* newListNode = (struct ListNode*) malloc(sizeof(struct ListNode)); + newListNode->data = data; + /* Next pointer of new ListNode will point to head ListNode of linked list */ + newListNode->next = *head; + /* make new ListNode as new head of linked list */ + *head = newListNode; +} + +int getLength(struct ListNode *head){ + /* Input Validation */ + if (head == NULL) { + printf("Error : Invalid ListNode pointer !!!\n"); + return 0; + } + + int length =0; + while(head != NULL){ + head = head->next; + length++; + } + return length; +} + +// Prints a linked list from head ListNode till tail ListNode +void printLinkedList(struct ListNode *head) { + while (head != NULL) { + printf("%d", head->data); + head = head->next; + if(head != NULL) + printf("-->"); + } +} + +/* Reverses a given linked list, and return the head pointer of reversed linked list */ +struct ListNode* reverseLinkedList(struct ListNode *head) { + struct ListNode *previous, *current, *next; + previous = NULL; + current = head; + + while (current != NULL) { + next = current->next; + current->next = previous; + previous = current; + current = next; + } + return previous; +} + +struct ListNode * intersectingListNode(struct ListNode * head1, struct ListNode * head2){ + // get count of both the lists + int m = getLength(head1); + int n = getLength(head2); + + //to store the merge point + struct ListNode * mergePoint = NULL; + + // finding the value of d based on the longer list + int diff = (m > n) ? (m-n) : (n-m); + + //traverse the smaller longer list for 'diff' steps + if(m > n){ + while(diff--) + head1 = head1 -> next; + } + else{ + while(diff--) + head2 = head2 -> next; + } + + // now both lists have equal ListNodes till the end. + while(head1 && head2){ + if(head1 -> next->data == head2 -> next->data){ + mergePoint = head1 -> next; + break; + } + + head1 = head1 -> next; + head2 = head2 -> next; + } + + return mergePoint; +} + +int main() { + struct ListNode *intersectingNode; + initialize(); + /* Creating a linked List*/ + insert(&head1, 3); + insert(&head1, 8); + insert(&head1, 12); + insert(&head1, 0); + insert(&head1, 35); + insert(&head1, 6); + insert(&head1, 10); + insert(&head1, 350); + insert(&head1, 16); + insert(&head1, 19); + head1 = reverseLinkedList(head1); + printf("\nLinked List\n"); + printLinkedList(head1); + insert(&head2, 13); + insert(&head2, 18); + insert(&head2, 112); + insert(&head2, 10); + insert(&head2, 135); + insert(&head2, 16); + insert(&head2, 10); + insert(&head2, 350); + insert(&head2, 16); + insert(&head2, 19); + head2 = reverseLinkedList(head2); + printf("\nLinked List\n"); + printLinkedList(head2); + intersectingNode = intersectingListNode(head1, head2); + if (intersectingListNode) + printf("\n Intersecting ListNode is %d", intersectingNode->data); + else + printf("\n NULL \n"); + return 0; +} diff --git a/src/Chapter_03_Linked_Lists/intersectingNodeBruteForce.c b/src/Chapter_03_Linked_Lists/intersectingNodeBruteForce.c new file mode 100644 index 0000000..a432efc --- /dev/null +++ b/src/Chapter_03_Linked_Lists/intersectingNodeBruteForce.c @@ -0,0 +1,133 @@ +// Copyright (c) 2008 CareerMonk Publications and others. +// #E-Mail : info@careermonk.com +// Creation Date : 2008-01-10 06:15:46 +// Created by : Narasimha Karumanchi +// Book Title : Data Structures And Algorithms Made Easy +// Warranty : This software is provided "as is" without any +// warranty; without even the implied warranty of +// merchantability or fitness for a particular purpose. + +#include +#include + +/* A structure of linked list ListNode */ +struct ListNode { + int data; + struct ListNode *next; +} *head1, *head2; + +void initialize(){ + head1 = NULL; + head2 = NULL; +} + +/* +Given a Inserts a ListNode in pTemp of a singly linked list. +*/ +void insert(struct ListNode **head, int data) { + /* Create a new Linked List ListNode */ + struct ListNode* newNode = (struct ListNode*) malloc(sizeof(struct ListNode)); + newNode->data = data; + /* Next pointer of new ListNode will point to head ListNode of linked list */ + newNode->next = *head; + /* make new ListNode as new head of linked list */ + *head = newNode; +} + +int getLength(struct ListNode *head){ + /* Input Validation */ + if (head == NULL) { + printf("Error : Invalid ListNode pointer !!!\n"); + return 0; + } + + int length =0; + while(head != NULL){ + head = head->next; + length++; + } + return length; +} + +// Prints a linked list from head ListNode till tail ListNode +void printLinkedList(struct ListNode *head) { + while (head != NULL) { + printf("%d", head->data); + head = head->next; + if(head != NULL) + printf("-->"); + } +} + +/* Reverses a given linked list, and return the head pointer of reversed linked list */ +struct ListNode* reverseLinkedList(struct ListNode *head) { + struct ListNode *previous, *current, *next; + previous = NULL; + current = head; + + while (current != NULL) { + next = current->next; + current->next = previous; + previous = current; + current = next; + } + return previous; +} + +struct ListNode * intersectingNodeBruteForce(struct ListNode *head1, struct ListNode *head2){ + // stores the result, if no ListNode is intersecting we return NULL + struct ListNode *temp; + + while(head1 != NULL){ + temp = head2; + printf("\n List1 data is %d", head1->data); + while(temp != NULL){ + if(temp->data == head1->data){ + printf("\n List2 data is %d", temp->data); + // found a matching ListNode + return head1; + } + temp = temp -> next; + } + head1 = head1 -> next; + } + return NULL; +} + +int main() { + struct ListNode *intersectingNode; + initialize(); + /* Creating a linked List*/ + insert(&head1, 3); + insert(&head1, 8); + insert(&head1, 12); + insert(&head1, 0); + insert(&head1, 35); + insert(&head1, 6); + insert(&head1, 10); + insert(&head1, 350); + insert(&head1, 16); + insert(&head1, 19); + head1 = reverseLinkedList(head1); + printf("\nLinked List\n"); + printLinkedList(head1); + insert(&head2, 13); + insert(&head2, 18); + insert(&head2, 112); + insert(&head2, 10); + insert(&head2, 135); + insert(&head2, 16); + insert(&head2, 10); + insert(&head2, 350); + insert(&head2, 16); + insert(&head2, 19); + head2 = reverseLinkedList(head2); + printf("\nLinked List\n"); + printLinkedList(head2); + intersectingNode = intersectingNodeBruteForce(head1, head2); + if (intersectingNode) + printf("\n Intersecting node is %d", intersectingNode->data); + else + printf("\n NULL \n"); + return 0; +} diff --git a/src/Chapter_03_Linked_Lists/intersection.c b/src/Chapter_03_Linked_Lists/intersection.c new file mode 100644 index 0000000..09e6adf --- /dev/null +++ b/src/Chapter_03_Linked_Lists/intersection.c @@ -0,0 +1,195 @@ +// Copyright (c) 2008 CareerMonk Publications and others. +// #E-Mail : info@careermonk.com +// Creation Date : 2008-01-10 06:15:46 +// Created by : Narasimha Karumanchi +// Book Title : Data Structures And Algorithms Made Easy +// Warranty : This software is provided "as is" without any +// warranty; without even the implied warranty of +// merchantability or fitness for a particular purpose. + +#include +#include + +/* A structure of linked list ListNode */ +struct ListNode { + int data; + struct ListNode *next; +} *head1, *head2; + +void initialize(){ + head1 = NULL; + head2 = NULL; +} + +/* +Given a Inserts a ListNode in pTemp of a singly linked list. +*/ +void insert(struct ListNode **head, int data) { + /* Create a new Linked List ListNode */ + struct ListNode* newNode = (struct ListNode*) malloc(sizeof(struct ListNode)); + newNode->data = data; + /* Next pointer of new ListNode will point to head ListNode of linked list */ + newNode->next = *head; + /* make new ListNode as new head of linked list */ + *head = newNode; +} + +int getLength(struct ListNode *head){ + /* Input Validation */ + if (head == NULL) { + printf("Error : Invalid ListNode pointer !!!\n"); + return 0; + } + + int length =0; + while(head != NULL){ + head = head->next; + length++; + } + return length; +} + +// Prints a linked list from head ListNode till tail ListNode +void printLinkedList(struct ListNode *head) { + while (head != NULL) { + printf("%d", head->data); + head = head->next; + if(head != NULL) + printf("-->"); + } +} + +/* Reverses a given linked list, and return the head pointer of reversed linked list */ +struct ListNode* reverseLinkedList(struct ListNode *head) { + struct ListNode *previous, *current, *next; + previous = NULL; + current = head; + + while (current != NULL) { + next = current->next; + current->next = previous; + previous = current; + current = next; + } + return previous; +} + +// Insert new Node in the beginning of the linked list +void push(struct ListNode** head, int data){ + struct ListNode* newNode = (struct ListNode*)malloc(sizeof(struct ListNode)); + newNode->data = data; + newNode->next = *head; + *head = newNode; +} + +// Solution to give common elements in the reverse +struct ListNode * intersection1(struct ListNode *list1, struct ListNode *list2) { + struct ListNode *head = NULL; + while (list1 != NULL && list2 != NULL) { + if (list1->data == list2->data) { + push(&head, list1->data); // Copy common element. + list1 = list1->next; + list2 = list2->next; + } else if (list1->data > list2->data) { + list2 = list2->next; + } else { // list1->data < list2->data + list1 = list1->next; + } + } + return head; +} + +// Solution to give common elements in the reverse +struct ListNode * intersection2(struct ListNode *list1, struct ListNode *list2) { + struct ListNode *head = NULL; + struct ListNode* tail; + while (list1 != NULL && list2 != NULL) { + if (list1->data == list2->data) { + if (head == NULL) { + push(&head, list1->data); + tail = head; + } + else{ + push(&tail->next, list1->data); + tail = tail->next; + } + list1 = list1->next; + list2 = list2->next; + } else if (list1->data > list2->data) { + list2 = list2->next; + } else { // list1->data < list2->data + list1 = list1->next; + } + } + return head; +} + +// Solution uses the temporary dummy node to build up the result list +struct ListNode * intersection3(struct ListNode *list1, struct ListNode *list2) { + struct ListNode dummy; + struct ListNode *tail = &dummy; + dummy.next = NULL; + while (list1 != NULL && list2 != NULL) { + if (list1->data == list2->data) { + push((&tail->next), list1->data); // Copy common element. + list1 = list1->next; + list2 = list2->next; + tail = tail->next; + } else if (list1->data > list2->data) { + list2 = list2->next; + } else { // list1->data < list2->data + list1 = list1->next; + } + } + return dummy.next; +} + +int main() { + struct ListNode *commonNodes; + initialize(); + /* Creating a linked List*/ + insert(&head1, 3); + insert(&head1, 8); + insert(&head1, 12); + insert(&head1, 20); + insert(&head1, 35); + insert(&head1, 36); + insert(&head1, 100); + insert(&head1, 350); + insert(&head1, 516); + insert(&head1, 519); + head1 = reverseLinkedList(head1); + printf("\nLinked List\n"); + printLinkedList(head1); + insert(&head2, 3); + insert(&head2, 8); + insert(&head2, 13); + insert(&head2, 22); + insert(&head2, 35); + insert(&head2, 36); + insert(&head2, 200); + insert(&head2, 380); + insert(&head2, 516); + insert(&head2, 529); + head2 = reverseLinkedList(head2); + printf("\nLinked List\n"); + printLinkedList(head2); + commonNodes = intersection1(head1, head2); + printf("\nCommon elements\n"); + while (commonNodes != NULL) { + printf(" %d-->", commonNodes->data); + commonNodes = commonNodes->next; + } + commonNodes = intersection2(head1, head2); + printf("\nCommon elements\n"); + while (commonNodes != NULL) { + printf(" %d-->", commonNodes->data); + commonNodes = commonNodes->next; + } + commonNodes = intersection3(head1, head2); + printf("\nCommon elements\n"); + while (commonNodes != NULL) { + printf(" %d-->", commonNodes->data); + commonNodes = commonNodes->next; + } +} diff --git a/src/Chapter_03_Linked_Lists/kth node from end.c b/src/Chapter_03_Linked_Lists/kth node from end.c new file mode 100644 index 0000000..86d28f2 --- /dev/null +++ b/src/Chapter_03_Linked_Lists/kth node from end.c @@ -0,0 +1,104 @@ +/*Copyright (c) 2008 CareerMonk Publications and others. +#E-Mail : info@careermonk.com +#Creation Date : 2008-01-10 06:15:46 +#Created by : Narasimha Karumanchi +#Book Title : Data Structures And Algorithms Made Easy +#Warranty : This software is provided "as is" without any +# warranty; without even the implied warranty of +# merchantability or fitness for a particular purpose.*/ + +#include +#include + +/* A structure of linked list ListNode */ +struct ListNode { + int data; + struct ListNode *next; +} *head; + +void initialize(){ + head = NULL; +} + +/* +Given a Inserts a ListNode in pTemp of a singly linked list. +*/ +void insert(int data) { + /* Create a new Linked List ListNode */ + struct ListNode* newNode = (struct ListNode*) malloc(sizeof(struct ListNode)); + newNode->data = data; + /* Next pointer of new ListNode will point to head ListNode of linked list */ + newNode->next = head; + /* make new ListNode as new head of linked list */ + head = newNode; + printf("Inserted Element : %d\n", data); +} + +int getLength(struct ListNode *head){ + /* Input Validation */ + if (head == NULL) { + printf("Error : Invalid ListNode pointer !!!\n"); + return 0; + } + + int length =0; + while(head != NULL){ + head = head->next; + length++; + } + return length; +} + +struct ListNode* kthNodeFromEnd(struct ListNode* head, int k){ + struct ListNode *pTemp, *kthNode; + int i; + pTemp = kthNode = head; + /* k should be less than length of Linked List */ + if(k > getLength(head)){ + printf("Error : k is greater than length of linked list\n"); + return NULL; + } + /* Move pTemp pointer k-1 ListNodes. This will create + a difference of k-1 ListNodes between pTemp and kthNode */ + for(i = 0; i < k-1; i++){ + pTemp = pTemp->next; + } + /* Now, move both pointers together till pTemp reaches + last ListNode of linked list. when pTemp reaches last ListNode + kthNode pointer will be pointing to Nth last ListNode*/ + while(pTemp->next != NULL){ + pTemp = pTemp->next; + kthNode = kthNode->next; + } + + return kthNode; +} +/* +Prints a linked list from head ListNode till tail ListNode +*/ +void printLinkedList(struct ListNode *ListNodePtr) { + while (ListNodePtr != NULL) { + printf("%d", ListNodePtr->data); + ListNodePtr = ListNodePtr->next; + if(ListNodePtr != NULL) + printf("-->"); + } +} + +int main() { + struct ListNode *kthNode; + initialize(); + /* Creating a linked List*/ + insert(3); + insert(8); + insert(12); + insert(0); + insert(35); + insert(6); + + printf("\nLinked List\n"); + printLinkedList(head); + kthNode = kthNodeFromEnd(head, 3); + printf("\nkth node from end in the linked list is %d", kthNode->data); + return 0; +} diff --git a/src/Chapter_03_Linked_Lists/middleNode.c b/src/Chapter_03_Linked_Lists/middleNode.c new file mode 100644 index 0000000..a537dd2 --- /dev/null +++ b/src/Chapter_03_Linked_Lists/middleNode.c @@ -0,0 +1,100 @@ +/*Copyright (c) 2008 CareerMonk Publications and others. +#E-Mail : info@careermonk.com +#Creation Date : 2008-01-10 06:15:46 +#Created by : Narasimha Karumanchi +#Book Title : Data Structures And Algorithms Made Easy +#Warranty : This software is provided "as is" without any +# warranty; without even the implied warranty of +# merchantability or fitness for a particular purpose.*/ + +#include +#include + +/* A structure of linked list ListNode */ +struct ListNode { + int data; + struct ListNode *next; +} *head; + +void initialize(){ + head = NULL; +} + +/* +Given a Inserts a ListNode in pTemp of a singly linked list. +*/ +void insert(int data) { + /* Create a new Linked List ListNode */ + struct ListNode* newNode = (struct ListNode*) malloc(sizeof(struct ListNode)); + newNode->data = data; + /* Next pointer of new ListNode will point to head ListNode of linked list */ + newNode->next = head; + /* make new ListNode as new head of linked list */ + head = newNode; + printf("Inserted Element : %d\n", data); +} + +int getLength(struct ListNode *head){ + /* Input Validation */ + if (head == NULL) { + printf("Error : Invalid ListNode pointer !!!\n"); + return 0; + } + + int length =0; + while(head != NULL){ + head = head->next; + length++; + } + return length; +} + +struct ListNode * middleNode(struct ListNode *head){ + /* Input Validation */ + if(head == NULL){ + printf("Error: List is empty!\n"); + return NULL; + } + struct ListNode *slow, *fast; + slow = fast = head; + /* In every iteration, slow pointer will move one node whereas fast pointer will move two ListNodes. + When fast pointer reaches last ListNode then slow pointer will be pointing to middle ListNode */ + while(fast != NULL && fast->next != NULL) { + fast = fast->next->next; + slow = slow->next; + } + return slow; +} + +/* +Prints a linked list from head ListNode till tail ListNode +*/ +void printLinkedList(struct ListNode *ListNodePtr) { + while (ListNodePtr != NULL) { + printf("%d", ListNodePtr->data); + ListNodePtr = ListNodePtr->next; + if(ListNodePtr != NULL) + printf("-->"); + } +} + +int main() { + struct ListNode *middle; + initialize(); + /* Creating a linked List*/ + insert(3); + insert(8); + insert(12); + insert(0); + insert(35); + insert(6); + insert(10); + insert(350); + insert(16); + insert(19); + printf("\nLinked List\n"); + printLinkedList(head); + middle = middleNode(head); + printf("\n Middle in the linked list is %d", middle->data); + return 0; +} diff --git a/src/Chapter_03_Linked_Lists/printListInReverse.c b/src/Chapter_03_Linked_Lists/printListInReverse.c new file mode 100644 index 0000000..9bf1972 --- /dev/null +++ b/src/Chapter_03_Linked_Lists/printListInReverse.c @@ -0,0 +1,88 @@ +/*Copyright (c) 2008 CareerMonk Publications and others. +#E-Mail : info@careermonk.com +#Creation Date : 2008-01-10 06:15:46 +#Created by : Narasimha Karumanchi +#Book Title : Data Structures And Algorithms Made Easy +#Warranty : This software is provided "as is" without any +# warranty; without even the implied warranty of +# merchantability or fitness for a particular purpose.*/ +#include +#include + +/* A structure of linked list ListNode */ +struct ListNode { + int data; + struct ListNode *next; +} *head; + +void initialize(){ + head = NULL; +} + +/* +Given a Inserts a ListNode in pTemp of a singly linked list. +*/ +void insert(int data) { + /* Create a new Linked List ListNode */ + struct ListNode* newNode = (struct ListNode*) malloc(sizeof(struct ListNode)); + newNode->data = data; + /* Next pointer of new ListNode will point to head ListNode of linked list */ + newNode->next = head; + /* make new ListNode as new head of linked list */ + head = newNode; + printf("Inserted Element : %d\n", data); +} + +int getLength(struct ListNode *head){ + /* Input Validation */ + if (head == NULL) { + printf("Error : Invalid ListNode pointer !!!\n"); + return 0; + } + + int length =0; + while(head != NULL){ + head = head->next; + length++; + } + return length; +} + +void printListInReverse(struct ListNode *head) { + if(!head) + return; + printListInReverse(head->next); + printf("%d-->", head->data); +} +/* +Prints a linked list from head ListNode till tail ListNode +*/ +void printLinkedList(struct ListNode *ListNodePtr) { + while (ListNodePtr != NULL) { + printf("%d", ListNodePtr->data); + ListNodePtr = ListNodePtr->next; + if(ListNodePtr != NULL) + printf("-->"); + } +} + +int main() { + struct ListNode *middle; + initialize(); + /* Creating a linked List*/ + insert(3); + insert(8); + insert(12); + insert(0); + insert(35); + insert(6); + insert(10); + insert(350); + insert(16); + insert(19); + printf("\nLinked List\n"); + printLinkedList(head); + printf("\nLinked list in reverse\n"); + printListInReverse(head); + return 0; +} diff --git a/src/Chapter_03_Linked_Lists/removeDuplicates.c b/src/Chapter_03_Linked_Lists/removeDuplicates.c new file mode 100644 index 0000000..7b8e555 --- /dev/null +++ b/src/Chapter_03_Linked_Lists/removeDuplicates.c @@ -0,0 +1,113 @@ +// Copyright (c) 2008 CareerMonk Publications and others. +// #E-Mail : info@careermonk.com +// Creation Date : 2008-01-10 06:15:46 +// Created by : Narasimha Karumanchi +// Book Title : Data Structures And Algorithms Made Easy +// Warranty : This software is provided "as is" without any +// warranty; without even the implied warranty of +// merchantability or fitness for a particular purpose. + +#include +#include + +/* A structure of linked list ListNode */ +struct ListNode { + int data; + struct ListNode *next; +} *head; + +void initialize(){ + head = NULL; +} + +/* +Given a Inserts a ListNode in pTemp of a singly linked list. +*/ +void insert(struct ListNode **head, int data) { + /* Create a new Linked List ListNode */ + struct ListNode* newNode = (struct ListNode*) malloc(sizeof(struct ListNode)); + newNode->data = data; + /* Next pointer of new ListNode will point to head ListNode of linked list */ + newNode->next = *head; + /* make new ListNode as new head of linked list */ + *head = newNode; +} + +int getLength(struct ListNode *head){ + /* Input Validation */ + if (head == NULL) { + printf("Error : Invalid ListNode pointer !!!\n"); + return 0; + } + + int length =0; + while(head != NULL){ + head = head->next; + length++; + } + return length; +} + +// Prints a linked list from head ListNode till tail ListNode +void printLinkedList(struct ListNode *head) { + while (head != NULL) { + printf("%d", head->data); + head = head->next; + if(head != NULL) + printf("-->"); + } +} + +/* Reverses a given linked list, and return the head pointer of reversed linked list */ +struct ListNode* reverseLinkedList(struct ListNode *head) { + struct ListNode *previous, *current, *next; + previous = NULL; + current = head; + + while (current != NULL) { + next = current->next; + current->next = previous; + previous = current; + current = next; + } + return previous; +} + +// Remove duplicates from a sorted list +void removeDuplicates(struct ListNode **head) { + struct ListNode* current = *head; + if (current == NULL) return; // do nothing if the list is empty + // Compare current ListNode with next ListNode + while(current->next!=NULL) { + if (current->data == current->next->data) { + struct ListNode* nextNext = current->next->next; + free(current->next); + current->next = nextNext; + } + else { + current = current->next; // only advance if no deletion + } + } +} + +int main() { + struct ListNode *commonNodes; + initialize(); + /* Creating a linked List*/ + insert(&head, 3); + insert(&head, 8); + insert(&head, 13); + insert(&head, 13); + insert(&head, 35); + insert(&head, 120); + insert(&head, 200); + insert(&head, 200); + insert(&head, 516); + insert(&head, 516); + printf("\nLinked List\n"); + head = reverseLinkedList(head); + printLinkedList(head); + removeDuplicates(&head); + printf("\nLinked List\n"); + printLinkedList(head); +} diff --git a/src/Chapter_03_Linked_Lists/reverseLinkedList.c b/src/Chapter_03_Linked_Lists/reverseLinkedList.c new file mode 100644 index 0000000..b118b5f --- /dev/null +++ b/src/Chapter_03_Linked_Lists/reverseLinkedList.c @@ -0,0 +1,110 @@ + /*Copyright (c) 2008 CareerMonk Publications and others. +#E-Mail : info@careermonk.com +#Creation Date : 2008-01-10 06:15:46 +#Created by : Narasimha Karumanchi +#Book Title : Data Structures And Algorithms Made Easy +#Warranty : This software is provided "as is" without any +# warranty; without even the implied warranty of +# merchantability or fitness for a particular purpose.*/ + +#include +#include + +/* A structure of linked list ListNode */ +struct ListNode { + int data; + struct ListNode *next; +} *head; + +void initialize(){ + head = NULL; +} + +/* +Given a Inserts a ListNode in pTemp of a singly linked list. +*/ +void insert(int data) { + /* Create a new Linked List ListNode */ + struct ListNode* newNode = (struct ListNode*) malloc(sizeof(struct ListNode)); + newNode->data = data; + /* Next pointer of new ListNode will point to head ListNode of linked list */ + newNode->next = head; + /* make new ListNode as new head of linked list */ + head = newNode; + printf("Inserted Element : %d\n", data); +} + +int getLength(struct ListNode *head){ + /* Input Validation */ + if (head == NULL) { + printf("Error : Invalid ListNode pointer !!!\n"); + return 0; + } + + int length =0; + while(head != NULL){ + head = head->next; + length++; + } + return length; +} + +/* Reverses a given linked list, and return the head pointer of reversed linked list */ +struct ListNode* reverseLinkedList(struct ListNode *head) { + struct ListNode *previous, *current, *next; + previous = NULL; + current = head; + + while (current != NULL) { + next = current->next; + current->next = previous; + previous = current; + current = next; + } + return previous; +} + +struct ListNode * reverseLinkedListRecursive(struct ListNode *head) { + if (head == NULL || head->next == NULL) + return head; + struct ListNode *secondElem = head->next; + // Need to unlink list from the rest or you will get a cycle + head->next = NULL; + // Reverse everything from the second element on + struct ListNode *reverseRest = reverseLinkedListRecursive(secondElem); + secondElem->next = head; // then we join the two lists + return reverseRest; +} +/* +Prints a linked list from head ListNode till tail ListNode +*/ +void printLinkedList(struct ListNode *ListNodePtr) { + while (ListNodePtr != NULL) { + printf("%d", ListNodePtr->data); + ListNodePtr = ListNodePtr->next; + if(ListNodePtr != NULL) + printf("-->"); + } +} + +int main() { + struct ListNode *middle; + initialize(); + /* Creating a linked List*/ + insert(3); + insert(8); + insert(12); + insert(0); + insert(35); + insert(6); + insert(10); + insert(350); + insert(16); + insert(19); + printf("\nLinked List\n"); + printLinkedList(head); + printf("\nLinked list in reverse\n"); + head = reverseLinkedListRecursive(head); + printLinkedList(head); + return 0; +} diff --git a/src/Chapter_03_Linked_Lists/sortedInsert.c b/src/Chapter_03_Linked_Lists/sortedInsert.c new file mode 100644 index 0000000..d4c0404 --- /dev/null +++ b/src/Chapter_03_Linked_Lists/sortedInsert.c @@ -0,0 +1,98 @@ +/*Copyright (c) 2008 CareerMonk Publications and others. +#E-Mail : info@careermonk.com +#Creation Date : 2008-01-10 06:15:46 +#Created by : Narasimha Karumanchi +#Book Title : Data Structures And Algorithms Made Easy +#Warranty : This software is provided "as is" without any +# warranty; without even the implied warranty of +# merchantability or fitness for a particular purpose.*/ +#include +#include + +/* A structure of linked list ListNode */ +struct ListNode { + int data; + struct ListNode *next; +} *head; + +void initialize(){ + head = NULL; +} + +/* +Given a Inserts a ListNode in pTemp of a singly linked list. +*/ +void insert(int data) { + /* Create a new Linked List ListNode */ + struct ListNode* newNode = (struct ListNode*) malloc(sizeof(struct ListNode)); + newNode->data = data; + /* Next pointer of new ListNode will point to head ListNode of linked list */ + newNode->next = head; + /* make new ListNode as new head of linked list */ + head = newNode; + printf("Inserted Element : %d\n", data); +} + +int getLength(struct ListNode *head){ + /* Input Validation */ + if (head == NULL) { + printf("Error : Invalid ListNode pointer !!!\n"); + return 0; + } + + int length =0; + while(head != NULL){ + head = head->next; + length++; + } + return length; +} + +// Function to insert the given node into the correct sorted position in the given list sorted in increasing order +void sortedInsert(struct ListNode** head, int data){ + /* Create a new Linked List ListNode */ + struct ListNode* newNode = (struct ListNode*) malloc(sizeof(struct ListNode)); + newNode->data = data; + // Special case for the head end + if (*head == NULL || (*head)->data >= newNode->data){ + newNode->next = *head; + *head = newNode; + return; + } + + // Locate the node before the point of insertion + struct ListNode* current = *head; + while(current->next != NULL && current->next->data < newNode->data) + current = current->next; + + newNode->next = current->next; + current->next = newNode; +} + +/* +Prints a linked list from head ListNode till tail ListNode +*/ +void printLinkedList(struct ListNode *ListNodePtr) { + while (ListNodePtr != NULL) { + printf("%d", ListNodePtr->data); + ListNodePtr = ListNodePtr->next; + if(ListNodePtr != NULL) + printf("-->"); + } +} + +int main() { + struct ListNode *temp; + initialize(); + /* Creating a linked List*/ + sortedInsert(&head, 1); + + sortedInsert(&head, 19); + sortedInsert(&head, 5); + sortedInsert(&head, 61); + sortedInsert(&head, 7); + + printf("\nLinked List\n"); + printLinkedList(head); + return 0; +} diff --git a/src/Chapter_04_Queues/DynamicQueue.c b/src/Chapter_04_Queues/DynamicQueue.c new file mode 100644 index 0000000..5fd50ad --- /dev/null +++ b/src/Chapter_04_Queues/DynamicQueue.c @@ -0,0 +1,157 @@ +// Copyright (c) 2008 CareerMonk Publications and others. +// #E-Mail : info@careermonk.com +// Creation Date : 2008-01-10 06:15:46 +// Created by : Narasimha Karumanchi +// Book Title : Data Structures And Algorithms Made Easy +// Warranty : This software is provided "as is" without any +// warranty; without even the implied warranty of +// merchantability or fitness for a particular purpose. + +#include +#include +#include + +struct Queue { + int front, rear; + int capacity; + int size; + int *array; +}; + +// Create an empty queue +struct Queue *createQueue(int capacity) { + struct Queue *Q = malloc(sizeof(struct Queue)); + if(!Q) + return NULL; + Q->capacity = capacity; + Q->front = Q->rear = -1; + Q->size = 0; + Q->array= malloc(Q->capacity * sizeof(int)); + + if(!Q->array) + return NULL; + return Q; +} + +// Returns queue size +int size(struct Queue *Q) { + return Q->size; +} + +// Returns Frnt Element of the Queue +int frontElement(struct Queue *Q) { + return Q->array[Q->front]; +} + +// Returns the Rear Element of the Queue +int rearElement(struct Queue *Q) { + return Q->array[Q->rear]; +} + +// Check's if Queue is empty or not +int isEmpty(struct Queue *Q) { + // if the condition is true then 1 is returned else 0 is returned + return (Q->size == 0); +} + +// Check's if Queue is full or not +int isFull(struct Queue *Q) { + // if the condition is true then 1 is returned else 0 is returned + return (Q->size == Q->capacity); +} + +void resizeQueue(struct Queue *Q) { + int size = Q->capacity; + Q->capacity = Q->capacity*2; + Q->array = realloc (Q->array, sizeof(int) * Q->capacity); + if(!Q->array) { + printf("Memory Error"); + return; + } + if(Q->front > Q->rear ) { + for(int i=0; i < Q->front; i++) { + Q->array[i+size] =Q->array[i]; + } + Q->rear = Q->rear + size; + } +} + + +// Adding elements in Queue +void enqueue(struct Queue *Q, int data) { + if(isFull(Q)) + resizeQueue(Q); + Q->rear = (Q->rear+1) % Q->capacity; + Q->array[Q->rear]= data; + if(Q->front == -1) + Q->front = Q->rear; + Q->size += 1; +} + +// Removes an element from front of the queue +int dequeue(struct Queue *Q) { + int data = INT_MIN; //or element which does not exist in Queue + if(isEmpty(Q)){ + printf("Queue is empty\n"); + return data; + } + data = Q->array[Q->front]; + if(Q->front == Q->rear) { + Q->front = Q->rear = -1; + Q->size = 0; + } else { + Q->front = (Q->front+1) % Q->capacity; + Q->size -= 1; + } + return data; +} + +void deleteQueue(struct Queue *Q) { + if(Q) { + if(Q->array) + free(Q->array); + free(Q); + } +} + +int main() { + // Initializing Queue + struct Queue *Q; + Q = createQueue(3); + + // Adding elements in Queue + enqueue(Q, 1); + enqueue(Q, 3); + enqueue(Q, 7); + enqueue(Q, 5); + enqueue(Q, 10); + enqueue(Q, 19); + + // Printing size of Queue + printf("\nSize of queue : %d\n", size(Q)); + + // Printing front and rear element of Queue */ + printf("Front element : %d\n", frontElement(Q)); + printf("Rear element : %d\n", rearElement(Q)); + + // Removing Element from Queue + printf("\nDequeued element : %d\n", dequeue(Q)); + printf("Dequeued element : %d\n", dequeue(Q)); + printf("Dequeued element : %d\n", dequeue(Q)); + printf("Dequeued element : %d\n", dequeue(Q)); + printf("Dequeued element : %d\n", dequeue(Q)); + printf("Dequeued element : %d\n", dequeue(Q)); + enqueue(Q, 15); + enqueue(Q, 100); + + // Printing size of Queue + printf("\nSize of queue : %d\n", size(Q)); + + // Printing front and rear element of Queue + printf("Front element : %d\n", frontElement(Q)); + printf("Rear element : %d\n", rearElement(Q)); + + // Removing Queue + deleteQueue(Q); + return 0; +} diff --git a/src/Chapter_04_Queues/QueueWithTwoStacks.c b/src/Chapter_04_Queues/QueueWithTwoStacks.c new file mode 100644 index 0000000..46ea0ea --- /dev/null +++ b/src/Chapter_04_Queues/QueueWithTwoStacks.c @@ -0,0 +1,156 @@ +/*Copyright (c) 2016 CareerMonk Publications and others. +#E-Mail : info@careermonk.com +#Creation Date : 2008-01-10 06:15:46 +#Created by : Narasimha Karumanchi +#Book Title : Data Structures And Algorithms Made Easy +#Warranty : This software is provided "as is" without any +# warranty; without even the implied warranty of +# merchantability or fitness for a particular purpose.*/ + +#include +#include +#include + +struct Stack { + int top; + int capacity; + int *array; +}; + +struct Stack *createStack(int capacity) { + struct Stack *S = malloc(sizeof(struct Stack)); + if(!S) + return NULL; + S->capacity = capacity; + S->top = -1; + S->array= malloc(S->capacity * sizeof(int)); + if(!S->array) + return NULL; + return S; +} + +int isEmpty(struct Stack *S) { + return (S->top == -1); // if the condition is true then 1 is returned else 0 is returned +} + +int size(struct Stack *S) { + return (S->top + 1); +} + +int isFull(struct Stack *S){ + //if the condition is true then 1 is returned else 0 is returned + return (S->top == S->capacity - 1); +} + +void doubleStack(struct Stack *S){ + S->capacity *= 2; + S->array = realloc(S->array, S->capacity * sizeof(int)); +} + + +void push(struct Stack *S, int data){ + if(isFull(S)) + doubleStack(S); + S->array[++S->top] = data; +} + +int pop(struct Stack *S){ + /* S->top == - 1 indicates empty stack*/ + if(isEmpty(S)){ + printf("Stack is Empty\n"); + return INT_MIN; + } + else /* Removing element from ‘top’ of the array and reducing ‘top’ by 1*/ + return (S->array[S->top--]); +} + +int peek(struct Stack *S){ + /* S->top == - 1 indicates empty stack*/ + if(isEmpty(S)){ + printf("Stack is Empty"); + return INT_MIN;; + } + else + return (S->array[S->top]); +} + +void deleteStack(struct Stack *S){ + if(S) { + if(S->array) + free(S->array); + free(S); + } +} + +struct Queue { + struct Stack *S1; // for enQueue + struct Stack *S2; // for deQueue +}; + +int queueSize(struct Queue *Q) { + return size(Q->S1); +} + +struct Queue *createQueue(int capacity) { + struct Stack *S1 = createStack(capacity); + struct Stack *S2 = createStack(capacity); + struct Queue *Q = malloc(sizeof(struct Queue)); + if(!Q) + return NULL; + Q->S1 = S1; + Q->S2 = S2; + return Q; +} + +void enQueue(struct Queue *Q, int data) { + push(Q->S1, data); +} + +int deQueue(struct Queue *Q) { + if(!isEmpty(Q->S2)) + return pop(Q->S2); + else { + while( !isEmpty(Q->S1) ) + push(Q->S2, pop(Q->S1)); + return pop(Q->S2); + } +} + +void deleteQueue(struct Queue *Q){ + if(Q) { + if(Q->S1) + free(Q->S1); + if(Q->S2) + free(Q->S2); + free(Q); + } +} + +int main(){ + // Initializing Queue + struct Queue *Q; + Q = createQueue(6); + + // Adding elements in Queue + enQueue(Q, 1); + enQueue(Q, 3); + enQueue(Q, 7); + enQueue(Q, 5); + enQueue(Q, 10); + enQueue(Q, 19); + + // Printing size of Queue + printf("\nSize of queue : %d\n", queueSize(Q)); + + // Removing Element from Queue + printf("\nDequeued element : %d\n", deQueue(Q)); + printf("Dequeued element : %d\n", deQueue(Q)); + printf("Dequeued element : %d\n", deQueue(Q)); + printf("Dequeued element : %d\n", deQueue(Q)); + printf("Dequeued element : %d\n", deQueue(Q)); + printf("Dequeued element : %d\n", deQueue(Q)); + + // Removing Queue + deleteQueue(Q); + return 0; +} diff --git a/src/Chapter_04_Queues/QueuesWithLinkedLists.c b/src/Chapter_04_Queues/QueuesWithLinkedLists.c new file mode 100644 index 0000000..cd4f7d7 --- /dev/null +++ b/src/Chapter_04_Queues/QueuesWithLinkedLists.c @@ -0,0 +1,176 @@ +// Copyright (c) 2008 CareerMonk Publications and others. +// #E-Mail : info@careermonk.com +// Creation Date : 2008-01-10 06:15:46 +// Created by : Narasimha Karumanchi +// Book Title : Data Structures And Algorithms Made Easy +// Warranty : This software is provided "as is" without any +// warranty; without even the implied warranty of +// merchantability or fitness for a particular purpose. + +#include +#include + +struct ListNode { + int data; + struct ListNode *next; +}; + +struct Queue { + struct ListNode *front; + struct ListNode *rear; +}; + +/* Create an empty queue */ +struct Queue *CreateQueue() { + struct Queue *Q; + struct ListNode *temp; + Q = malloc(sizeof(struct Queue)); + if(!Q) + return NULL; + + temp = malloc(sizeof(struct ListNode)); + Q->front = Q->rear = NULL; + return Q; +} + +/* Returns queue size */ +int size(struct Queue *Q) { + struct ListNode *temp = Q->front; + int count = 0; + + if(Q->front == NULL && Q->rear == NULL) + return 0; + + while(temp != Q->rear){ + count++; + temp = temp->next; + } + if(temp == Q->rear) + count++; + + return count; +} + +/* Returns Frnt Element of the Queue */ +int frontElement(struct Queue *Q) { + return Q->front->data; +} + +/* Returns the Rear Element of the Queue */ +int rearElement(struct Queue *Q) { + return Q->rear->data; +} + +/* +Check's if Queue is empty or not +*/ +void isEmpty(struct Queue *Q) { + if (Q->front == NULL && Q->rear == NULL) + printf("Empty Queue\n"); + else + printf("Queue is not Empty\n"); +} +/* +Adding elements in Queue +*/ +void enqueue(struct Queue *Q, int num) { + struct ListNode *temp; + temp = (struct ListNode *)malloc(sizeof(struct ListNode)); + temp->data = num; + temp->next = NULL; + + if (Q->rear == NULL) { + Q->front = Q->rear = temp; + } else { + Q->rear->next = temp; + Q->rear = temp; + } +} + +/* +Removes an element from front of the queue +*/ +void dequeue(struct Queue *Q) { + struct ListNode *temp; + if (Q->front == NULL) { + printf("\nQueue is Empty \n"); + return; + } else { + temp = Q->front; + Q->front = Q->front->next; + if(Q->front == NULL){ + Q->rear = NULL; + } + printf("Removed Element : %d\n", temp->data); + free(temp); + } +} + +/* + Print's Queue +*/ +void printQueue(struct Queue *Q) { + struct ListNode *temp = Q->front; + + if ((Q->front == NULL) && (Q->rear == NULL)) { + printf("Queue is Empty\n"); + return; + } + + while (temp != NULL) { + printf("%d", temp->data); + temp = temp->next; + if(temp != NULL) + printf("-->"); + } +} + +void deleteQueue(struct Queue *Q) { + struct ListNode *temp; + while(Q->front) { + temp = Q->front; + printf("Element being deleted: %d\n", temp->data); + Q->front = Q->front->next; + free(temp); + } + free(Q); +} + + +int main() { + /* Initializing Queue */ + struct Queue *Q; + Q = CreateQueue(); + /* Adding elements in Queue */ + enqueue(Q, 1); + enqueue(Q, 3); + enqueue(Q, 7); + enqueue(Q, 5); + enqueue(Q, 10); + /* Printing Queue */ + printQueue(Q); + /* Printing size of Queue */ + printf("\nSize of Queue : %d\n", size(Q)); + /* Printing front and rear element of Queue */ + printf("Front Element : %d\n", frontElement(Q)); + printf("Rear Element : %d\n", rearElement(Q)); + /* Removing Element from Queue */ + dequeue(Q); + dequeue(Q); + dequeue(Q); + dequeue(Q); + dequeue(Q); + dequeue(Q); + enqueue(Q, 15); + enqueue(Q, 100); + /* Printing Queue */ + printQueue(Q); + /* Printing size of Queue */ + printf("\nSize of Queue : %d\n", size(Q)); + /* Printing front and rear element of Queue */ + printf("Front Element : %d\n", frontElement(Q)); + printf("Rear Element : %d\n", rearElement(Q)); + /* Removing Queue */ + deleteQueue(Q); + return 0; +} diff --git a/src/Chapter_04_Queues/ReverseQueue.c b/src/Chapter_04_Queues/ReverseQueue.c new file mode 100644 index 0000000..6be573b --- /dev/null +++ b/src/Chapter_04_Queues/ReverseQueue.c @@ -0,0 +1,236 @@ +// Copyright (c) 2008 CareerMonk Publications and others. +// #E-Mail : info@careermonk.com +// Creation Date : 2008-01-10 06:15:46 +// Created by : Narasimha Karumanchi +// Book Title : Data Structures And Algorithms Made Easy +// Warranty : This software is provided "as is" without any +// warranty; without even the implied warranty of +// merchantability or fitness for a particular purpose. + +#include +#include +#include + +struct Stack { + int top; + int capacity; + int *array; +}; + +struct Stack *createStack(int capacity) { + struct Stack *S = malloc(sizeof(struct Stack)); + if(!S) + return NULL; + S->capacity = capacity; + S->top = -1; + S->array= malloc(S->capacity * sizeof(int)); + if(!S->array) + return NULL; + return S; +} + +int isEmptyStack(struct Stack *S) { + return (S->top == -1); // if the condition is true then 1 is returned else 0 is returned +} + +int stackSize(struct Stack *S) { + return (S->top + 1); +} + +int isFullStack(struct Stack *S){ + //if the condition is true then 1 is returned else 0 is returned + return (S->top == S->capacity - 1); +} + +void doubleStack(struct Stack *S){ + S->capacity *= 2; + S->array = realloc(S->array, S->capacity * sizeof(int)); +} + + +void push(struct Stack *S, int data){ + if(isEmptyStack(S)) + doubleStack(S); + S->array[++S->top] = data; +} + +int pop(struct Stack *S){ + /* S->top == - 1 indicates empty stack*/ + if(isEmptyStack(S)){ + printf("Stack is Empty\n"); + return INT_MIN; + } + else /* Removing element from ‘top’ of the array and reducing ‘top’ by 1*/ + return (S->array[S->top--]); +} + +int peek(struct Stack *S){ + /* S->top == - 1 indicates empty stack*/ + if(isEmptyStack(S)){ + printf("Stack is Empty"); + return INT_MIN;; + } + else + return (S->array[S->top]); +} + +void deleteStack(struct Stack *S){ + if(S) { + if(S->array) + free(S->array); + free(S); + } +} + +struct Queue { + int front, rear; + int capacity; + int size; + int *array; +}; + +// Create an empty queue +struct Queue *createQueue(int capacity) { + struct Queue *Q = malloc(sizeof(struct Queue)); + if(!Q) + return NULL; + Q->capacity = capacity; + Q->front = Q->rear = -1; + Q->size = 0; + Q->array= malloc(Q->capacity * sizeof(int)); + + if(!Q->array) + return NULL; + return Q; +} + +// Returns queue size +int queueSize(struct Queue *Q) { + return Q->size; +} + +// Returns Frnt Element of the Queue +int frontElement(struct Queue *Q) { + return Q->array[Q->front]; +} + +// Returns the Rear Element of the Queue +int rearElement(struct Queue *Q) { + return Q->array[Q->rear]; +} + +// Check's if Queue is empty or not +int isEmptyQueue(struct Queue *Q) { + // if the condition is true then 1 is returned else 0 is returned + return (Q->size == 0); +} + +// Check's if Queue is full or not +int isFullQueue(struct Queue *Q) { + // if the condition is true then 1 is returned else 0 is returned + return (Q->size == Q->capacity); +} + +void resizeQueue(struct Queue *Q) { + int size = Q->capacity; + Q->capacity = Q->capacity*2; + Q->array = realloc (Q->array, sizeof(int) * Q->capacity); + if(!Q->array) { + printf("Memory Error"); + return; + } + if(Q->front > Q->rear ) { + for(int i=0; i < Q->front; i++) { + Q->array[i+size] =Q->array[i]; + } + Q->rear = Q->rear + size; + } +} + + +// Adding elements in Queue +void enqueue(struct Queue *Q, int data) { + if(isFullQueue(Q)) + resizeQueue(Q); + Q->rear = (Q->rear+1) % Q->capacity; + Q->array[Q->rear]= data; + if(Q->front == -1) + Q->front = Q->rear; + Q->size += 1; +} + +// Removes an element from front of the queue +int dequeue(struct Queue *Q) { + int data = INT_MIN; //or element which does not exist in Queue + if(isEmptyQueue(Q)){ + printf("Queue is empty\n"); + return data; + } + data = Q->array[Q->front]; + if(Q->front == Q->rear) { + Q->front = Q->rear = -1; + Q->size = 0; + } else { + Q->front = (Q->front+1) % Q->capacity; + Q->size -= 1; + } + return data; +} + +void deleteQueue(struct Queue *Q) { + if(Q) { + if(Q->array) + free(Q->array); + free(Q); + } +} + +void reverseQueue(struct Queue *Q) { + struct Stack *S = createStack(5); + while (!isEmptyQueue(Q)) + push(S, dequeue(Q)); + while (!isEmptyStack(S)) + enqueue(Q, pop(S)); +} + + +int main() { + // Initializing Queue + struct Queue *Q; + Q = createQueue(3); + + // Adding elements in Queue + enqueue(Q, 1); + enqueue(Q, 3); + enqueue(Q, 7); + enqueue(Q, 5); + enqueue(Q, 10); + enqueue(Q, 19); + + // Printing size of Queue + printf("\nSize of queue : %d\n", queueSize(Q)); + + // Printing front and rear element of Queue */ + printf("Front element : %d\n", frontElement(Q)); + printf("Rear element : %d\n", rearElement(Q)); + + reverseQueue(Q); + + // Printing size of Queue + printf("\nSize of queue : %d\n", queueSize(Q)); + + // Printing front and rear element of Queue */ + printf("Front element : %d\n", frontElement(Q)); + printf("Rear element : %d\n", rearElement(Q)); + + // Removing Element from Queue + printf("\nDequeued element : %d\n", dequeue(Q)); + printf("Dequeued element : %d\n", dequeue(Q)); + printf("Dequeued element : %d\n", dequeue(Q)); + printf("Dequeued element : %d\n", dequeue(Q)); + printf("Dequeued element : %d\n", dequeue(Q)); + printf("Dequeued element : %d\n", dequeue(Q)); + // Removing Queue + deleteQueue(Q); + return 0; +} diff --git a/src/Chapter_04_Queues/SimpleQueue.c b/src/Chapter_04_Queues/SimpleQueue.c new file mode 100644 index 0000000..3af7296 --- /dev/null +++ b/src/Chapter_04_Queues/SimpleQueue.c @@ -0,0 +1,141 @@ +// Copyright (c) 2008 CareerMonk Publications and others. +// #E-Mail : info@careermonk.com +// Creation Date : 2008-01-10 06:15:46 +// Created by : Narasimha Karumanchi +// Book Title : Data Structures And Algorithms Made Easy +// Warranty : This software is provided "as is" without any +// warranty; without even the implied warranty of +// merchantability or fitness for a particular purpose. + +#include +#include +#include + +struct Queue { + int front, rear; + int capacity; + int size; + int *array; +}; + +// Create an empty queue +struct Queue *createQueue(int capacity) { + struct Queue *Q = malloc(sizeof(struct Queue)); + if(!Q) + return NULL; + Q->capacity = capacity; + Q->front = Q->rear = -1; + Q->size = 0; + Q->array= malloc(Q->capacity * sizeof(int)); + + if(!Q->array) + return NULL; + return Q; +} + +// Returns queue size +int size(struct Queue *Q) { + return Q->size; +} + +// Returns Frnt Element of the Queue +int frontElement(struct Queue *Q) { + return Q->array[Q->front]; +} + +// Returns the Rear Element of the Queue +int rearElement(struct Queue *Q) { + return Q->array[Q->rear]; +} + +// Check's if Queue is empty or not +int isEmpty(struct Queue *Q) { + // if the condition is true then 1 is returned else 0 is returned + return (Q->size == 0); +} + +// Check's if Queue is full or not +int isFull(struct Queue *Q) { + // if the condition is true then 1 is returned else 0 is returned + return (Q->size == Q->capacity); +} + +// Adding elements in Queue +void enqueue(struct Queue *Q, int data) { + if(isFull(Q)) + printf("Queue overflow\n"); + else { + Q->rear = (Q->rear+1) % Q->capacity; + Q->array[Q->rear]= data; + if(Q->front == -1) + Q->front = Q->rear; + Q->size += 1; + } +} + +// Removes an element from front of the queue +int dequeue(struct Queue *Q) { + int data = INT_MIN; //or element which does not exist in Queue + if(isEmpty(Q)){ + printf("Queue is empty\n"); + return data; + } + data = Q->array[Q->front]; + if(Q->front == Q->rear) { + Q->front = Q->rear = -1; + Q->size = 0; + } else { + Q->front = (Q->front+1) % Q->capacity; + Q->size -= 1; + } + return data; +} + +void deleteQueue(struct Queue *Q) { + if(Q) { + if(Q->array) + free(Q->array); + free(Q); + } +} + +int main() { + // Initializing Queue + struct Queue *Q; + Q = createQueue(4); + // Adding elements in Queue + enqueue(Q, 1); + enqueue(Q, 3); + enqueue(Q, 7); + enqueue(Q, 5); + enqueue(Q, 10); + + // Printing size of Queue + printf("\nSize of queue : %d\n", size(Q)); + + // Printing front and rear element of Queue */ + printf("Front element : %d\n", frontElement(Q)); + printf("Rear element : %d\n", rearElement(Q)); + + // Removing Element from Queue + printf("\nDequeued element : %d\n", dequeue(Q)); + printf("Dequeued element : %d\n", dequeue(Q)); + printf("Dequeued element : %d\n", dequeue(Q)); + printf("Dequeued element : %d\n", dequeue(Q)); + printf("Dequeued element : %d\n", dequeue(Q)); + printf("Dequeued element : %d\n", dequeue(Q)); + enqueue(Q, 15); + enqueue(Q, 100); + + // Printing size of Queue + printf("\nSize of queue : %d\n", size(Q)); + + // Printing front and rear element of Queue + printf("Front element : %d\n", frontElement(Q)); + printf("Rear element : %d\n", rearElement(Q)); + + // Removing Queue + deleteQueue(Q); + return 0; +} + diff --git a/src/Chapter_04_Stacks/DynamicStack.c b/src/Chapter_04_Stacks/DynamicStack.c index 657771d..da9a003 100644 --- a/src/Chapter_04_Stacks/DynamicStack.c +++ b/src/Chapter_04_Stacks/DynamicStack.c @@ -7,82 +7,103 @@ # warranty; without even the implied warranty of # merchantability or fitness for a particular purpose.*/ -#include +#include #include #include -struct DynArrayStack { +struct Stack { int top; int capacity; int *array; }; -struct DynArrayStack *CreateStack(){ - struct DynArrayStack *S = malloc(sizeof(struct DynArrayStack)); +struct Stack *createStack(int capacity) { + struct Stack *S = malloc(sizeof(struct Stack)); if(!S) - return NULL; - S->capacity = 1; + return NULL; + S->capacity = capacity; S->top = -1; - S->array = malloc(S->capacity * sizeof(int)); // allocate an array of size 1 initially - + S->array= malloc(S->capacity * sizeof(int)); if(!S->array) return NULL; return S; } -int IsFullStack(struct DynArrayStack *S){ - return (S->top == S->capacity-1); +int isEmpty(struct Stack *S) { + return (S->top == -1); // if the condition is true then 1 is returned else 0 is returned +} + +int size(struct Stack *S) { + return (S->top + 1); } -void DoubleStack(struct DynArrayStack *S){ +int isFull(struct Stack *S){ + //if the condition is true then 1 is returned else 0 is returned + return (S->top == S->capacity - 1); +} + +void doubleStack(struct Stack *S){ S->capacity *= 2; S->array = realloc(S->array, S->capacity * sizeof(int)); } -void Push(struct DynArrayStack *S, int x){ - // No overflow in this implementation - if(IsFullStack(S)) - DoubleStack(S); - S->array[++S->top] = x; +void push(struct Stack *S, int data){ + if(isFull(S)) + doubleStack(S); + S->array[++S->top] = data; } -int IsEmptyStack(struct DynArrayStack *S){ - return S->top == -1; +int pop(struct Stack *S){ + /* S->top == - 1 indicates empty stack*/ + if(isEmpty(S)){ + printf("Stack is Empty\n"); + return INT_MIN; + } + else /* Removing element from ‘top’ of the array and reducing ‘top’ by 1*/ + return (S->array[S->top--]); } -int Top(struct DynArrayStack *S){ - if(IsEmptyStack(S)) - return INT_MIN; +int peek(struct Stack *S){ + /* S->top == - 1 indicates empty stack*/ + if(isEmpty(S)){ + printf("Stack is Empty"); + return INT_MIN;; + } + else + return (S->array[S->top]); +} - return S->array[S->top]; +void deleteStack(struct Stack *S){ + if(S) { + if(S->array) + free(S->array); + free(S); + } } -int Pop(struct DynArrayStack *S){ - if(IsEmptyStack(S)) - return INT_MIN; - return S->array[S->top--]; -} +int main(){ + int i = 0, capacity = 5; + // create a stack of capacity 5 + struct Stack *stk = createStack(capacity); -void DeleteDynStack(struct DynArrayStack *S){ - if(S) { - if(S->array) - free(S->array); - free(S); + for(i = 0; i <= 2 * capacity; i++){ + push(stk, i); } -} -void testDynamicStack(){ - struct DynArrayStack *s = CreateStack(); - Push(s, 10); - Push(s, 1); - Push(s, 11); - Push(s, 2); - Push(s, 10); - Push(s, 50); - while(!IsEmptyStack(s)){ - printf("%d\n", Pop(s)); + printf("Top element is %d\n", peek(stk)); + printf("Stack size is %d\n", size(stk)); + + for (i = 0; i <= capacity; i++){ + printf("Popped element is %d\n", pop(stk)); } - DeleteDynStack(s); -} \ No newline at end of file + + if (isEmpty(stk)) + printf("Stack is empty"); + else + printf("Stack is not empty"); + + deleteStack(stk); + return 0; +} diff --git a/src/Chapter_04_Stacks/QueueWithTwoStacks.c b/src/Chapter_04_Stacks/QueueWithTwoStacks.c new file mode 100644 index 0000000..46ea0ea --- /dev/null +++ b/src/Chapter_04_Stacks/QueueWithTwoStacks.c @@ -0,0 +1,156 @@ +/*Copyright (c) 2016 CareerMonk Publications and others. +#E-Mail : info@careermonk.com +#Creation Date : 2008-01-10 06:15:46 +#Created by : Narasimha Karumanchi +#Book Title : Data Structures And Algorithms Made Easy +#Warranty : This software is provided "as is" without any +# warranty; without even the implied warranty of +# merchantability or fitness for a particular purpose.*/ + +#include +#include +#include + +struct Stack { + int top; + int capacity; + int *array; +}; + +struct Stack *createStack(int capacity) { + struct Stack *S = malloc(sizeof(struct Stack)); + if(!S) + return NULL; + S->capacity = capacity; + S->top = -1; + S->array= malloc(S->capacity * sizeof(int)); + if(!S->array) + return NULL; + return S; +} + +int isEmpty(struct Stack *S) { + return (S->top == -1); // if the condition is true then 1 is returned else 0 is returned +} + +int size(struct Stack *S) { + return (S->top + 1); +} + +int isFull(struct Stack *S){ + //if the condition is true then 1 is returned else 0 is returned + return (S->top == S->capacity - 1); +} + +void doubleStack(struct Stack *S){ + S->capacity *= 2; + S->array = realloc(S->array, S->capacity * sizeof(int)); +} + + +void push(struct Stack *S, int data){ + if(isFull(S)) + doubleStack(S); + S->array[++S->top] = data; +} + +int pop(struct Stack *S){ + /* S->top == - 1 indicates empty stack*/ + if(isEmpty(S)){ + printf("Stack is Empty\n"); + return INT_MIN; + } + else /* Removing element from ‘top’ of the array and reducing ‘top’ by 1*/ + return (S->array[S->top--]); +} + +int peek(struct Stack *S){ + /* S->top == - 1 indicates empty stack*/ + if(isEmpty(S)){ + printf("Stack is Empty"); + return INT_MIN;; + } + else + return (S->array[S->top]); +} + +void deleteStack(struct Stack *S){ + if(S) { + if(S->array) + free(S->array); + free(S); + } +} + +struct Queue { + struct Stack *S1; // for enQueue + struct Stack *S2; // for deQueue +}; + +int queueSize(struct Queue *Q) { + return size(Q->S1); +} + +struct Queue *createQueue(int capacity) { + struct Stack *S1 = createStack(capacity); + struct Stack *S2 = createStack(capacity); + struct Queue *Q = malloc(sizeof(struct Queue)); + if(!Q) + return NULL; + Q->S1 = S1; + Q->S2 = S2; + return Q; +} + +void enQueue(struct Queue *Q, int data) { + push(Q->S1, data); +} + +int deQueue(struct Queue *Q) { + if(!isEmpty(Q->S2)) + return pop(Q->S2); + else { + while( !isEmpty(Q->S1) ) + push(Q->S2, pop(Q->S1)); + return pop(Q->S2); + } +} + +void deleteQueue(struct Queue *Q){ + if(Q) { + if(Q->S1) + free(Q->S1); + if(Q->S2) + free(Q->S2); + free(Q); + } +} + +int main(){ + // Initializing Queue + struct Queue *Q; + Q = createQueue(6); + + // Adding elements in Queue + enQueue(Q, 1); + enQueue(Q, 3); + enQueue(Q, 7); + enQueue(Q, 5); + enQueue(Q, 10); + enQueue(Q, 19); + + // Printing size of Queue + printf("\nSize of queue : %d\n", queueSize(Q)); + + // Removing Element from Queue + printf("\nDequeued element : %d\n", deQueue(Q)); + printf("Dequeued element : %d\n", deQueue(Q)); + printf("Dequeued element : %d\n", deQueue(Q)); + printf("Dequeued element : %d\n", deQueue(Q)); + printf("Dequeued element : %d\n", deQueue(Q)); + printf("Dequeued element : %d\n", deQueue(Q)); + + // Removing Queue + deleteQueue(Q); + return 0; +} diff --git a/src/Chapter_04_Stacks/ReverseQueue.c b/src/Chapter_04_Stacks/ReverseQueue.c new file mode 100644 index 0000000..6be573b --- /dev/null +++ b/src/Chapter_04_Stacks/ReverseQueue.c @@ -0,0 +1,236 @@ +// Copyright (c) 2008 CareerMonk Publications and others. +// #E-Mail : info@careermonk.com +// Creation Date : 2008-01-10 06:15:46 +// Created by : Narasimha Karumanchi +// Book Title : Data Structures And Algorithms Made Easy +// Warranty : This software is provided "as is" without any +// warranty; without even the implied warranty of +// merchantability or fitness for a particular purpose. + +#include +#include +#include + +struct Stack { + int top; + int capacity; + int *array; +}; + +struct Stack *createStack(int capacity) { + struct Stack *S = malloc(sizeof(struct Stack)); + if(!S) + return NULL; + S->capacity = capacity; + S->top = -1; + S->array= malloc(S->capacity * sizeof(int)); + if(!S->array) + return NULL; + return S; +} + +int isEmptyStack(struct Stack *S) { + return (S->top == -1); // if the condition is true then 1 is returned else 0 is returned +} + +int stackSize(struct Stack *S) { + return (S->top + 1); +} + +int isFullStack(struct Stack *S){ + //if the condition is true then 1 is returned else 0 is returned + return (S->top == S->capacity - 1); +} + +void doubleStack(struct Stack *S){ + S->capacity *= 2; + S->array = realloc(S->array, S->capacity * sizeof(int)); +} + + +void push(struct Stack *S, int data){ + if(isEmptyStack(S)) + doubleStack(S); + S->array[++S->top] = data; +} + +int pop(struct Stack *S){ + /* S->top == - 1 indicates empty stack*/ + if(isEmptyStack(S)){ + printf("Stack is Empty\n"); + return INT_MIN; + } + else /* Removing element from ‘top’ of the array and reducing ‘top’ by 1*/ + return (S->array[S->top--]); +} + +int peek(struct Stack *S){ + /* S->top == - 1 indicates empty stack*/ + if(isEmptyStack(S)){ + printf("Stack is Empty"); + return INT_MIN;; + } + else + return (S->array[S->top]); +} + +void deleteStack(struct Stack *S){ + if(S) { + if(S->array) + free(S->array); + free(S); + } +} + +struct Queue { + int front, rear; + int capacity; + int size; + int *array; +}; + +// Create an empty queue +struct Queue *createQueue(int capacity) { + struct Queue *Q = malloc(sizeof(struct Queue)); + if(!Q) + return NULL; + Q->capacity = capacity; + Q->front = Q->rear = -1; + Q->size = 0; + Q->array= malloc(Q->capacity * sizeof(int)); + + if(!Q->array) + return NULL; + return Q; +} + +// Returns queue size +int queueSize(struct Queue *Q) { + return Q->size; +} + +// Returns Frnt Element of the Queue +int frontElement(struct Queue *Q) { + return Q->array[Q->front]; +} + +// Returns the Rear Element of the Queue +int rearElement(struct Queue *Q) { + return Q->array[Q->rear]; +} + +// Check's if Queue is empty or not +int isEmptyQueue(struct Queue *Q) { + // if the condition is true then 1 is returned else 0 is returned + return (Q->size == 0); +} + +// Check's if Queue is full or not +int isFullQueue(struct Queue *Q) { + // if the condition is true then 1 is returned else 0 is returned + return (Q->size == Q->capacity); +} + +void resizeQueue(struct Queue *Q) { + int size = Q->capacity; + Q->capacity = Q->capacity*2; + Q->array = realloc (Q->array, sizeof(int) * Q->capacity); + if(!Q->array) { + printf("Memory Error"); + return; + } + if(Q->front > Q->rear ) { + for(int i=0; i < Q->front; i++) { + Q->array[i+size] =Q->array[i]; + } + Q->rear = Q->rear + size; + } +} + + +// Adding elements in Queue +void enqueue(struct Queue *Q, int data) { + if(isFullQueue(Q)) + resizeQueue(Q); + Q->rear = (Q->rear+1) % Q->capacity; + Q->array[Q->rear]= data; + if(Q->front == -1) + Q->front = Q->rear; + Q->size += 1; +} + +// Removes an element from front of the queue +int dequeue(struct Queue *Q) { + int data = INT_MIN; //or element which does not exist in Queue + if(isEmptyQueue(Q)){ + printf("Queue is empty\n"); + return data; + } + data = Q->array[Q->front]; + if(Q->front == Q->rear) { + Q->front = Q->rear = -1; + Q->size = 0; + } else { + Q->front = (Q->front+1) % Q->capacity; + Q->size -= 1; + } + return data; +} + +void deleteQueue(struct Queue *Q) { + if(Q) { + if(Q->array) + free(Q->array); + free(Q); + } +} + +void reverseQueue(struct Queue *Q) { + struct Stack *S = createStack(5); + while (!isEmptyQueue(Q)) + push(S, dequeue(Q)); + while (!isEmptyStack(S)) + enqueue(Q, pop(S)); +} + + +int main() { + // Initializing Queue + struct Queue *Q; + Q = createQueue(3); + + // Adding elements in Queue + enqueue(Q, 1); + enqueue(Q, 3); + enqueue(Q, 7); + enqueue(Q, 5); + enqueue(Q, 10); + enqueue(Q, 19); + + // Printing size of Queue + printf("\nSize of queue : %d\n", queueSize(Q)); + + // Printing front and rear element of Queue */ + printf("Front element : %d\n", frontElement(Q)); + printf("Rear element : %d\n", rearElement(Q)); + + reverseQueue(Q); + + // Printing size of Queue + printf("\nSize of queue : %d\n", queueSize(Q)); + + // Printing front and rear element of Queue */ + printf("Front element : %d\n", frontElement(Q)); + printf("Rear element : %d\n", rearElement(Q)); + + // Removing Element from Queue + printf("\nDequeued element : %d\n", dequeue(Q)); + printf("Dequeued element : %d\n", dequeue(Q)); + printf("Dequeued element : %d\n", dequeue(Q)); + printf("Dequeued element : %d\n", dequeue(Q)); + printf("Dequeued element : %d\n", dequeue(Q)); + printf("Dequeued element : %d\n", dequeue(Q)); + // Removing Queue + deleteQueue(Q); + return 0; +} diff --git a/src/Chapter_04_Stacks/StackWithLinkedLists.c b/src/Chapter_04_Stacks/StackWithLinkedLists.c new file mode 100644 index 0000000..98a9562 --- /dev/null +++ b/src/Chapter_04_Stacks/StackWithLinkedLists.c @@ -0,0 +1,111 @@ +/*Copyright (c) 2016 CareerMonk Publications and others. +#E-Mail : info@careermonk.com +#Creation Date : 2008-01-10 06:15:46 +#Created by : Narasimha Karumanchi +#Book Title : Data Structures And Algorithms Made Easy +#Warranty : This software is provided "as is" without any +# warranty; without even the implied warranty of +# merchantability or fitness for a particular purpose.*/ + +#include +#include +#include + +struct ListNode{ + int data; + struct ListNode *next; +}; + +struct Stack{ + struct ListNode *top; +}; + +struct Stack *createStack(){ + struct Stack *stk; + stk = malloc(sizeof(struct Stack)); + stk->top = NULL; + return stk; +} + +void push(struct Stack *stk, int data){ + struct ListNode *temp; + temp = malloc(sizeof(struct ListNode)); + if(!temp){ + printf("\nStack/Heap overflow"); + return; + } + temp->data = data; + temp->next = stk->top; + stk->top = temp; +} + +int size(struct Stack *stk){ + // we can improve the size function by adding extra size variable in stack structure + // and update it while push/pop operations + int count = 0; + struct ListNode *temp; + if(isEmpty(stk)) + return 0; + temp = stk->top; + while (temp){ + count++; + temp = temp->next; + } + return count; +} + +int isEmpty(struct Stack *stk){ + return stk->top == NULL; +} + +int pop(struct Stack *stk){ + int data; + struct ListNode *temp; + if(isEmpty(stk)) + return INT_MIN; + temp = stk->top; + stk->top = stk->top->next; + data = temp->data; + free(temp); + return data; +} + +int peek(struct Stack * stk){ + if(isEmpty(stk)) + return INT_MIN; + return stk->top->data; +} + +void deleteStack(struct Stack *stk){ + struct ListNode *temp, *p; + p = stk->top; + while( p) { + temp = p->next; + free(p); + p = temp; + } + free(stk); + } + int main(){ + int i = 0; + struct Stack *stk = createStack(); + + for(i = 0; i <= 10; i++){ + push(stk, i); + } + + printf("Top element is %d\n", peek(stk)); + printf("Stack size is %d\n", size(stk)); + + for (i = 0; i <= 10; i++){ + printf("Popped element is %d\n", pop(stk)); + } + + if (isEmpty(stk)) + printf("Stack is empty"); + else + printf("Stack is not empty"); + + deleteStack(stk); + return 0; + } diff --git a/src/Chapter_04_Stacks/TwoStacksInOneArray.c b/src/Chapter_04_Stacks/TwoStacksInOneArray.c new file mode 100644 index 0000000..8057b53 --- /dev/null +++ b/src/Chapter_04_Stacks/TwoStacksInOneArray.c @@ -0,0 +1,119 @@ +/*Copyright (c) 2016 CareerMonk Publications and others. +#E-Mail : info@careermonk.com +#Creation Date : 2008-01-10 06:15:46 +#Created by : Narasimha Karumanchi +#Book Title : Data Structures And Algorithms Made Easy +#Warranty : This software is provided "as is" without any +# warranty; without even the implied warranty of +# merchantability or fitness for a particular purpose.*/ + +#include +#include +#include +#include + +struct MultiStacks { + int top1, top2; + int capacity; + char *array; +}; + +struct MultiStacks *createStack(int capacity) { + struct MultiStacks *twoStacks = malloc(sizeof(struct MultiStacks)); + if(!twoStacks) + return NULL; + twoStacks->capacity = capacity; + twoStacks->top1 = -1; + twoStacks->top2 = capacity; + twoStacks->array= malloc(twoStacks->capacity * sizeof(int)); + if(!twoStacks->array) + return NULL; + return twoStacks; +} + +int isEmpty(struct MultiStacks *twoStacks, int stackNumber) { + if (stackNumber == 1){ + return (twoStacks->top1 == -1); + } else { + return (twoStacks->top2 == twoStacks->capacity); + } +} + +int size(struct MultiStacks *twoStacks, int stackNumber) { + if (stackNumber == 1){ + return (twoStacks->top1 + 1); + } else { + return (twoStacks->capacity - twoStacks->top2); + } +} + +int isFull(struct MultiStacks *twoStacks){ + return (size(twoStacks, 1) + size(twoStacks, 2) == twoStacks->capacity); +} + +void push(struct MultiStacks *twoStacks, int stackNumber, char data){ + if(isFull(twoStacks)){ + printf("Stack overflow\n"); + return; + } + if (stackNumber == 1){ + twoStacks->array[++twoStacks->top1] = data; + } else { + twoStacks->array[--twoStacks->top2] = data; + } +} + +char pop(struct MultiStacks *twoStacks, int stackNumber){ + /* twoStacks->top == - 1 indicates empty stack*/ + if(isEmpty(twoStacks, stackNumber)){ + printf("Stack is Empty\n"); + return '\0'; + } + if (stackNumber == 1){ + return (twoStacks->array[twoStacks->top1--]); + } else { + return (twoStacks->array[twoStacks->top2++]); + } +} + +int peek(struct MultiStacks *twoStacks, int stackNumber){ + if(isEmpty(twoStacks, stackNumber)){ + printf("Stack is Empty"); + return INT_MIN;; + } + if (stackNumber == 1){ + return (twoStacks->array[twoStacks->top1]); + } else { + return (twoStacks->array[twoStacks->top2]); + } +} + +void deleteStack(struct MultiStacks *twoStacks){ + if(twoStacks) { + if(twoStacks->array) + free(twoStacks->array); + free(twoStacks); + } +} + +int main(void){ + int i = 0, capacity = 15; + // create a stack of capacity 15 + struct MultiStacks *stk = createStack(capacity); + + for(i = 0; i <= capacity; i++){ + printf("Pushing %d to %d\n", i, i%2+1); + push(stk, i%2+1, i); + } + printf("Top element in first stack is %d\n", peek(stk, 1)); + printf("Top element in second stack is %d\n", peek(stk, 2)); + printf("Size of first stack is %d\n", size(stk,1)); + printf("Size of second stack is %d\n", size(stk,2)); + + for (i = 0; i <= capacity; i++){ + printf("Popped element from stack %d is %d\n", i%2+1, pop(stk, i%2+1)); + } + deleteStack(stk); + return 0; +} + diff --git a/src/Chapter_04_Stacks/balanced parenthesis using stack b/src/Chapter_04_Stacks/balanced parenthesis using stack new file mode 100644 index 0000000..36fe199 --- /dev/null +++ b/src/Chapter_04_Stacks/balanced parenthesis using stack @@ -0,0 +1,89 @@ +#include +#include +#include +#define size 100 + +struct node +{ + char data; + struct node* link; +}; +int c=0; +struct node * head; + +void push(char x) +{ +struct node*p,*temp; + temp=(struct node*)malloc(sizeof(struct node)); + temp->data=x; + if(head==NULL) + { + head=temp; + p=head; + p->link=NULL; + c++; + } + else + { + temp->link=p; + p=temp; + head=p; + c++; + } + +} +char pop(void) +{ + char x; + struct node*p=head; + x=p->data; + head=p->link; + free(p); + c--; + return x; + +} + +int isBalanced(char *s) { //{[()]} + int i=0;char x; + while(s[i]!='\0') + { + if(s[i]=='{'||s[i]=='('||s[i]=='[') + push(s[i]); + else + { + if(c<=0) + return 0; + + + x=pop(); + if( x=='{'&&s[i]!='}') + return 0; + if(x=='['&&s[i]!=']') + return 0; + if(x=='('&&s[i]!=')') + return 0 ; + }i++; + } + if(c==0) + return 1; + else + return 0; +} + +int main() { + int t; + scanf("%d",&t); + for(int a0 = 0; a0 < t; a0++){ + char s[size]; +int result; + scanf("%s",s); + result = isBalanced(s); +if(result==1) +printf("\nYES"); +else + printf("\nNO"); + + } + return 0; +} diff --git a/src/Chapter_04_Stacks/find_spans.c b/src/Chapter_04_Stacks/find_spans.c new file mode 100644 index 0000000..a8773d2 --- /dev/null +++ b/src/Chapter_04_Stacks/find_spans.c @@ -0,0 +1,51 @@ +// Copyright (c) 2008 CareerMonk Publications and others. +// #E-Mail : info@careermonk.com +// Creation Date : 2008-01-10 06:15:46 +// Created by : Narasimha Karumanchi +// Book Title : Data Structures And Algorithms Made Easy +// Warranty : This software is provided "as is" without any +// warranty; without even the implied warranty of +// merchantability or fitness for a particular purpose. + +#include +#include + +#define MAX_N 100000 + +int stack[MAX_N], top = -1; + +int largest_rectangle_area(int heights[], int n) { + int max_area = 0, i = 0; + while (i < n) { + if (top == -1 || heights[i] >= heights[stack[top]]) { + stack[++top] = i++; + } else { + int top_index = stack[top--]; + int area = heights[top_index] * (top == -1 ? i : i - stack[top] - 1); + if (area > max_area) { + max_area = area; + } + } + } + while (top != -1) { + int top_index = stack[top--]; + int area = heights[top_index] * (top == -1 ? i : i - stack[top] - 1); + if (area > max_area) { + max_area = area; + } + } + return max_area; +} + +int main() { + int n, heights[MAX_N]; + printf("Enter the number of bars in the histogram: "); + scanf("%d", &n); + printf("Enter the heights of the bars:\n"); + for (int i = 0; i < n; i++) { + scanf("%d", &heights[i]); + } + int max_area = largest_rectangle_area(heights, n); + printf("The largest rectangle under the histogram has area %d\n", max_area); + return 0; +} diff --git a/src/Chapter_04_Stacks/findingSpan.cpp b/src/Chapter_04_Stacks/findingSpan.cpp new file mode 100644 index 0000000..cd81bb8 --- /dev/null +++ b/src/Chapter_04_Stacks/findingSpan.cpp @@ -0,0 +1,39 @@ +/* + Author : Shivam Chauhan + Date : Feb 28 , 2019 + Finding the Span +*/ + +#include +using namespace std; +void getSpan( int span[] , int n ) +{ + stacks; + int calculatedSpan[n] , price ; + for ( int i = 0 ; i < n ; i++ ) + { + while( !s.empty() && span[s.top()] <= span[i] ) + { + s.pop(); + } + calculatedSpan[i] = i - ( s.empty() ? -1 : s.top() ) ; + s.push(i); + } + for( int i = 0 ; i < n ; i++ ) + { + cout << calculatedSpan[i] << " "; + } + cout << endl ; +} +int main() +{ + int n ; + cin >> n ; + int span[n]; + for ( int i = 0 ; i < n ; i++ ) + { + cin >> span[i]; + } + getSpan(span,n); + return 0 ; +} \ No newline at end of file diff --git a/src/Chapter_04_Stacks/getMinimum.c b/src/Chapter_04_Stacks/getMinimum.c new file mode 100644 index 0000000..0ebbcd8 --- /dev/null +++ b/src/Chapter_04_Stacks/getMinimum.c @@ -0,0 +1,173 @@ +/*Copyright (c) 2016 CareerMonk Publications and others. +#E-Mail : info@careermonk.com +#Creation Date : 2008-01-10 06:15:46 +#Created by : Narasimha Karumanchi +#Book Title : Data Structures And Algorithms Made Easy +#Warranty : This software is provided "as is" without any +# warranty; without even the implied warranty of +# merchantability or fitness for a particular purpose.*/ + +#include +#include +#include + +struct Stack { + int top; + int capacity; + int *array; +}; + +struct Stack *createStack(int capacity) { + struct Stack *S = malloc(sizeof(struct Stack)); + if(!S) + return NULL; + S->capacity = capacity; + S->top = -1; + S->array= malloc(S->capacity * sizeof(int)); + if(!S->array) + return NULL; + return S; +} + +int isEmpty(struct Stack *S) { + return (S->top == -1); // if the condition is true then 1 is returned else 0 is returned +} + +int size(struct Stack *S) { + return (S->top + 1); +} + +int isFull(struct Stack *S){ + //if the condition is true then 1 is returned else 0 is returned + return (S->top == S->capacity - 1); +} + +void doubleStack(struct Stack *S){ + S->capacity *= 2; + S->array = realloc(S->array, S->capacity * sizeof(int)); +} + + +void push(struct Stack *S, int data){ + if(isFull(S)) + doubleStack(S); + S->array[++S->top] = data; +} + +int pop(struct Stack *S){ + /* S->top == - 1 indicates empty stack*/ + if(isEmpty(S)){ + printf("Stack is Empty\n"); + return INT_MIN; + } + else /* Removing element from ‘top’ of the array and reducing ‘top’ by 1*/ + return (S->array[S->top--]); +} + +int peek(struct Stack *S){ + /* S->top == - 1 indicates empty stack*/ + if(isEmpty(S)){ + printf("Stack is Empty"); + return INT_MIN;; + } + else + return (S->array[S->top]); +} + +void deleteStack(struct Stack *S){ + if(S) { + if(S->array) + free(S->array); + free(S); + } +} +struct AdvancedStack { + struct Stack *elementStack; + struct Stack *minStack; +}; + + +int isEmptyA(struct AdvancedStack *S) { + return (S->elementStack->top == -1); // if the condition is true then 1 is returned else 0 is returned +} + +int sizeA(struct AdvancedStack *S) { + return (S->elementStack->top + 1); +} + +int isFullA(struct AdvancedStack *S){ + //if the condition is true then 1 is returned else 0 is returned + return (S->elementStack->top == S->elementStack->capacity - 1); +} + +void pushA(struct AdvancedStack *S, int data){ + push(S->elementStack, data); + + if(isEmpty(S->minStack) || peek(S->minStack) >= data) + push (S->minStack, data); +} + +int popA(struct AdvancedStack *S ){ + int temp; + + if(isEmpty(S->elementStack)) + return INT_MIN; + + temp = peek(S->elementStack); + + if(peek(S->minStack) == pop(S->elementStack)) + pop (S->minStack); + return temp; +} + +int peekA(struct AdvancedStack *S ){ + return peek(S->elementStack); +} + +int getMinimum(struct AdvancedStack *S){ + return peek(S->minStack); +} + +struct AdvancedStack * createAdvancedStack(int capacity){ + struct AdvancedStack *S = malloc (sizeof (struct AdvancedStack)); + + if(!S) + return NULL; + + S->elementStack = createStack(capacity); + S->minStack = createStack(capacity); + return S; +} + +void deleteStackA(struct AdvancedStack *S){ + if(S) { + deleteStackA(S->elementStack); + deleteStackA(S->minStack); + free(S); + } +} + +int main(){ + int i = 0, capacity = 5; + // create a stack of capacity 5 + struct AdvancedStack *stk = createAdvancedStack(capacity); + + for(i = 0; i <= 2 * capacity; i++){ + pushA(stk, i); + } + + printf("Top element is %d\n", peekA(stk)); + printf("Stack size is %d\n", sizeA(stk)); + + for (i = 0; i <= capacity; i++){ + printf("Popped element is %d\n", popA(stk)); + } + + if (isEmptyA(stk)) + printf("Stack is empty"); + else + printf("Stack is not empty"); + + deleteStackA(stk); + return 0; +} diff --git a/src/Chapter_04_Stacks/getMinimums.c b/src/Chapter_04_Stacks/getMinimums.c new file mode 100644 index 0000000..d16bc84 --- /dev/null +++ b/src/Chapter_04_Stacks/getMinimums.c @@ -0,0 +1,173 @@ +/*Copyright (c) 2016 CareerMonk Publications and others. +#E-Mail : info@careermonk.com +#Creation Date : 2008-01-10 06:15:46 +#Created by : Narasimha Karumanchi +#Book Title : Data Structures And Algorithms Made Easy +#Warranty : This software is provided "as is" without any +# warranty; without even the implied warranty of +# merchantability or fitness for a particular purpose.*/ + +#include +#include +#include + +struct Stack { + int top; + int capacity; + int *array; +}; + +struct Stack *createStack(int capacity) { + struct Stack *S = malloc(sizeof(struct Stack)); + if(!S) + return NULL; + S->capacity = capacity; + S->top = -1; + S->array= malloc(S->capacity * sizeof(int)); + if(!S->array) + return NULL; + return S; +} + +int isEmpty(struct Stack *S) { + return (S->top == -1); // if the condition is true then 1 is returned else 0 is returned +} + +int size(struct Stack *S) { + return (S->top + 1); +} + +int isFull(struct Stack *S){ + //if the condition is true then 1 is returned else 0 is returned + return (S->top == S->capacity - 1); +} + +void doubleStack(struct Stack *S){ + S->capacity *= 2; + S->array = realloc(S->array, S->capacity * sizeof(int)); +} + + +void push(struct Stack *S, int data){ + if(isFull(S)) + doubleStack(S); + S->array[++S->top] = data; +} + +int pop(struct Stack *S){ + /* S->top == - 1 indicates empty stack*/ + if(isEmpty(S)){ + printf("Stack is Empty\n"); + return INT_MIN; + } + else /* Removing element from ‘top’ of the array and reducing ‘top’ by 1*/ + return (S->array[S->top--]); +} + +int peek(struct Stack *S){ + /* S->top == - 1 indicates empty stack*/ + if(isEmpty(S)){ + printf("Stack is Empty"); + return INT_MIN;; + } + else + return (S->array[S->top]); +} + +void deleteStack(struct Stack *S){ + if(S) { + if(S->array) + free(S->array); + free(S); + } +} +struct AdvancedStack { + struct Stack *elementStack; + struct Stack *minStack; +}; + + +int isEmptyA(struct AdvancedStack *S) { + return (S->elementStack->top == -1); // if the condition is true then 1 is returned else 0 is returned +} + +int sizeA(struct AdvancedStack *S) { + return (S->elementStack->top + 1); +} + +int isFullA(struct AdvancedStack *S){ + //if the condition is true then 1 is returned else 0 is returned + return (S->elementStack->top == S->elementStack->capacity - 1); +} + +void pushA(struct AdvancedStack *S, int data){ + push(S->elementStack, data); + + if(isEmpty(S->minStack) || peek(S->minStack) >= data) + push(S->minStack, data); + +} + +int popA(struct AdvancedStack *S ){ + int temp; + if(isEmpty(S->elementStack)) + return -1; + + temp = peek(S->elementStack); + if(peek(S->minStack) == pop(S->elementStack)) + pop(S->minStack); + return temp; +} + +int peekA(struct AdvancedStack *S ){ + return peek(S->elementStack); +} + +int getMinimum(struct AdvancedStack *S){ + return peek(S->minStack); +} + +struct AdvancedStack * createAdvancedStack(int capacity){ + struct AdvancedStack *S = malloc (sizeof (struct AdvancedStack)); + + if(!S) + return NULL; + + S->elementStack = createStack(capacity); + S->minStack = createStack(capacity); + return S; +} + +void deleteStackA(struct AdvancedStack *S){ + if(S) { + deleteStackA(S->elementStack); + deleteStackA(S->minStack); + free(S); + } +} + +int main(){ + int i = 0, capacity = 5; + // create a stack of capacity 5 + struct AdvancedStack *stk = createAdvancedStack(capacity); + + for(i = 0; i <= 2 * capacity; i++){ + pushA(stk, (7*i)%4); + } + + printf("Top element is %d\n", peekA(stk)); + printf("Stack size is %d\n", sizeA(stk)); + + for (i = 0; i <= capacity; i++){ + printf("Popped element is %d\n", popA(stk)); + printf("Minimum element is %d\n", getMinimum(stk)); + } + + if (isEmptyA(stk)) + printf("Stack is empty"); + else + printf("Stack is not empty"); + + deleteStackA(stk); + return 0; +} diff --git a/src/Chapter_04_Stacks/infixToPostfix.c b/src/Chapter_04_Stacks/infixToPostfix.c new file mode 100644 index 0000000..9615934 --- /dev/null +++ b/src/Chapter_04_Stacks/infixToPostfix.c @@ -0,0 +1,167 @@ +/*Copyright (c) 2016 CareerMonk Publications and others. +#E-Mail : info@careermonk.com +#Creation Date : 2008-01-10 06:15:46 +#Created by : Narasimha Karumanchi +#Book Title : Data Structures And Algorithms Made Easy +#Warranty : This software is provided "as is" without any +# warranty; without even the implied warranty of +# merchantability or fitness for a particular purpose.*/ + +#include +#include +#include + +struct Stack { + int top; + int capacity; + int *array; +}; + +struct Stack *createStack(int capacity) { + struct Stack *S = malloc(sizeof(struct Stack)); + if(!S) + return NULL; + S->capacity = capacity; + S->top = -1; + S->array= malloc(S->capacity * sizeof(int)); + if(!S->array) + return NULL; + return S; +} + +int isEmpty(struct Stack *S) { + return (S->top == -1); // if the condition is true then 1 is returned else 0 is returned +} + +int size(struct Stack *S) { + return (S->top + 1); +} + +int isFull(struct Stack *S){ + //if the condition is true then 1 is returned else 0 is returned + return (S->top == S->capacity - 1); +} + +void doubleStack(struct Stack *S){ + S->capacity *= 2; + S->array = realloc(S->array, S->capacity * sizeof(int)); +} + + +void push(struct Stack *S, int data){ + if(isFull(S)) + doubleStack(S); + S->array[++S->top] = data; +} + +int pop(struct Stack *S){ + /* S->top == - 1 indicates empty stack*/ + if(isEmpty(S)){ + printf("Stack is Empty\n"); + return INT_MIN; + } + else /* Removing element from ‘top’ of the array and reducing ‘top’ by 1*/ + return (S->array[S->top--]); +} + +int peek(struct Stack *S){ + /* S->top == - 1 indicates empty stack*/ + if(isEmpty(S)){ + printf("Stack is Empty"); + return INT_MIN;; + } + else + return (S->array[S->top]); +} + +void deleteStack(struct Stack *S){ + if(S) { + if(S->array) + free(S->array); + free(S); + } +} +struct AdvancedStack { + struct Stack *elementStack; + struct Stack *minStack; +}; + + +int isEmptyA(struct AdvancedStack *S) { + return (S->elementStack->top == -1); // if the condition is true then 1 is returned else 0 is returned +} + +int sizeA(struct AdvancedStack *S) { + return (S->elementStack->top + 1); +} + +int isFullA(struct AdvancedStack *S){ + //if the condition is true then 1 is returned else 0 is returned + return (S->elementStack->top == S->elementStack->capacity - 1); +} + +void pushA(struct AdvancedStack *S, int data){ + push(S->elementStack, data); + + if(isEmpty(S->minStack) || peek(S->minStack) >= data) + push (S->minStack, data); + else push (S->minStack, peek(S->minStack)); +} + +int popA(struct AdvancedStack *S ){ + int temp; + + if(isEmpty(S->elementStack)) + return INT_MIN; + + temp = peek(S->elementStack); + + if(peek(S->minStack) == pop(S->elementStack)) + pop (S->minStack); + return temp; +} + +int peekA(struct AdvancedStack *S ){ + return peek(S->elementStack); +} + +int getMinimum(struct AdvancedStack *S){ + return peek(S->minStack); +} + +struct AdvancedStack * createAdvancedStack(int capacity){ + struct AdvancedStack *S = malloc (sizeof (struct AdvancedStack)); + + if(!S) + return NULL; + + S->elementStack = createStack(capacity); + S->minStack = createStack(capacity); + return S; +} + +int main(){ + int i = 0, capacity = 5; + // create a stack of capacity 5 + struct AdvancedStack *stk = createAdvancedStack(capacity); + + for(i = 0; i <= 2 * capacity; i++){ + pushA(stk, (7*i)%4); + } + + printf("Top element is %d\n", peekA(stk)); + printf("Stack size is %d\n", sizeA(stk)); + + for (i = 0; i <= capacity; i++){ + printf("Popped element is %d\n", popA(stk)); + printf("Minimum element is %d\n", getMinimum(stk)); + } + + if (isEmptyA(stk)) + printf("Stack is empty"); + else + printf("Stack is not empty"); + + deleteStack(stk); + return 0; +} diff --git a/src/Chapter_04_Stacks/infixToPostfix.cpp b/src/Chapter_04_Stacks/infixToPostfix.cpp new file mode 100644 index 0000000..8ca8c8e --- /dev/null +++ b/src/Chapter_04_Stacks/infixToPostfix.cpp @@ -0,0 +1,69 @@ +/* + Author : Shivam Chauhan + Date : Feb 27 , 2019 + Infix to Postfix Implementation +*/ +#include +using namespace std ; +int getPriority(char ch ) +{ + switch(ch) + { + case '+' : + case '-' : return 1; + break; + case '*' : + case '/' : return 2; + break; + + case '^' : return 3; + break; + + default : return 0 ; + break ; + + } +} +string infix_to_postfix(string str ) +{ + stacks; + string result = ""; + for ( auto c : str) + { + if( ( c >= 'a' && c <= 'z' ) || (c >= 'A' && c <= 'Z') ) + { + result += c ; + } + else if ( c == ')') + { + while ( !s.empty() && s.top() != '(' ) + { + result += s.top(); + s.pop(); + } + if( !s.empty() && s.top() == '(' ) s.pop() ; + } + else + { + while( !s.empty() && getPriority(s.top()) >= getPriority(c) && c != '(') + { + result += s.top(); + s.pop(); + } + s.push(c); + } + } + while(!s.empty()) + { + result += s.top(); + s.pop(); + } + return result ; +} + +int main() +{ + string str = "(A+B)/(C+D)"; + cout << infix_to_postfix(str) << endl ; + return 0 ; +} \ No newline at end of file diff --git a/src/Chapter_04_Stacks/isPalindrome.c b/src/Chapter_04_Stacks/isPalindrome.c new file mode 100644 index 0000000..21d455d --- /dev/null +++ b/src/Chapter_04_Stacks/isPalindrome.c @@ -0,0 +1,40 @@ +/*Copyright (c) 2016 CareerMonk Publications and others. +#E-Mail : info@careermonk.com +#Creation Date : 2008-01-10 06:15:46 +#Created by : Narasimha Karumanchi +#Book Title : Data Structures And Algorithms Made Easy +#Warranty : This software is provided "as is" without any +# warranty; without even the implied warranty of +# merchantability or fitness for a particular purpose.*/ +#include +#include + +int isPalindrome(char str[]){ + //the first index + int i = 0; + //the last index + int j = strlen(str)-1; + + while(i < j && str[i] == str[j]){ + //increment start index and decrement last index + i++; + j--; + } + + if(i < j){ + //did not reach the center + printf("Not a palindrome\n"); + return 0; + } + else{ + //reached the center + printf("Palindrome\n"); + return 1; + } +} + +int main(void){ + isPalindrome("ababaXababa"); + isPalindrome("ababababXbababbbbabba"); + return 0; +} diff --git a/src/Chapter_04_Stacks/isPalindrome2.c b/src/Chapter_04_Stacks/isPalindrome2.c new file mode 100644 index 0000000..e8cea2c --- /dev/null +++ b/src/Chapter_04_Stacks/isPalindrome2.c @@ -0,0 +1,110 @@ +/*Copyright (c) 2016 CareerMonk Publications and others. +#E-Mail : info@careermonk.com +#Creation Date : 2008-01-10 06:15:46 +#Created by : Narasimha Karumanchi +#Book Title : Data Structures And Algorithms Made Easy +#Warranty : This software is provided "as is" without any +# warranty; without even the implied warranty of +# merchantability or fitness for a particular purpose.*/ + +#include +#include +#include +#include + +struct Stack { + int top; + int capacity; + char *array; +}; + +struct Stack *createStack(int capacity) { + struct Stack *S = malloc(sizeof(struct Stack)); + if(!S) + return NULL; + S->capacity = capacity; + S->top = -1; + S->array= malloc(S->capacity * sizeof(int)); + if(!S->array) + return NULL; + return S; +} + +int isEmpty(struct Stack *S) { + return (S->top == -1); // if the condition is true then 1 is returned else 0 is returned +} + +int size(struct Stack *S) { + return (S->top + 1); +} + +int isFull(struct Stack *S){ + //if the condition is true then 1 is returned else 0 is returned + return (S->top == S->capacity - 1); +} + +void doubleStack(struct Stack *S){ + S->capacity *= 2; + S->array = realloc(S->array, S->capacity * sizeof(int)); +} + + +void push(struct Stack *S, char data){ + if(isFull(S)) + doubleStack(S); + S->array[++S->top] = data; +} + +char pop(struct Stack *S){ + /* S->top == - 1 indicates empty stack*/ + if(isEmpty(S)){ + printf("Stack is Empty\n"); + return '\0'; + } + else /* Removing element from ‘top’ of the array and reducing ‘top’ by 1*/ + return (S->array[S->top--]); +} + +int peek(struct Stack *S){ + /* S->top == - 1 indicates empty stack*/ + if(isEmpty(S)){ + printf("Stack is Empty"); + return INT_MIN;; + } + else + return (S->array[S->top]); +} + +void deleteStack(struct Stack *S){ + if(S) { + if(S->array) + free(S->array); + free(S); + } +} + +int isPalindrome(char A[]){ + int i=0; + struct Stack *stk = createStack(strlen(A)); + while(A[i] && A[i] != 'X') { + push(stk, A[i]); + i++; + } + i++; + while(A[i]) { + if(isEmpty(stk) || A[i] != pop(stk)) { + printf("Not a palindrome\n"); + return 0; + } + i++; + } + printf("Palindrome\n"); + return 1; +} + +int main(void){ + isPalindrome("ababaXababa"); + isPalindrome("ababababXbababbbbabba"); + return 0; +} + diff --git a/src/Chapter_04_Stacks/largestHistrogram_n^2.cpp b/src/Chapter_04_Stacks/largestHistrogram_n^2.cpp new file mode 100644 index 0000000..e398163 --- /dev/null +++ b/src/Chapter_04_Stacks/largestHistrogram_n^2.cpp @@ -0,0 +1,27 @@ +#include +#include +using namespace std; + +int largestHistrogram(vector &A) { + int maxArea = 0; + for (int i = 0; i < A.size(); i++) { + for (int j = i, minimum_height = A[i]; j < A.size(); j++) { + minimum_height = min(minimum_height, A[j]); + maxArea = max(maxArea, (j-i+1) * minimum_height); + } + } + return maxArea; +} + +int main() { + vector A; + A.push_back(6); + A.push_back(2); + A.push_back(5); + A.push_back(4); + A.push_back(5); + A.push_back(1); + A.push_back(6); + printf("largestRectangleArea: %d", largestHistrogram(A)); + return 0; +} diff --git a/src/Chapter_04_Stacks/largestHistrogram_n^3.cpp b/src/Chapter_04_Stacks/largestHistrogram_n^3.cpp new file mode 100644 index 0000000..46c1e75 --- /dev/null +++ b/src/Chapter_04_Stacks/largestHistrogram_n^3.cpp @@ -0,0 +1,35 @@ +#include +#include +using namespace std; +int findMin(vector &A, int i, int j){ + int min = A[i]; + while(i <= j){ + if (min > A[i]) + min = A[i]; + i++; + } + return min; +} +int largestHistrogram(vector &A) { + int maxArea = 0; + for (int i = 0; i < A.size(); i++) { + for (int j = i, minimum_height = A[i]; j < A.size(); j++) { + minimum_height = findMin(A, i, j); + maxArea = max(maxArea, (j-i+1) * minimum_height); + } + } + return maxArea; +} + +int main() { + vector A; + A.push_back(6); + A.push_back(2); + A.push_back(5); + A.push_back(4); + A.push_back(5); + A.push_back(1); + A.push_back(6); + printf("largestRectangleArea: %d", largestHistrogram(A)); + return 0; +} diff --git a/src/Chapter_04_Stacks/largestHistrogram_nlogn.cpp b/src/Chapter_04_Stacks/largestHistrogram_nlogn.cpp new file mode 100644 index 0000000..a3216ee --- /dev/null +++ b/src/Chapter_04_Stacks/largestHistrogram_nlogn.cpp @@ -0,0 +1,47 @@ +#include +using namespace std; + +// Function returning the max area under the histogram +int largestArea(int hist[],int n) +{ + stack index ; + int currentArea , maxArea = -1 ; + int left , top ; + for ( int i = 0 ; i <= n ; i++) + { + while( !index.empty() && (i == n || hist[index.top()] > hist[i]) ) + { + // Calculating the nearest smallest pillar + if ( index.size() > 1 ) + { + top = index.top(); + index.pop(); + left = index.top(); + } + // Case of only one element + else + { + left = -1 ; + top = index.top() ; + index.pop(); + } + currentArea = hist[top] * ( i - left - 1) ; + // Updating the maxArea if condition evaluates out to be true + maxArea = maxArea < currentArea ? currentArea : maxArea ; + } + if( i < n ) + { + index.push(i); + } + } + return maxArea ; +} + +int main() +{ + // Array containing the heights of the various histogram + int arr[] = { 3, 2, 5, 6, 1, 4, 4 }; + // sizeof(arr)/sizeof(arr[0]) gives the size of the array i.e. 7 in this case + cout << largestArea(arr,sizeof(arr)/sizeof(arr[0])) << endl ; + return 0 ; +} diff --git a/src/Chapter_04_Stacks/postfixEvaluation.c b/src/Chapter_04_Stacks/postfixEvaluation.c new file mode 100644 index 0000000..552d066 --- /dev/null +++ b/src/Chapter_04_Stacks/postfixEvaluation.c @@ -0,0 +1,111 @@ +/*Copyright (c) 2016 CareerMonk Publications and others. +#E-Mail : info@careermonk.com +#Creation Date : 2008-01-10 06:15:46 +#Created by : Narasimha Karumanchi +#Book Title : Data Structures And Algorithms Made Easy +#Warranty : This software is provided "as is" without any +# warranty; without even the implied warranty of +# merchantability or fitness for a particular purpose.*/ + +#include +#include + +struct Stack { + int top; + int capacity; + int *array; +}; + +struct Stack *createStack(int capacity) { + struct Stack *S = malloc(sizeof(struct Stack)); + if(!S) + return NULL; + S->capacity = capacity; + S->top = -1; + S->array= malloc(S->capacity * sizeof(int)); + if(!S->array) + return NULL; + return S; +} + +int isEmpty(struct Stack *S) { + return (S->top == -1); // if the condition is true then 1 is returned else 0 is returned +} + +int isFull(struct Stack *S){ + //if the condition is true then 1 is returned else 0 is returned + return (S->top == S->capacity - 1); +} + +void doubleStack(struct Stack *S){ + S->capacity *= 2; + S->array = realloc(S->array, S->capacity * sizeof(int)); +} + +void push(struct Stack *S, char data){ + if(isFull(S)) + doubleStack(S); + S->array[++S->top] = data; +} + +int peek(struct Stack *S){ + /* S->top == - 1 indicates empty stack*/ + if(isEmpty(S)){ + printf("Stack is Empty"); + return '\0'; + } + else + return (S->array[S->top]); +} + +char pop(struct Stack *S){ + /* S->top == - 1 indicates empty stack*/ + if(isEmpty(S)){ + printf("Stack is Empty\n"); + return '\0'; + } + else /* Removing element from ‘top’ of the array and reducing ‘top’ by 1*/ + return (S->array[S->top--]); +} + +void deleteStack(struct Stack *S){ + if(S) { + if(S->array) + free(S->array); + free(S); + } +} + +int postfixEvaluation(char expression[]){ + // Create a Stack of capacity equal to expression size + struct Stack* stk = createStack(strlen(expression)); + int i; + + // Scan all characters one by one + for (i = 0; expression[i]; ++i){ + // If the scanned character is an operand (number here), + // push it to the Stack. + if (isdigit(expression[i])) + push(stk, expression[i] - '0'); + + // If the scanned character is an operator, pop top two + // elements from stack apply the operator + else{ + int topElement = pop(stk); + int secondTopElement = pop(stk); + switch (expression[i]){ + case '+': push(stk, secondTopElement + topElement); break; + case '-': push(stk, secondTopElement - topElement); break; + case '*': push(stk, secondTopElement * topElement); break; + case '/': push(stk, secondTopElement/topElement); break; + } + } + } + return pop(stk); +} + +// test code +int main() { + printf ("postfix evaluation: %d", postfixEvaluation("123*+5-")); + return 0; +} diff --git a/src/Chapter_04_Stacks/postfixEvaluation.cpp b/src/Chapter_04_Stacks/postfixEvaluation.cpp new file mode 100644 index 0000000..516a088 --- /dev/null +++ b/src/Chapter_04_Stacks/postfixEvaluation.cpp @@ -0,0 +1,48 @@ +/* + Author : Shivam Chauhan + Date : Feb 27 , 2019 + Postfix Expression Evalutaion +*/ +#include +using namespace std ; +int postfix_evaluator( string str) +{ + stacks; + for ( auto c : str ) + { + int n1 , n2 ; + if ( c >= '0' && c <= '9' ) + { + s.push(c-'0'); + } + else + { + if ( s.size() >= 2 ) + { + n1 = s.top() ; s.pop() ; + n2 = s.top() ; s.pop() ; + switch(c) + { + case '+' : s.push(n2+n1); + break; + case '-' : s.push(n2-n1); + break; + case '/' : s.push(n2/n1); + break; + case '*' : s.push(n2*n1); + break; + } + } + } + } + int tmp = s.top(); + s.pop(); + return tmp ; + +} +int main() +{ + string str = "95+4-"; + cout << postfix_evaluator(str) << endl ; + return 0 ; +} \ No newline at end of file diff --git a/src/Chapter_04_Stacks/reverseStack.c b/src/Chapter_04_Stacks/reverseStack.c new file mode 100644 index 0000000..67e7bfe --- /dev/null +++ b/src/Chapter_04_Stacks/reverseStack.c @@ -0,0 +1,132 @@ +/*Copyright (c) 2016 CareerMonk Publications and others. +#E-Mail : info@careermonk.com +#Creation Date : 2008-01-10 06:15:46 +#Created by : Narasimha Karumanchi +#Book Title : Data Structures And Algorithms Made Easy +#Warranty : This software is provided "as is" without any +# warranty; without even the implied warranty of +# merchantability or fitness for a particular purpose.*/ + +#include +#include +#include +#include + +struct Stack { + int top; + int capacity; + char *array; +}; + +struct Stack *createStack(int capacity) { + struct Stack *S = malloc(sizeof(struct Stack)); + if(!S) + return NULL; + S->capacity = capacity; + S->top = -1; + S->array= malloc(S->capacity * sizeof(int)); + if(!S->array) + return NULL; + return S; +} + +int isEmpty(struct Stack *S) { + return (S->top == -1); // if the condition is true then 1 is returned else 0 is returned +} + +int size(struct Stack *S) { + return (S->top + 1); +} + +int isFull(struct Stack *S){ + //if the condition is true then 1 is returned else 0 is returned + return (S->top == S->capacity - 1); +} + +void doubleStack(struct Stack *S){ + S->capacity *= 2; + S->array = realloc(S->array, S->capacity * sizeof(int)); +} + + +void push(struct Stack *S, char data){ + if(isFull(S)) + doubleStack(S); + S->array[++S->top] = data; +} + +char pop(struct Stack *S){ + /* S->top == - 1 indicates empty stack*/ + if(isEmpty(S)){ + printf("Stack is Empty\n"); + return '\0'; + } + else /* Removing element from ‘top’ of the array and reducing ‘top’ by 1*/ + return (S->array[S->top--]); +} + +int peek(struct Stack *S){ + /* S->top == - 1 indicates empty stack*/ + if(isEmpty(S)){ + printf("Stack is Empty"); + return INT_MIN;; + } + else + return (S->array[S->top]); +} + +void deleteStack(struct Stack *S){ + if(S) { + if(S->array) + free(S->array); + free(S); + } +} + +void reverseStack(struct Stack *S){ + char data; + + if(isEmpty(S)) + return; + + data = pop(S); + reverseStack(S); + insertAtBottom(S, data); +} + +void insertAtBottom(struct Stack *S, char data){ + char temp; + + if(isEmpty(S)) { + push(S, data); + return; + } + + temp = pop(S); + insertAtBottom(S, data); + push(S, temp); +} + + +int main(void){ + int i = 0, capacity = 2; + // create a stack of capacity 2 + struct Stack *stk = createStack(capacity); + + for(i = 0; i <= capacity; i++){ + push(stk, i); + } + reverseStack(stk); + printf("Top element is %d\n", peek(stk)); + printf("Stack size is %d\n", size(stk)); + + for (i = 0; i <= capacity; i++){ + printf("Popped element is %d\n", pop(stk)); + } + + deleteStack(stk); + return 0; + + return 0; +} + diff --git a/src/Chapter_06_Trees/FindMaxUsingLevelOrder.c b/src/Chapter_06_Trees/FindMaxUsingLevelOrder.c new file mode 100644 index 0000000..92b1857 --- /dev/null +++ b/src/Chapter_06_Trees/FindMaxUsingLevelOrder.c @@ -0,0 +1,192 @@ +// Copyright (c) 2008 CareerMonk Publications and others. +// #E-Mail : info@careermonk.com +// Creation Date : 2008-01-10 06:15:46 +// Created by : Narasimha Karumanchi +// Book Title : Data Structures And Algorithms Made Easy +// Warranty : This software is provided "as is" without any +// warranty; without even the implied warranty of +// merchantability or fitness for a particular purpose. + +#include +#include +#include + +struct BinaryTreeNode { + int data; + struct BinaryTreeNode *left; + struct BinaryTreeNode *right; +}; + +struct ListNode { + struct BinaryTreeNode *data; + struct ListNode *next; +}; + + +struct Queue { + struct ListNode *front; + struct ListNode *rear; +}; + +/* Create an empty queue */ +struct Queue *createQueue() { + struct Queue *Q; + Q = malloc(sizeof(struct Queue)); + if(!Q) + return NULL; + + Q->front = Q->rear = NULL; + return Q; +} + +/* Returns queue size */ +int size(struct Queue *Q) { + struct ListNode *temp = Q->front; + int count = 0; + + if(Q->front == NULL && Q->rear == NULL) + return 0; + + while(temp != Q->rear){ + count++; + temp = temp->next; + } + if(temp == Q->rear) + count++; + + return count; +} + +/* Returns Frnt Element of the Queue */ +struct BinaryTreeNode* frontElement(struct Queue *Q) { + return Q->front->data; +} + +/* Returns the Rear Element of the Queue */ +struct BinaryTreeNode* rearElement(struct Queue *Q) { + return Q->rear->data; +} + +/* +Check's if Queue is empty or not +*/ +int isEmpty(struct Queue *Q) { + if (Q->front == NULL && Q->rear == NULL) + return 1; + else + return 0; +} +/* +Adding elements in Queue +*/ +void enQueue(struct Queue *Q, struct BinaryTreeNode *node) { + struct ListNode *temp; + temp = (struct ListNode *)malloc(sizeof(struct ListNode)); + temp->data = node; + temp->next = NULL; + + if (Q->rear == NULL) { + Q->front = Q->rear = temp; + } else { + Q->rear->next = temp; + Q->rear = temp; + } +} + +/* +Removes an element from front of the queue +*/ +struct BinaryTreeNode* deQueue(struct Queue *Q) { + struct ListNode *temp; + if (Q->front == NULL) { + printf("\nQueue is Empty \n"); + return NULL; + } else { + temp = Q->front; + Q->front = Q->front->next; + if(Q->front == NULL){ + Q->rear = NULL; + } + return temp->data; + } +} + +/* + Print's Queue +*/ +void printQueue(struct Queue *Q) { + struct ListNode *temp = Q->front; + + if ((Q->front == NULL) && (Q->rear == NULL)) { + printf("Queue is Empty\n"); + return; + } + + while (temp != NULL) { + printf("%d", temp->data->data); + temp = temp->next; + if(temp != NULL) + printf("-->"); + } +} + +void deleteQueue(struct Queue *Q) { + struct ListNode *temp; + while(Q->front) { + temp = Q->front; + printf("Element being deleted: %d\n", temp->data->data); + Q->front = Q->front->next; + free(temp); + } + free(Q); +} + + + +struct BinaryTreeNode* createNewNode(int data){ // creating new node + struct BinaryTreeNode* newNode = (struct BinaryTreeNode*)malloc(sizeof(struct BinaryTreeNode)); + newNode->data = data; + newNode->left = NULL; + newNode->right = NULL; + + return(newNode); +} + +int findMaxUsingLevelOrder(struct BinaryTreeNode *root){ + struct BinaryTreeNode *temp; + int max = INT_MIN; + struct Queue *Q = createQueue(); + + enQueue(Q,root); + + while(!isEmpty(Q)) { + temp = deQueue(Q); + // largest of the three values + if(max < temp->data) + max = temp->data; + if(temp->left) + enQueue (Q, temp->left); + if(temp->right) + enQueue (Q, temp->right); + } + deleteQueue(Q); + return max; +} + + +int main() { + //**same BinaryTreeNode is builted as shown in example** + struct BinaryTreeNode *root = createNewNode(2); + root->left= createNewNode(7); + root->right= createNewNode(5); + root->right->right=createNewNode(19); + root->right->right->left=createNewNode(4); + root->left->left=createNewNode(2); + root->left->right=createNewNode(6); + root->left->right->left=createNewNode(5); + root->left->right->right=createNewNode(11); + + printf("Maximum in tree is %d", findMaxUsingLevelOrder(root)); + ; + return 0; +} diff --git a/src/Chapter_06_Trees/LevelOrder.c b/src/Chapter_06_Trees/LevelOrder.c new file mode 100644 index 0000000..912fb63 --- /dev/null +++ b/src/Chapter_06_Trees/LevelOrder.c @@ -0,0 +1,191 @@ +// Copyright (c) 2008 CareerMonk Publications and others. +// #E-Mail : info@careermonk.com +// Creation Date : 2008-01-10 06:15:46 +// Created by : Narasimha Karumanchi +// Book Title : Data Structures And Algorithms Made Easy +// Warranty : This software is provided "as is" without any +// warranty; without even the implied warranty of +// merchantability or fitness for a particular purpose. + +#include +#include + + +struct BinaryTreeNode { + int data; + struct BinaryTreeNode *left; + struct BinaryTreeNode *right; +}; + +struct ListNode { + struct BinaryTreeNode *data; + struct ListNode *next; +}; + + +struct Queue { + struct ListNode *front; + struct ListNode *rear; +}; + +/* Create an empty queue */ +struct Queue *createQueue() { + struct Queue *Q; + Q = malloc(sizeof(struct Queue)); + if(!Q) + return NULL; + + Q->front = Q->rear = NULL; + return Q; +} + +/* Returns queue size */ +int size(struct Queue *Q) { + struct ListNode *temp = Q->front; + int count = 0; + + if(Q->front == NULL && Q->rear == NULL) + return 0; + + while(temp != Q->rear){ + count++; + temp = temp->next; + } + if(temp == Q->rear) + count++; + + return count; +} + +/* Returns Frnt Element of the Queue */ +struct BinaryTreeNode* frontElement(struct Queue *Q) { + return Q->front->data; +} + +/* Returns the Rear Element of the Queue */ +struct BinaryTreeNode* rearElement(struct Queue *Q) { + return Q->rear->data; +} + +/* +Check's if Queue is empty or not +*/ +int isEmpty(struct Queue *Q) { + if (Q->front == NULL && Q->rear == NULL) + return 1; + else + return 0; +} +/* +Adding elements in Queue +*/ +void enQueue(struct Queue *Q, struct BinaryTreeNode *node) { + struct ListNode *temp; + temp = (struct ListNode *)malloc(sizeof(struct ListNode)); + temp->data = node; + temp->next = NULL; + + if (Q->rear == NULL) { + Q->front = Q->rear = temp; + } else { + Q->rear->next = temp; + Q->rear = temp; + } +} + +/* +Removes an element from front of the queue +*/ +struct BinaryTreeNode* deQueue(struct Queue *Q) { + struct ListNode *temp; + if (Q->front == NULL) { + printf("\nQueue is Empty \n"); + return NULL; + } else { + temp = Q->front; + Q->front = Q->front->next; + if(Q->front == NULL){ + Q->rear = NULL; + } + return temp->data; + } +} + +/* + Print's Queue +*/ +void printQueue(struct Queue *Q) { + struct ListNode *temp = Q->front; + + if ((Q->front == NULL) && (Q->rear == NULL)) { + printf("Queue is Empty\n"); + return; + } + + while (temp != NULL) { + printf("%d", temp->data->data); + temp = temp->next; + if(temp != NULL) + printf("-->"); + } +} + +void deleteQueue(struct Queue *Q) { + struct ListNode *temp; + while(Q->front) { + temp = Q->front; + printf("Element being deleted: %d\n", temp->data->data); + Q->front = Q->front->next; + free(temp); + } + free(Q); +} + + + +struct BinaryTreeNode* createNewNode(int data){ // creating new node + struct BinaryTreeNode* newNode = (struct BinaryTreeNode*)malloc(sizeof(struct BinaryTreeNode)); + newNode->data = data; + newNode->left = NULL; + newNode->right = NULL; + + return(newNode); +} + +void levelOrder(struct BinaryTreeNode *root){ + struct BinaryTreeNode *temp; + struct Queue *Q = createQueue(); + + if(!root) + return; + + enQueue(Q, root); + while(!isEmpty(Q)){ + temp = deQueue(Q); + //Process current node + printf("\n%d", temp->data); + if(temp->left) + enQueue(Q, temp->left); + if(temp->right) + enQueue(Q, temp->right); + } + deleteQueue(Q); +} + + +int main() { + //**same BinaryTreeNode is builted as shown in example** + struct BinaryTreeNode *root = createNewNode(2); + root->left= createNewNode(7); + root->right= createNewNode(5); + root->right->right=createNewNode(9); + root->right->right->left=createNewNode(4); + root->left->left=createNewNode(2); + root->left->right=createNewNode(6); + root->left->right->left=createNewNode(5); + root->left->right->right=createNewNode(11); + + printf("Level Order traversal of binary BinaryTreeNode is :"); + levelOrder(root); + return 0; +} diff --git a/src/Chapter_09_Graph_Algorithms/AdjacencyMatrix.c b/src/Chapter_09_Graph_Algorithms/AdjacencyMatrix.c new file mode 100644 index 0000000..00757d4 --- /dev/null +++ b/src/Chapter_09_Graph_Algorithms/AdjacencyMatrix.c @@ -0,0 +1,157 @@ +// Copyright (c) 2008 CareerMonk Publications and others. +// E-Mail : info@careermonk.com +// Creation Date : 2008-01-10 06:15:46 +// Created by : Narasimha Karumanchi +// Book Title : Data Structures And Algorithms Made Easy +// Warranty : This software is provided "as is" without any +// warranty; without even the implied warranty of +// merchantability or fitness for a particular purpose. + +#include +#include +#include +#include +#define MAX_VERTICES 50 // max number of vertices for our graph +#define MAX_DEGREE 50 // max degree for a vertex + +struct graph{ + int V; // number of vertices + int E; // number of edges + int **adjMatrix; // adjacency matrix +}; + +struct edge{ + int source; + int destination; +}; + +void rand_init(void){ + // Initializes the random generator rand() + time_t t; + srand((unsigned) time(&t)); +} + +struct graph* createGraph(const int numVertices){ + assert(numVertices >= 0); + // Create an empty graph with numVertices + int i, j; + struct graph* G = (struct graph *) malloc(sizeof( struct graph)); + G->V = numVertices; + G->E = 0; + // allocate memory for each row + G->adjMatrix = malloc(numVertices * sizeof(int *)); + assert(G != NULL); + // allocate memory for each column and initialise with 0 + for (i = 0; i < numVertices; i++) { + G->adjMatrix[i] = calloc(numVertices, sizeof(int)); + assert(G->adjMatrix[i] != NULL); + } + return G; +} + +void displayGraph(const struct graph* G){ + // Display the graph (adjMatrix) + int i,j, v; + v = G->V; + printf("%d vertices; %d edges.\n", G->V, G->E); + for(i=0; i< v; i++){ + for(j=0; j < v; j++) printf("%3d ",(G->adjMatrix)[i][j]); + printf("\n"); + } +} + +void displayEdges(const struct graph* G){ + int v,i,j; + v = G->V; + for(i=0; i < v; i++){ + for(j=i+1; j < v; j++){ + if(G->adjMatrix[i][j]==1) printf("%d-%d ",i,j); + } + } +} + +void insertEdge(struct graph* G, const struct edge E){ + int v, x, y; + v = G->V; + x = E.source; + y = E.destination; + if(x >= v || y >= v) { + printf("Error when adding edge."); + exit(EXIT_FAILURE); + } + if (G->adjMatrix[x][y] == 0){ // For undirected graphs set both the bits + G->adjMatrix[x][y] = 1; + G->adjMatrix[y][x] = 1; + (G->E)++; + } +} + +void removeEdge(struct graph* G, const struct edge E){ + int v, x, y; + v = G->V; + x = E.source; + y = E.destination; + if(x >= v || y >= v) { + printf("Error when deleting edge."); + exit(EXIT_FAILURE); + } + if (G->adjMatrix[x][y] == 1){ + G->adjMatrix[x][y] = 0; + G->adjMatrix[y][x] = 0; + (G->E)--; + } +} + +void destroyGraph(struct graph* G){ // to free memory + if (G){ + if (G->adjMatrix){ + int i; + for (i = 0; i < G->V; i++) + free(G->adjMatrix[i]); + free(G->adjMatrix); + } + free(G); + } +} + +struct edge newEdge(int x, int y){ + // return an edge with ends x and y + struct edge e; + e.source = x; + e.destination = y; + return e; +} + +struct graph* randomGraph(const int N, const float p){ + // A random graph with N vertices and probability p for each edge + int i, j; + struct edge E; + struct graph* G = createGraph(N); + rand_init(); + for (i=0; i < N; i++) for(j=i+1; j < N; j++) { + if (rand() < p * RAND_MAX) { // rand() returns an integer between 0 and RAND_MAX + E = newEdge(i,j); + insertEdge(G, E); + } + } + return G; +} + + + +void main(void){ + // Test code + struct edge E; + struct graph* G = randomGraph(10, 0.15); + displayGraph(G); + E = newEdge(5,6); + insertEdge(G, E); + displayGraph(G); + printf("\n"); + displayEdges(G); + removeEdge(G, E); + displayGraph(G); + printf("\n"); + displayEdges(G); + destroyGraph(G); +} diff --git a/src/Chapter_09_Graph_Algorithms/AdjacentList.c b/src/Chapter_09_Graph_Algorithms/AdjacentList.c new file mode 100644 index 0000000..be053be --- /dev/null +++ b/src/Chapter_09_Graph_Algorithms/AdjacentList.c @@ -0,0 +1,181 @@ +// Copyright (c) 2008 CareerMonk Publications and others. +// E-Mail : info@careermonk.com +// Creation Date : 2008-01-10 06:15:46 +// Created by : Narasimha Karumanchi +// Book Title : Data Structures And Algorithms Made Easy +// Warranty : This software is provided "as is" without any +// warranty; without even the implied warranty of +// merchantability or fitness for a particular purpose. + +#include +#include +#include +#include +#include + +struct ListNode { + int vertex; + struct ListNode *next; +}; + +struct edge{ + int source; + int destination; +}; + +struct graph{ + int V; // number of vertices + int E; // number of edges + struct ListNode *adjList[]; // adjacency matrix +}; + +void rand_init(void){ + // Initializes the random generator rand() + time_t t; + srand((unsigned) time(&t)); +} + + +int insertEdge(struct graph* G, const struct edge E) { + int n, from, to; + n = G->V; + from = E.source; + to = E.destination; + + if (0 > from || from > n || 0 > to || to > n) return -1; + + struct ListNode *prev = NULL, *ptr = G->adjList[from]; + while (ptr != NULL) { + if (ptr->vertex == to) return 0; + else { + prev = ptr; + ptr = ptr->next; + } + } + if (ptr==NULL) { + struct ListNode *newNode = (struct ListNode *) malloc(sizeof(struct ListNode)); + newNode->vertex = to; + newNode->next = NULL; + + if (prev == NULL) { + G->adjList[from] = newNode; + } else { + prev->next = newNode; + } + } + return 1; +} + +int removeEdge(struct graph* G, const struct edge E) { + int n, from, to; + n = G->V; + from = E.source; + to = E.destination; + if (0 > from || from > n || 0 > to || to > n) return -1; + struct ListNode *prev = NULL, *ptr = G->adjList[from]; + while (ptr != NULL) { + if (ptr->vertex == to) { + if (prev == NULL) { + G->adjList[from] = ptr->next; + free(ptr); + } else { + prev->next = ptr->next; + free(ptr); + } + return 1; + } else { + prev = ptr; + ptr = ptr->next; + } + } + return 0; +} + +struct graph* createGraph(const int numVertices) { + assert(numVertices >= 0); + // Create an empty graph with numVertices + int i, j; + struct graph* G = (struct graph *) malloc(sizeof( struct graph)); + assert(G != NULL); + G->V = numVertices; + G->E = 0; + + // allocate memory for each column and initialise with 0 + struct ListNode *newNode, *last; + for (int i = 0; i < G->V; i++) { + G->adjList[i] = (struct ListNode *) malloc(sizeof(struct ListNode)); + assert(G->adjList[i] != NULL); + G->adjList[i]->vertex = i; + G->adjList[i]->next = NULL; + } + return G; +} + +struct edge newEdge(int x, int y){ + // return an edge with ends x and y + struct edge e; + e.source = x; + e.destination = y; + return e; +} + +struct graph* randomGraph(const int N, const float p){ + // A random graph with N vertices and probability p for each edge + int i, j; + struct edge E; + struct graph* G = createGraph(N); + rand_init(); + for (i=0; i < N; i++) for(j=i+1; j < N; j++) { + if (rand() < p * RAND_MAX) { // rand() returns an integer between 0 and RAND_MAX + E = newEdge(i,j); + insertEdge(G, E); + } + } + return G; +} + +void displayGraph(struct graph* G) { + struct ListNode *ptr; + int i; + for (i = 0; i < G->V; i++) { + ptr = G->adjList[i]; + printf("\nnode %d neighbors:", i); + while (ptr != NULL) { + printf(" %d", ptr->vertex); + ptr = ptr->next; + } + } +} + +void destroyGraph(struct graph* G) { + int i; + struct ListNode *temp, *ptr; + for (i = 0; i < G->V; i++) { + ptr = G->adjList[i]; + while (ptr != NULL) { + temp = ptr; + ptr = ptr->next; + free(temp); + } + G->adjList[i] = NULL; + } + printf("\nGraph is deleted"); +} + +int main(int argc, char *args[]) { + // Test code + struct edge E; + struct graph* G = randomGraph(10, 0.15); + displayGraph(G); + + E = newEdge(5,6); + insertEdge(G, E); + displayGraph(G); + printf("\n"); + + removeEdge(G, E); + displayGraph(G); + printf("\n"); + destroyGraph(G); + return 0; +} diff --git a/src/Chapter_09_Graph_Algorithms/DFS.c b/src/Chapter_09_Graph_Algorithms/DFS.c new file mode 100644 index 0000000..0ede3fe --- /dev/null +++ b/src/Chapter_09_Graph_Algorithms/DFS.c @@ -0,0 +1,230 @@ +// Copyright (c) 2008 CareerMonk Publications and others. +// E-Mail : info@careermonk.com +// Creation Date : 2008-01-10 06:15:46 +// Created by : Narasimha Karumanchi +// Book Title : Data Structures And Algorithms Made Easy +// Warranty : This software is provided "as is" without any +// warranty; without even the implied warranty of +// merchantability or fitness for a particular purpose. + +#include +#include +#include +#include +#include + +struct ListNode { + int vertex; + struct ListNode *next; +}; + +struct edge{ + int source; + int destination; +}; + +struct graph{ + int V; // number of vertices + int E; // number of edges + struct ListNode *adjList[]; // adjacency matrix +}; + +void rand_init(void){ + // Initializes the random generator rand() + time_t t; + srand((unsigned) time(&t)); +} + + +int insertEdge(struct graph* G, const struct edge E) { + int n, from, to; + n = G->V; + from = E.source; + to = E.destination; + + if (0 > from || from > n || 0 > to || to > n) return -1; + + struct ListNode *prev = NULL, *ptr = G->adjList[from]; + while (ptr != NULL) { + if (ptr->vertex == to) return 0; + else { + prev = ptr; + ptr = ptr->next; + } + } + if (ptr==NULL) { + struct ListNode *newNode = (struct ListNode *) malloc(sizeof(struct ListNode)); + newNode->vertex = to; + newNode->next = NULL; + + if (prev == NULL) { + G->adjList[from] = newNode; + } else { + prev->next = newNode; + } + } + return 1; +} + +int removeEdge(struct graph* G, const struct edge E) { + int n, from, to; + n = G->V; + from = E.source; + to = E.destination; + if (0 > from || from > n || 0 > to || to > n) return -1; + struct ListNode *prev = NULL, *ptr = G->adjList[from]; + while (ptr != NULL) { + if (ptr->vertex == to) { + if (prev == NULL) { + G->adjList[from] = ptr->next; + free(ptr); + } else { + prev->next = ptr->next; + free(ptr); + } + return 1; + } else { + prev = ptr; + ptr = ptr->next; + } + } + return 0; +} + +struct graph* createGraph(const int numVertices) { + assert(numVertices >= 0); + // Create an empty graph with numVertices + int i, j; + struct graph* G = (struct graph *) malloc(sizeof( struct graph)); + assert(G != NULL); + G->V = numVertices; + G->E = 0; + + // allocate memory for each column and initialise with 0 + struct ListNode *newNode, *last; + for (int i = 0; i < G->V; i++) { + G->adjList[i] = (struct ListNode *) malloc(sizeof(struct ListNode)); + assert(G->adjList[i] != NULL); + G->adjList[i]->vertex = i; + G->adjList[i]->next = NULL; + } + return G; +} + +struct edge newEdge(int x, int y){ + // return an edge with ends x and y + struct edge e; + e.source = x; + e.destination = y; + return e; +} + +struct graph* randomGraph(const int N, const float p){ + // A random graph with N vertices and probability p for each edge + int i, j; + struct edge E; + struct graph* G = createGraph(N); + rand_init(); + for (i=0; i < N; i++) for(j=i+1; j < N; j++) { + if (rand() < p * RAND_MAX) { // rand() returns an integer between 0 and RAND_MAX + E = newEdge(i,j); + insertEdge(G, E); + } + } + return G; +} + +void displayGraph(struct graph* G) { + struct ListNode *ptr; + int i; + for (i = 0; i < G->V; i++) { + ptr = G->adjList[i]; + printf("\nnode %d neighbors:", i); + while (ptr != NULL) { + printf(" %d", ptr->vertex); + ptr = ptr->next; + } + } +} + +void destroyGraph(struct graph* G) { + int i; + struct ListNode *temp, *ptr; + for (i = 0; i < G->V; i++) { + ptr = G->adjList[i]; + while (ptr != NULL) { + temp = ptr; + ptr = ptr->next; + free(temp); + } + G->adjList[i] = NULL; + } + printf("\nGraph is deleted"); +} + +void DFS_iterative(struct graph* G, int visited[], int start){ + int stack[G->V]; + int top = -1, i; + visited[start] = 1; + stack[++top] = start; + struct ListNode *p = NULL; + while (top != -1) { + start = stack[top--]; + printf("%d ", start); + p = G->adjList[start]; + while (p) { + i = p->vertex; + if (visited[i] == 0) { + stack[++top] = i; + visited[i] = 1; + } + p = p->next; + } + } +} + +void DFS_recursive(struct graph* G, int visited[], int start){ + int i; + struct ListNode *p = NULL; + visited[start] = 1; + printf("%d ", start); + p = G->adjList[start]; + while (p) { + i = p->vertex; + if (visited[i] == 0) { + DFS_recursive(G, visited, i); + } + p = p->next; + } +} + +int main(int argc, char *args[]) { + // Test code + struct edge E; + int n = 10; + struct graph* G = randomGraph(n, 0.15); + displayGraph(G); + + // initialization of visited array + int i; + int visited[n]; + for (i = 0; i < n; i++) visited[i] = 0; + printf("\nDFS recursive order:\n"); + // DFS start from 0 + DFS_recursive(G, visited, 0); + printf("\nvisited by DFS:\n"); + for (i=0; i +using namespace std ; +class Graph +{ +public : + int V ; + list *adj ; + Graph(int V); + void add_edge( int u , int v); + void print_graph(); +}; + +Graph::Graph( int V ) +{ + this -> V = V ; + this -> adj = new list [V] ; +} + +void Graph::add_edge( int u , int v) +{ + this -> adj[u].push_back(v); +} + +void Graph::print_graph() +{ + cout << "The Graph formed is : " << endl ; + for ( int i = 0 ; i < this -> V ; i++ ) + { + cout << i << " -> " ; + for ( auto it = this -> adj[i].begin() ; it != this -> adj[i].end() ; it++ ) + { + cout << *it << " " ; + } + cout << endl ; + } +} + +int main () +{ + Graph graph(4); + graph.add_edge(0, 1); + graph.add_edge(0, 2); + graph.add_edge(1, 2); + graph.add_edge(2, 0); + graph.add_edge(2, 3); + graph.add_edge(3, 3); + graph.print_graph(); + return 0; +} diff --git a/src/Chapter_09_Graph_Algorithms/GraphUsingAdjacencyMatrix.cpp b/src/Chapter_09_Graph_Algorithms/GraphUsingAdjacencyMatrix.cpp new file mode 100644 index 0000000..d98f180 --- /dev/null +++ b/src/Chapter_09_Graph_Algorithms/GraphUsingAdjacencyMatrix.cpp @@ -0,0 +1,57 @@ +/* + Author : Shivam Chauhan + Date : March 28 , 2019 + Graph using Adjacency Matrix +*/ +#include +using namespace std ; +class Graph +{ +public : + int V ; + int *adj_mat; + Graph(int V); + void add_edge( int u , int v); + void print_graph(); +}; + +Graph::Graph( int V ) +{ + this -> V = V ; + /* + Using 1-D array as 2-D in place of arr[i][j] -> arr[ i * row_size + j ] is used + */ + adj_mat = new int[V*V](); // default initialise array with 0 , don't use (0) + +} + +void Graph::add_edge( int u , int v) +{ + adj_mat[u * V + v] = 1 ; +} + +void Graph::print_graph() +{ + cout << "The Graph formed is : " << endl ; + for ( int i = 0 ; i < this -> V ; i++ ) + { + for ( int j = 0 ; j < this -> V ; j++ ) + { + cout << this -> adj_mat[i*V+j] << " " ; + } + cout << endl ; + } +} + +int main () +{ + Graph graph(4); + graph.add_edge(0, 1); + graph.add_edge(0, 2); + graph.add_edge(1, 2); + graph.add_edge(2, 0); + graph.add_edge(2, 3); + graph.add_edge(3, 3); + graph.print_graph(); + return 0; +} diff --git a/src/Chapter_09_Graph_Algorithms/TopologicalSort.c b/src/Chapter_09_Graph_Algorithms/TopologicalSort.c new file mode 100644 index 0000000..b1baf37 --- /dev/null +++ b/src/Chapter_09_Graph_Algorithms/TopologicalSort.c @@ -0,0 +1,210 @@ +// Copyright (c) 2008 CareerMonk Publications and others. +// E-Mail : info@careermonk.com +// Creation Date : 2008-01-10 06:15:46 +// Created by : Narasimha Karumanchi +// Book Title : Data Structures And Algorithms Made Easy +// Warranty : This software is provided "as is" without any +// warranty; without even the implied warranty of +// merchantability or fitness for a particular purpose. +#include +#include +#include +#include +#define MAX_VERTICES 50 // max number of vertices for our graph +#define MAX_DEGREE 50 // max degree for a vertex + +struct graph{ + int V; // number of vertices + int E; // number of edges + int **adjMatrix; // adjacency matrix +}; + +struct edge{ + int source; + int destination; +}; + +void rand_init(void){ + // Initializes the random generator rand() + time_t t; + srand((unsigned) time(&t)); +} + +struct graph* createGraph(const int numVertices){ + assert(numVertices >= 0); + // Create an empty graph with numVertices + int i, j; + struct graph* G = (struct graph *) malloc(sizeof( struct graph)); + G->V = numVertices; + G->E = 0; + // allocate memory for each row + G->adjMatrix = malloc(numVertices * sizeof(int *)); + assert(G != NULL); + // allocate memory for each column and initialise with 0 + for (i = 0; i < numVertices; i++) { + G->adjMatrix[i] = calloc(numVertices, sizeof(int)); + assert(G->adjMatrix[i] != NULL); + } + return G; +} + +void displayGraph(const struct graph* G){ + // Display the graph (adjMatrix) + int i, j, v; + v = G->V; + printf("%d vertices; %d edges.\n", G->V, G->E); + for(i=0; i< v; i++){ + for(j=0; j < v; j++) printf("%3d ",(G->adjMatrix)[i][j]); + printf("\n"); + } +} + +void displayEdges(const struct graph* G){ + int v,i,j; + v = G->V; + for(i=0; i < v; i++){ + for(j=i+1; j < v; j++){ + if(G->adjMatrix[i][j]==1) printf("%d-%d ",i,j); + } + } +} + +void insertEdge(struct graph* G, const struct edge E){ + int v, x, y; + v = G->V; + x = E.source; + y = E.destination; + if(x >= v || y >= v) { + printf("Error when adding edge."); + exit(EXIT_FAILURE); + } + if (G->adjMatrix[x][y] == 0){ // For undirected graphs set both the bits + G->adjMatrix[x][y] = 1; + (G->E)++; + } +} + +void removeEdge(struct graph* G, const struct edge E){ + int v, x, y; + v = G->V; + x = E.source; + y = E.destination; + if(x >= v || y >= v) { + printf("Error when deleting edge."); + exit(EXIT_FAILURE); + } + if (G->adjMatrix[x][y] == 1){ + G->adjMatrix[x][y] = 0; + G->adjMatrix[y][x] = 0; + (G->E)--; + } +} + +void destroyGraph(struct graph* G){ // to free memory + if (G){ + if (G->adjMatrix){ + int i; + for (i = 0; i < G->V; i++) + free(G->adjMatrix[i]); + free(G->adjMatrix); + } + free(G); + } +} + +struct edge newEdge(int x, int y){ + // return an edge with ends x and y + struct edge e; + e.source = x; + e.destination = y; + return e; +} + +struct graph* randomGraph(const int N, const float p){ + // A random graph with N vertices and probability p for each edge + int i, j; + struct edge E; + struct graph* G = createGraph(N); + rand_init(); + for (i=0; i < N; i++) for(j=i+1; j < N; j++) { + if (rand() < p * RAND_MAX) { // rand() returns an integer between 0 and RAND_MAX + E = newEdge(i,j); + insertEdge(G, E); + } + } + return G; +} + +int queue[MAX_VERTICES], front = -1, rear = -1; + +int findIndegree(struct graph* G, int node) { + int i, indegree = 0; + for (i = 0; i < G->V; i++) { + if (G->adjMatrix[i][node] == 1) + indegree++; + } + return indegree; +} + +void insertQueue(int node) { + if (rear == MAX_VERTICES) + printf("\nOVERFLOW "); + else { + if (front == -1) /*If queue is initially empty */ + front = 0; + queue[++rear] = node; + } +} + +int deleteQueue() { + int del_node; + if (front == -1 || front > rear) { + printf("\nUNDERFLOW %d %d", front, rear); + return -1; + } else { + del_node = queue[front++]; + return del_node; + } +} + +void topologicalSort( struct graph *G ) { + int topsort[G->V], indeg[G->V]; + + /*Find the in-degree of each node*/ + int i; + for (i = 0; i < G->V; i++) { + indeg[i] = findIndegree(G, i); + if (indeg[i] == 0) + insertQueue(i); + } + + int j=0; + int del_node; + while (front <= rear){ /*Continue loop until queue is empty */ + del_node = deleteQueue(); + topsort[j] = del_node; /*Add the deleted node to topsort*/ + j++; + + /*Delete the del_node edges */ + for (i = 0; i < G->V; i++) { + if (G->adjMatrix[del_node][i] == 1) { + G->adjMatrix[del_node][i] = 0; + indeg[i] = indeg[i] - 1; + if (indeg[i] == 0) + insertQueue(i); + } + } + } + + printf("The topological sorting can be given as:\n"); + for (i=0; i +using namespace std; +void sortedSquaredArray(int A[], int n) { + int result[n]; + for (int i = 0; i < n; ++i) + result[i] = A[i] * A[i]; + + sort(result, result+n); + + cout << "\nSorted squares array " << endl; + for (int i = 0 ; i < n ; i++) + cout << result[i] << " " ; +} + +int main(){ + int A[] = { -4, -3, -1, 3, 4, 5 }; + int n = sizeof(A)/sizeof(A[0]); + + cout << "Given sorted array " << endl; + for (int i = 0; i < n; i++) + cout << A[i] << " " ; + sortedSquaredArray(A, n); + return 0; +} diff --git a/src/Chapter_10_Sorting/SortedSquaredArray2.cpp b/src/Chapter_10_Sorting/SortedSquaredArray2.cpp new file mode 100644 index 0000000..0c889f6 --- /dev/null +++ b/src/Chapter_10_Sorting/SortedSquaredArray2.cpp @@ -0,0 +1,58 @@ +/*Copyright (c) 2016 CareerMonk Publications and others. +#E-Mail : info@careermonk.com +#Creation Date : 2008-01-10 06:15:46 +#Created by : Narasimha Karumanchi +#Book Title : Data Structures And Algorithms Made Easy +#Warranty : This software is provided "as is" without any +# warranty; without even the implied warranty of +# merchantability or fitness for a particular purpose.*/ + +#include +using namespace std; +void sortedSquaredArray(int A[], int n) { + int result[n]; + int j = 0; + // Find the last index of the negative numbers + while (j < n && A[j] < 0) + j++; + + // i points to the last index of negative numbers + int i = j-1; + + int t = 0; + // j points to the first index of the positive numbers + while (i >= 0 && j < n) { + if (A[i] * A[i] < A[j] * A[j]) { + result[t++] = A[i] * A[i]; + i--; + } else { + result[t++] = A[j] * A[j]; + j++; + } + } + // add the remaining negative numbers squares to result + while (i >= 0) { + result[t++] = A[i] * A[i]; + i--; + } + + // add the remaining positive numbers squares to result + while (j < n) { + result[t++] = A[j] * A[j]; + j++; + } + cout << "\nSorted squares array " << endl; + for (int i = 0 ; i < n ; i++) + cout << result[i] << " " ; +} + +int main(){ + int A[] = { -4, -3, -1, 3, 4, 5 }; + int n = sizeof(A)/sizeof(A[0]); + + cout << "Given sorted array " << endl; + for (int i = 0; i < n; i++) + cout << A[i] << " " ; + sortedSquaredArray(A, n); + return 0; +} diff --git a/src/Chapter_10_Sorting/bubbleSort.c b/src/Chapter_10_Sorting/bubbleSort.c new file mode 100644 index 0000000..092dc26 --- /dev/null +++ b/src/Chapter_10_Sorting/bubbleSort.c @@ -0,0 +1,54 @@ +/*Copyright (c) 2008 CareerMonk Publications and others. +#E-Mail : info@careermonk.com +#Creation Date : 2008-01-10 06:15:46 +#Created by : Narasimha Karumanchi +#Book Title : Data Structures And Algorithms Made Easy +#Warranty : This software is provided "as is" without any +# warranty; without even the implied warranty of +# merchantability or fitness for a particular purpose.*/ + +// Bubble Sort in C +#include + +void bubbleSortImproved(int data[], int size) { + int pass, i, temp, swapped = 1; + for (pass = size - 1; pass >= 0 && swapped; pass--) { + swapped = 0; + for (i = 0; i <= pass - 1 ; i++) { + if(data[i] > data[i+1]) { + // swap elements + temp = data[i]; + data[i] = data[i+1]; + data[i+1] = temp; + swapped = 1; + } + } + } +} + +void bubbleSort(int data[], int size){ + for(int step=0; step to <. + if (data[i]>data[i+1]){ + int temp = data[i]; + data[i] = data[i+1]; + data[i+1]= temp; + } + } + } +} +void printArray(int data[], int size){ + for(int i=0; i + +void insertionSort(int data[], int size) { + int i, j, key; + for (i = 1; i <= size - 1; i++) { + key = data[i]; + j = i; + while (j >= 1 && data[j-1] > key) { + data[j] = data[j-1]; + j--; + } + data[j] = key; + } +} + + +void printArray(int data[], int size){ + for(int i=0; i + +int MinIndex(int A[], int N) +{ + int min = A[0], minindex = 0; + + for (int i = 1; i < N; i++) + { + if (min > A[i]) + { + min = A[i]; + minindex = i; + } + } + return minindex; +} + +void sort(int A[], int N) +{ + int t, minindex = MinIndex(A, N); + + if (N > 1) + { + t = A[0]; + A[0] = A[minindex]; + A[minindex] = t; + + sort(&A[1], N - 1); + } +} + +void main() +{ + int N; + + printf("Enter N numbers to sort: "); + scanf("%d", &N); + + int A[N]; + + for (int i = 0; i < N; i++) + scanf("%d", &A[i]); + + sort(A, N); + + for (int i = 0; i < N; i++) + printf("%d ", A[i]); + + printf("\n"); +} diff --git a/src/Chapter_14_Hashing/LinearChainingImplementation.c b/src/Chapter_14_Hashing/LinearChainingImplementation.c new file mode 100644 index 0000000..b8d10be --- /dev/null +++ b/src/Chapter_14_Hashing/LinearChainingImplementation.c @@ -0,0 +1,204 @@ +/*Copyright (c) 2016 CareerMonk Publications and others. +#E-Mail : info@careermonk.com +#Creation Date : 2008-01-10 06:15:46 +#Created by : Narasimha Karumanchi +#Book Title : Data Structures And Algorithms Made Easy +#Warranty : This software is provided "as is" without any +# warranty; without even the implied warranty of +# merchantability or fitness for a particular purpose.*/ + +#include +#include +#include +#include +#include + +/* elements */ +struct element { + int key; /* key */ + int value; /* data */ +}; +typedef struct element* element; + +struct list { + element data; + struct list* next; +}; +typedef struct list* list; +/* linked lists may be NULL (= end of list) and we do not check for circularity */ + +struct chain { + list list; +}; + +/* Chains, implemented as linked lists */ +typedef struct chain* chain; + +struct table { + int capacity; + int size; + chain* buckets; +}; + +/* Hash table interface */ +typedef struct table* table; +table newHashTable (int capacity); +element put(table H, element e); +element get(table H, int key); +void deleteHashTable(table H); +chain newChain (); +element insertInChain(table H, chain C, element e); +element searchInChain(table H, chain C, int key); +void deleteChain(chain C); + +void* xmalloc(size_t capacity) { + void* p = malloc(capacity); + if (p == NULL) { + fprintf(stderr, "allocation failed\n"); + abort(); + } + return p; +} + +void* xcalloc(size_t nobj, size_t capacity) { + void* p = calloc(nobj, capacity); + if (p == NULL) { + fprintf(stderr, "allocation failed\n"); + abort(); + } + return p; +} + +void deleteList(list p) { + list q; + while (p != NULL) { + if (p->data != NULL) + /* free element, if such a function is supplied */ + free(p->data); + q = p->next; + free(p); + p = q; + } +} + +chain newChain(){ + chain C = xmalloc(sizeof(struct chain)); + C->list = NULL; + return C; +} + +// findInChain(p, key) returns list element whosecdata field has key key, or NULL if none exists +list findInChain(table H, chain C, int key){ + list p = C->list; + while (p != NULL) { + if (key == p->data->key) + return p; + p = p->next; + } + return NULL; +} + +element insertInChain(table H, chain C, element e){ + list p = findInChain(H, C, e->key); + if (p == NULL) { + /* insert new element at the beginning */ + list new_item = xmalloc(sizeof(struct list)); + new_item->data = e; + new_item->next = C->list; + C->list = new_item; + return NULL; /* did not overwrite entry */ + } else { + /* overwrite existing entry with given key */ + element oldElement = p->data; + p->data = e; + return oldElement; /* return old entry */ + } +} + +element searchInChain(table H, chain C, int key){ + list p = findInChain(H, C, key); + if (p == NULL) return NULL; + else return p->data; +} + +void deleteChain(chain C){ + deleteList(C->list); + free(C); +} + +/* hash function */ +int hash(int key, int capacity){ + return key % capacity; +} + +/* Hash table implementation */ +table newHashTable(int capacity){ + chain* A = xcalloc(capacity, sizeof(chain)); + table H = xmalloc(sizeof(struct table)); + H->capacity = capacity; + H->size = 0; + H->buckets = A; /* all initialized to NULL; */ + return H; +} + +element put(table H, element e){ + element oldElement; + int key = e->key; + int h = hash(key, H->capacity); + if (H->buckets[h] == NULL) + H->buckets[h] = newChain(); + oldElement = insertInChain(H, H->buckets[h], e); + if (oldElement != NULL) return oldElement; + H->size++; + return NULL; +} + +element get(table H, int key){ + int h = hash(key, H->capacity); + if (H->buckets[h] == NULL) return NULL; + element e = searchInChain(H, H->buckets[h], key); + return e; +} + +void deleteHashTable(table H){ + int i; + for (i = 0; i < H->capacity; i++) { + chain C = H->buckets[i]; + if (C != NULL) deleteChain(C); + } + free(H->buckets); + free(H); +} + +void deleteElement(element e) { + free(e); +} + +int main () { + int n = 100; + int capacity = 5; + int num_tests = 5; + int i; int j; + + printf("Testing buckets of capacity %d with %d values, %d times\n", capacity, n, num_tests); + for (j = 0; j < num_tests; j++) { + table H = newHashTable(capacity); + for (i = 0; i < n; i++) { + element e = xmalloc(sizeof(struct element)); + e->key = j*n+i; + e->value = j*n+i; + put(H, e); + } + for (i = 0; i < n; i++) { + int key = j*n+i; + assert(((element)get(H, key))->value == j*n+i); /* "missed existing element" */ + } + for (i = 0; i < n; i++) { + int key = (j+1)*n+i; + assert(get(H, key) == NULL); /* "found nonexistent element" */ + } + deleteHashTable(H); + } + printf("All tests passed!\n"); + return 0; +} diff --git a/src/Chapter_22_Miscellaneous_Bitwise_Hacking/DecimaltoBinary.c b/src/Chapter_22_Miscellaneous_Bitwise_Hacking/DecimaltoBinary.c new file mode 100644 index 0000000..62d20d4 --- /dev/null +++ b/src/Chapter_22_Miscellaneous_Bitwise_Hacking/DecimaltoBinary.c @@ -0,0 +1,15 @@ +#include + +void main(void){ + long num, remainder, base = 1, binary = 0; + + num = 1910; + while (num > 0){ + remainder = num % 2; + binary = binary + remainder * base; + num = num / 2; + base = base * 10; + } + printf("Given number is = %d\n", num); + printf("Its binary equivalent is = %ld\n", binary); +} diff --git a/src/Chapter_22_Miscellaneous_Bitwise_Hacking/DecimaltoBinary.cpp b/src/Chapter_22_Miscellaneous_Bitwise_Hacking/DecimaltoBinary.cpp new file mode 100644 index 0000000..cd7c57f --- /dev/null +++ b/src/Chapter_22_Miscellaneous_Bitwise_Hacking/DecimaltoBinary.cpp @@ -0,0 +1,23 @@ +#include +#include +using namespace std; + +int main(){ + long num, decimal_num, remainder, base = 1, binary = 0; + + num = 34; + decimal_num = num; + while (num > 0){ + remainder = num % 2; + binary = binary + remainder * base; + num = num / 2; + base = base * 10; + } + cout<<"Given number is = "<< decimal_num << endl; + cout<<"Its binary equivalent is = "<< binary < +using namespace std; + +int main() { + int a[7] = {1,2,1,3,1,2,1}, i, res=0; + + for(i=0;i<7;i++) + res^=a[i]; + cout< +//Note: i and j indicates the position of bits from right to left starting with 1 +int swapbits(int n, int i, int j){ + // We can simply use the XOR operator to toggle the bits. + n ^= (1 << i-1); + n ^= (1 << j-1); + return n; +} +int main(void) { + int num = 34; //Binary Number: 00100010 + int i = 3, j = 6; + printf ("\nGiven Number: %d", num); + printf ("\nBinary representation of given number: 00100010"); + num = swapbits (num, i, j); + printf ("\nGiven Number after swapping %d and %d bits: %d", i, j, num); + return 0; +} diff --git a/src/Chapter_22_Miscellaneous_Bitwise_Hacking/SwapBits.cpp b/src/Chapter_22_Miscellaneous_Bitwise_Hacking/SwapBits.cpp new file mode 100644 index 0000000..8164128 --- /dev/null +++ b/src/Chapter_22_Miscellaneous_Bitwise_Hacking/SwapBits.cpp @@ -0,0 +1,22 @@ +#include +#include +using namespace std; + +//Note: i and j indicates the position of bits from right to left starting with 1 +int swapbits(int n, int i, int j){ + // We can simply use the XOR operator to toggle the bits. + n ^= (1 << i-1); + n ^= (1 << j-1); + return n; +} + +int main() { + int num = 34; //Binary Number: 00100010 + int i = 3, j = 6; + cout << "Given Number: " << num << endl; + cout << "Binary representation of given number: 00100010" << endl; + num = swapbits (num, i, j); + cout << "Given Number after swapping " << i <<" and " << j << " bits: " << num << endl; + + return 0; +} diff --git a/src/Chapter_22_Miscellaneous_Bitwise_Hacking/countSetBitsMethod1.c b/src/Chapter_22_Miscellaneous_Bitwise_Hacking/countSetBitsMethod1.c new file mode 100644 index 0000000..9349bc7 --- /dev/null +++ b/src/Chapter_22_Miscellaneous_Bitwise_Hacking/countSetBitsMethod1.c @@ -0,0 +1,19 @@ +#include + +/* Code to find the number of 1s in binary + representation of an integer. */ +unsigned int countSetBitsMethod1(int n){ + unsigned int count = 0; + while (n) { + n &= (n-1) ; + count++; + } + return count; +} + +/* Test Code */ +int main(){ + int i = 5; + printf("Number of 1s in %d are %d", i, countSetBitsMethod1(i)); + return 0; +} diff --git a/src/Chapter_22_Miscellaneous_Bitwise_Hacking/isPowerof2.cpp b/src/Chapter_22_Miscellaneous_Bitwise_Hacking/isPowerof2.cpp new file mode 100644 index 0000000..afa7431 --- /dev/null +++ b/src/Chapter_22_Miscellaneous_Bitwise_Hacking/isPowerof2.cpp @@ -0,0 +1,17 @@ +#include +#include +using namespace std; + +bool isPowerof2(int n){ + if(!(n&(n-1))) + return true; + else + return false; +} +int main() { + int n=32; + cout<