├── basic.md ├── BST ├── C++ │ ├── C++.cpp │ ├── minimum_Heightof_BST.cpp │ └── Insert_Iterative.cpp ├── Java │ └── Java.java ├── Other │ └── Language.txt └── Python │ └── Python.py ├── Graph ├── C++ │ ├── C++.cpp │ ├── DetectCycleInADirectedGraph.cpp │ ├── DFS_traversal.cpp │ ├── cycle_detect.cpp │ ├── floyd_warshall.cpp │ └── bellman_ford.cpp ├── Java │ └── Java.java ├── Other │ └── Language.txt └── Python │ └── Python.py ├── Heap ├── C++ │ └── C++.cpp ├── Java │ └── Java.java ├── Other │ └── Language.txt └── Python │ ├── Python.py │ └── heap.py ├── Map ├── C++ │ └── C++.cpp ├── Java │ └── Java.java ├── Other │ └── Language.txt └── Python │ └── Python.py ├── Sets ├── C++ │ ├── C++.cpp │ └── A. Is your horseshoe on the other hoof.cpp ├── Java │ └── Java.java ├── Other │ └── Language.txt └── Python │ └── Python.py ├── Stack ├── C++ │ ├── C++.cpp │ ├── Stack_STl.cpp │ └── stack_operations.cpp ├── Java │ └── Java.java ├── Other │ ├── Language.txt │ └── C Sharp │ │ ├── README.md │ │ ├── stack_class.cs │ │ └── stack.cs └── Python │ ├── stack_using_list.py │ ├── stack_using_collection.deque.py │ ├── stack_using_queue.LifoQueue.py │ └── README.md ├── Tree ├── C++ │ ├── C++.cpp │ ├── oddlevel.cpp │ ├── bstfromarray.cpp │ ├── Range_Update_Trick.cpp │ ├── rightleaf.cpp │ ├── leafnodesum.cpp │ ├── leftlef.cpp │ ├── isBST.cpp │ ├── removehalfnode.cpp │ └── fix2nodeinBST.cpp ├── Java │ └── Java.java ├── Other │ └── Language.txt └── Python │ └── Python.py ├── Trie ├── C++ │ └── C++.cpp ├── Java │ └── Java.java ├── Other │ └── Language.txt └── Python │ └── Python.py ├── Vector ├── C++ │ ├── C++.cpp │ ├── Vectors_cpp │ ├── Sum of Elements in Vector.cpp │ └── Quickly find multiple left rotations of an array.cpp ├── Java │ └── Java.java ├── Other │ └── Language.txt └── Python │ └── Python.py ├── Hash Tables ├── C++ │ └── C++.cpp ├── Java │ └── Java.java ├── Other │ └── Language.txt └── Python │ └── Python.py ├── LinkedList ├── C++ │ └── C++.cpp ├── Java │ ├── Java.java │ ├── CheckHasCycle.java │ └── IntersectionOfTwoLinkedLists.java ├── Other │ └── Language.txt └── Python │ └── Python.py ├── Recursion ├── C++ │ ├── C++.cpp │ ├── TowerOfHanoi.cpp │ └── Fast_Modular_Exponent.cpp ├── Java │ └── Java.java ├── Other │ └── Language.txt └── Python │ └── Python.py ├── Segment Tree ├── C++ │ ├── C++.cpp │ └── segmenttree.cpp ├── Java │ └── Java.java ├── Other │ └── Language.txt └── Python │ └── Python.py ├── Queue ├── Java │ └── Java.java ├── Other │ └── Language.txt ├── Python │ └── Python.py └── C++ │ ├── queue_using_lib.cpp │ ├── README.md │ ├── queue_using_list.cpp │ ├── queue_using_array.cpp │ ├── queue_using_linkedlist.cpp │ ├── priority_queue.cpp │ ├── dequeue.cpp │ └── circularqueue.cpp ├── Strings ├── Java │ ├── Java.java │ ├── Palindrome.java │ └── Anagram.java ├── Other │ └── Language.txt ├── C++ │ ├── string.cpp │ ├── user_input_string.cpp │ ├── string_concatenation.cpp │ ├── removing_spaces_from_string.cpp │ ├── string_length.cpp │ ├── string_library.cpp │ └── README.md └── Python │ ├── strings.py │ └── README.md ├── Dynamic Programming ├── C++ │ ├── C++.cpp │ ├── BoxStackingProblem.cpp │ └── longest_common_subsequence_implementation.cpp ├── Java │ └── Java.java ├── Other │ └── Language.txt └── Python │ └── Python.py ├── Searching and Sorting ├── C++ │ ├── C++.cpp │ ├── selection-sort.cpp │ ├── pigeonhole_sort.cpp │ ├── Linear vs Binary Search.c │ ├── bubblesort.cpp │ ├── heapsort.cpp │ ├── mergesort.cpp │ └── quicksort.cpp ├── Java │ ├── Java.java │ └── BubbleSort.java ├── Other │ └── Language.txt └── Python │ ├── Python.py │ ├── insertion_sort.py │ ├── shell_sort.py │ ├── (ALGOEXPERT)Quick_sort.py │ ├── binary_search_iterative.py │ ├── Bubble_Sort.py │ ├── merge_sort.py │ ├── Quick_sort.py │ ├── selection_and_bubble_sort.py │ └── Binary_Search.py ├── List_Hactober.py ├── Linked Lists ├── Length_Circularll.cpp ├── DeleteHead_LinkedList.cpp ├── NodesSum_LinkedList.cpp ├── DeleteTail_Doublyll.cpp ├── Searching_LinkedList.cpp ├── Display_Doublyll.cpp ├── Display_DoublyCircularll.cpp ├── DeleteTail_Circular.cpp ├── DeleteTail_LinkedList.cpp ├── DeleteHead_Doublyll.cpp ├── Display_LinkedList.cpp ├── InsertHead_Doubly;;.cpp ├── InsertTail_Doublyll.cpp ├── JoinTwo_LinkedzLists.cpp ├── Check_Circularll.cpp ├── DeleteHead_Circularll.cpp ├── InsertTail_Circularll.cpp ├── InsertHead_Circularll.cpp ├── DeleteAtPos_Circularll.cpp ├── Insertion_LinkedList.cpp ├── Max&Min_LinkedList.cpp ├── InsertAtPos_Circular.cpp ├── linkedlistSearch.cpp ├── SinglyLinear-LinkedList.cpp ├── DoublyLinear-LinkedList.cpp ├── SinglyCircular-LinkedList.cpp └── DoublyCircular-LinkedList.cpp ├── Dictionary.py ├── sumFenwickTree.cpp ├── search.cpp ├── sort.cpp ├── Vertical Order Traversal of a Binary Tree ├── Number Theory └── SieveOfEratosthenes.cpp ├── Stack.cpp ├── reverse_Linkedlist.cpp ├── QUEUE_Hctober.cpp ├── README.md └── Array └── ArrayADT.cpp.cpp /basic.md: -------------------------------------------------------------------------------- 1 | # just a readme 2 | -------------------------------------------------------------------------------- /BST/C++/C++.cpp: -------------------------------------------------------------------------------- 1 | //Use C++ only 2 | 3 | -------------------------------------------------------------------------------- /Graph/C++/C++.cpp: -------------------------------------------------------------------------------- 1 | //Use C++ only 2 | 3 | -------------------------------------------------------------------------------- /Heap/C++/C++.cpp: -------------------------------------------------------------------------------- 1 | //Use C++ only 2 | 3 | -------------------------------------------------------------------------------- /Map/C++/C++.cpp: -------------------------------------------------------------------------------- 1 | //Use C++ only 2 | 3 | -------------------------------------------------------------------------------- /Sets/C++/C++.cpp: -------------------------------------------------------------------------------- 1 | //Use C++ only 2 | 3 | -------------------------------------------------------------------------------- /Stack/C++/C++.cpp: -------------------------------------------------------------------------------- 1 | //Use C++ only 2 | 3 | -------------------------------------------------------------------------------- /Tree/C++/C++.cpp: -------------------------------------------------------------------------------- 1 | //Use C++ only 2 | 3 | -------------------------------------------------------------------------------- /Trie/C++/C++.cpp: -------------------------------------------------------------------------------- 1 | //Use C++ only 2 | 3 | -------------------------------------------------------------------------------- /Vector/C++/C++.cpp: -------------------------------------------------------------------------------- 1 | //Use C++ only 2 | 3 | -------------------------------------------------------------------------------- /BST/Java/Java.java: -------------------------------------------------------------------------------- 1 | //Include java code 2 | 3 | -------------------------------------------------------------------------------- /BST/Other/Language.txt: -------------------------------------------------------------------------------- 1 | -Java Script and more 2 | -------------------------------------------------------------------------------- /Hash Tables/C++/C++.cpp: -------------------------------------------------------------------------------- 1 | //Use C++ only 2 | 3 | -------------------------------------------------------------------------------- /Heap/Java/Java.java: -------------------------------------------------------------------------------- 1 | //Include java code 2 | 3 | -------------------------------------------------------------------------------- /LinkedList/C++/C++.cpp: -------------------------------------------------------------------------------- 1 | //Use C++ only 2 | 3 | -------------------------------------------------------------------------------- /Map/Java/Java.java: -------------------------------------------------------------------------------- 1 | //Include java code 2 | 3 | -------------------------------------------------------------------------------- /Map/Other/Language.txt: -------------------------------------------------------------------------------- 1 | -Java Script and more 2 | -------------------------------------------------------------------------------- /Recursion/C++/C++.cpp: -------------------------------------------------------------------------------- 1 | //Use C++ only 2 | 3 | -------------------------------------------------------------------------------- /Segment Tree/C++/C++.cpp: -------------------------------------------------------------------------------- 1 | //Use C++ only 2 | 3 | -------------------------------------------------------------------------------- /Sets/Java/Java.java: -------------------------------------------------------------------------------- 1 | //Include java code 2 | 3 | -------------------------------------------------------------------------------- /Tree/Java/Java.java: -------------------------------------------------------------------------------- 1 | //Include java code 2 | 3 | -------------------------------------------------------------------------------- /Trie/Java/Java.java: -------------------------------------------------------------------------------- 1 | //Include java code 2 | 3 | -------------------------------------------------------------------------------- /Graph/Java/Java.java: -------------------------------------------------------------------------------- 1 | //Include java code 2 | 3 | -------------------------------------------------------------------------------- /Graph/Other/Language.txt: -------------------------------------------------------------------------------- 1 | -Java Script and more 2 | -------------------------------------------------------------------------------- /Graph/Python/Python.py: -------------------------------------------------------------------------------- 1 | #Include python Code 2 | 3 | -------------------------------------------------------------------------------- /Heap/Other/Language.txt: -------------------------------------------------------------------------------- 1 | -Java Script and more 2 | -------------------------------------------------------------------------------- /Heap/Python/Python.py: -------------------------------------------------------------------------------- 1 | #Include python Code 2 | 3 | -------------------------------------------------------------------------------- /Map/Python/Python.py: -------------------------------------------------------------------------------- 1 | #Include python Code 2 | 3 | -------------------------------------------------------------------------------- /Queue/Java/Java.java: -------------------------------------------------------------------------------- 1 | //Include java code 2 | 3 | -------------------------------------------------------------------------------- /Queue/Other/Language.txt: -------------------------------------------------------------------------------- 1 | -Java Script and more 2 | -------------------------------------------------------------------------------- /Queue/Python/Python.py: -------------------------------------------------------------------------------- 1 | #Include python Code 2 | 3 | -------------------------------------------------------------------------------- /Recursion/Java/Java.java: -------------------------------------------------------------------------------- 1 | //Include java code 2 | 3 | -------------------------------------------------------------------------------- /Sets/Other/Language.txt: -------------------------------------------------------------------------------- 1 | -Java Script and more 2 | -------------------------------------------------------------------------------- /Sets/Python/Python.py: -------------------------------------------------------------------------------- 1 | #Include python Code 2 | 3 | -------------------------------------------------------------------------------- /Stack/Java/Java.java: -------------------------------------------------------------------------------- 1 | //Include java code 2 | 3 | -------------------------------------------------------------------------------- /Stack/Other/Language.txt: -------------------------------------------------------------------------------- 1 | -Java Script and more 2 | -------------------------------------------------------------------------------- /Strings/Java/Java.java: -------------------------------------------------------------------------------- 1 | //Include java code 2 | 3 | -------------------------------------------------------------------------------- /Strings/Other/Language.txt: -------------------------------------------------------------------------------- 1 | -Java Script and more 2 | -------------------------------------------------------------------------------- /Tree/Other/Language.txt: -------------------------------------------------------------------------------- 1 | -Java Script and more 2 | -------------------------------------------------------------------------------- /Tree/Python/Python.py: -------------------------------------------------------------------------------- 1 | #Include python Code 2 | 3 | -------------------------------------------------------------------------------- /Trie/Other/Language.txt: -------------------------------------------------------------------------------- 1 | -Java Script and more 2 | -------------------------------------------------------------------------------- /Trie/Python/Python.py: -------------------------------------------------------------------------------- 1 | #Include python Code 2 | 3 | -------------------------------------------------------------------------------- /Vector/Java/Java.java: -------------------------------------------------------------------------------- 1 | //Include java code 2 | 3 | -------------------------------------------------------------------------------- /Vector/Other/Language.txt: -------------------------------------------------------------------------------- 1 | -Java Script and more 2 | -------------------------------------------------------------------------------- /Vector/Python/Python.py: -------------------------------------------------------------------------------- 1 | #Include python Code 2 | 3 | -------------------------------------------------------------------------------- /Dynamic Programming/C++/C++.cpp: -------------------------------------------------------------------------------- 1 | //Use C++ only 2 | 3 | -------------------------------------------------------------------------------- /Hash Tables/Java/Java.java: -------------------------------------------------------------------------------- 1 | //Include java code 2 | 3 | -------------------------------------------------------------------------------- /Hash Tables/Other/Language.txt: -------------------------------------------------------------------------------- 1 | -Java Script and more 2 | -------------------------------------------------------------------------------- /Hash Tables/Python/Python.py: -------------------------------------------------------------------------------- 1 | #Include python Code 2 | 3 | -------------------------------------------------------------------------------- /LinkedList/Java/Java.java: -------------------------------------------------------------------------------- 1 | //Include java code 2 | 3 | -------------------------------------------------------------------------------- /LinkedList/Other/Language.txt: -------------------------------------------------------------------------------- 1 | -Java Script and more 2 | -------------------------------------------------------------------------------- /LinkedList/Python/Python.py: -------------------------------------------------------------------------------- 1 | #Include python Code 2 | 3 | -------------------------------------------------------------------------------- /Recursion/Other/Language.txt: -------------------------------------------------------------------------------- 1 | -Java Script and more 2 | -------------------------------------------------------------------------------- /Recursion/Python/Python.py: -------------------------------------------------------------------------------- 1 | #Include python Code 2 | 3 | -------------------------------------------------------------------------------- /Searching and Sorting/C++/C++.cpp: -------------------------------------------------------------------------------- 1 | //Use C++ only 2 | 3 | -------------------------------------------------------------------------------- /Segment Tree/Java/Java.java: -------------------------------------------------------------------------------- 1 | //Include java code 2 | 3 | -------------------------------------------------------------------------------- /Segment Tree/Other/Language.txt: -------------------------------------------------------------------------------- 1 | -Java Script and more 2 | -------------------------------------------------------------------------------- /Dynamic Programming/Java/Java.java: -------------------------------------------------------------------------------- 1 | //Include java code 2 | 3 | -------------------------------------------------------------------------------- /Segment Tree/Python/Python.py: -------------------------------------------------------------------------------- 1 | #Include python Code 2 | 3 | -------------------------------------------------------------------------------- /Dynamic Programming/Other/Language.txt: -------------------------------------------------------------------------------- 1 | -Java Script and more 2 | -------------------------------------------------------------------------------- /Dynamic Programming/Python/Python.py: -------------------------------------------------------------------------------- 1 | #Include python Code 2 | 3 | -------------------------------------------------------------------------------- /Searching and Sorting/Java/Java.java: -------------------------------------------------------------------------------- 1 | //Include java code 2 | 3 | -------------------------------------------------------------------------------- /Searching and Sorting/Other/Language.txt: -------------------------------------------------------------------------------- 1 | -Java Script and more 2 | -------------------------------------------------------------------------------- /List_Hactober.py: -------------------------------------------------------------------------------- 1 | list = [1, 2, 3] 2 | print(list) 3 | 4 | list.append([4, 5]) 5 | print(list) 6 | 7 | list.pop(2) 8 | print(list) 9 | 10 | list.extend([234, 'abc']) 11 | print(list) 12 | 13 | list.insert(1, 'insert') 14 | print(list) -------------------------------------------------------------------------------- /Linked Lists/Length_Circularll.cpp: -------------------------------------------------------------------------------- 1 | 2 | //solution 3 | int length(Node* head) 4 | { 5 | int ct=0; 6 | if(head==NULL) return ct; 7 | 8 | Node* temp=head; 9 | do{ 10 | ct++; 11 | temp=temp->next; 12 | }while(temp!=head); 13 | 14 | return ct; 15 | } -------------------------------------------------------------------------------- /Sets/C++/A. Is your horseshoe on the other hoof.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | # define lli long long int 3 | using namespace std; 4 | int main() 5 | { 6 | sets; 7 | int x; 8 | for(int i=0;i<4;i++) 9 | { 10 | cin>>x; 11 | s.insert(x); 12 | 13 | 14 | } 15 | cout<<4-s.size(); 16 | 17 | 18 | return 0; 19 | } 20 | -------------------------------------------------------------------------------- /Dictionary.py: -------------------------------------------------------------------------------- 1 | my_dict = {'First': 'Python', 'Second': 'Java', 'Third': 'Ruby'} 2 | 3 | print(my_dict.keys()) 4 | 5 | print(my_dict.values()) 6 | 7 | print(my_dict.items()) 8 | 9 | print(my_dict.get('First')) 10 | 11 | print(my_dict.get('Java')) 12 | 13 | print(my_dict.items()) 14 | 15 | mydict.get("hello",0) 16 | 17 | k=dict.pop(1) 18 | print(k) 19 | -------------------------------------------------------------------------------- /Linked Lists/DeleteHead_LinkedList.cpp: -------------------------------------------------------------------------------- 1 | //Given a linked list of size n, you have to delete the head of the linked list and return the new head. 2 | //Note: Please also set the next of the original head to null. 3 | 4 | Node* deleteHead(Node *head) 5 | { 6 | Node* temp=head->next; 7 | head->next=NULL; 8 | 9 | delete head; 10 | 11 | return temp; 12 | } -------------------------------------------------------------------------------- /Linked Lists/NodesSum_LinkedList.cpp: -------------------------------------------------------------------------------- 1 | //Given a singly linked list of size N. The task is to sum the elements of the linked list. 2 | //solution 3 | 4 | int sumOfElements(Node *head) 5 | { 6 | int sum=0; 7 | if(head==NULL) 8 | return 0; 9 | Node* temp=head; 10 | while(temp!=NULL) 11 | { 12 | sum=sum+temp->data; 13 | temp=temp->next; 14 | } 15 | return sum; 16 | } -------------------------------------------------------------------------------- /Strings/C++/string.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() { 5 | 6 | //Declaring String 7 | string name1 = "ACES DYPCOE"; 8 | cout<next->next) temp=temp->next; 10 | 11 | delete temp->next; 12 | temp->next=NULL; 13 | 14 | return head; 15 | } -------------------------------------------------------------------------------- /Linked Lists/Searching_LinkedList.cpp: -------------------------------------------------------------------------------- 1 | //Search given element in Linked list 2 | //solution 3 | 4 | bool searchLinkedList(Node *head, int x) 5 | { 6 |    int pos=1; 7 |    Node* temp=head; 8 |    while(temp!=NULL) 9 |    { 10 |        if(temp->data==x) 11 |        return pos; 12 |        else 13 |        { 14 |            pos++; 15 |            temp=temp->next; 16 |        } 17 |    } 18 |     return 0;    19 | } -------------------------------------------------------------------------------- /Linked Lists/Display_Doublyll.cpp: -------------------------------------------------------------------------------- 1 | //Given a doubly linked list of n elements. The task is to display the linked list. 2 | //solution 3 | 4 | vector displayList(Node *head) 5 | { 6 | vectorv; 7 | if(head==NULL) 8 | return v; 9 | Node* temp=head; 10 | while(temp) 11 | { 12 | v.push_back(temp->data); 13 | temp=temp->next; 14 | } 15 | return v; 16 | 17 | } -------------------------------------------------------------------------------- /Strings/C++/user_input_string.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() { 5 | 6 | string name; 7 | string college; 8 | 9 | // taking input from user 10 | cout<<"Enter you Name: "; 11 | getline(cin,name); 12 | cout<<"Your name is "<v; 4 | Node* temp=head; 5 | while(temp->next!=head) 6 | { 7 | v.push_back(temp->data); 8 | cout<data<<" "; 9 | temp=temp->next; 10 | } 11 | cout<data<<" "; 12 | v.push_back(temp->data); 13 | cout<=0;i--) 15 | cout< q; 9 | q.push(root); 10 | while(1){ 11 | int size=q.size(); 12 | if(size==0) 13 | break; 14 | while(size>0){ 15 | Node *temp=q.front(); 16 | if(level%2!=0) 17 | cout<data<<" "; 18 | q.pop(); 19 | if(temp->left) 20 | q.push(temp->left); 21 | if(temp->right) 22 | q.push(temp->right); 23 | size--; 24 | } 25 | level++; 26 | -------------------------------------------------------------------------------- /Recursion/C++/TowerOfHanoi.cpp: -------------------------------------------------------------------------------- 1 | // To calculate the steps reequired in complaeting Tower of Hanoi challenge 2 | #include 3 | using namespace std; 4 | 5 | void TOH (int n, int A, int B, int C) 6 | { 7 | if(n>0) 8 | { 9 | TOH(n-1, A, C, B); 10 | cout<<"("<next->next!=head) temp=temp->next; 11 | temp->next=head; 12 | return head; 13 | } -------------------------------------------------------------------------------- /Linked Lists/DeleteTail_LinkedList.cpp: -------------------------------------------------------------------------------- 1 | //Given a linked list of size n, you have to delete the tail (last element) in the linked list. 2 | //solution 3 | 4 | Node* deleteTail(Node *head) 5 | { 6 | //empty linked list 7 | if(head==NULL) 8 | return head; 9 | 10 | Node* temp=head; 11 | while(temp->next->next!=NULL) 12 | temp=temp->next; 13 | 14 | delete temp->next; 15 | temp->next=NULL; 16 | 17 | return head; 18 | } -------------------------------------------------------------------------------- /Stack/Python/stack_using_list.py: -------------------------------------------------------------------------------- 1 | 2 | stack = [] 3 | 4 | # append() function to push element in the stack 5 | stack.append('a') 6 | stack.append('b') 7 | stack.append('c') 8 | 9 | print('Initial stack') 10 | print(stack) 11 | 12 | # pop() fucntion to pop element from stack 13 | print('\nElements poped from stack:') 14 | print(stack.pop()) 15 | print(stack.pop()) 16 | print(stack.pop()) 17 | 18 | print('\nStack after elements are poped:') 19 | print(stack) -------------------------------------------------------------------------------- /Linked Lists/DeleteHead_Doublyll.cpp: -------------------------------------------------------------------------------- 1 | //Given a doubly linked list of size n, you have to delete the head of the linked list and return the new head. 2 | //Note: Please set the previous of new head to null, and set the next of old head to null, and then delete the old head. 3 | 4 | Node *deleteHead(Node * head) 5 | { 6 | if(head==NULL) return NULL; 7 | Node* temp=head; 8 | 9 | head=temp->next; 10 | head->prev=NULL; 11 | 12 | delete temp; 13 | return head; 14 | } -------------------------------------------------------------------------------- /Linked Lists/Display_LinkedList.cpp: -------------------------------------------------------------------------------- 1 | //Given a singly linked list of integers. The task is to display the linked list. 2 | //solution code snippet 3 | 4 | 5 | vector displayList(Node *head) 6 | { 7 | vectorv; 8 | //empty linked list 9 | if(head==NULL) 10 | return v; 11 | Node* temp=head; 12 | while(temp!=NULL) 13 | { 14 | int val=temp->data; 15 | v.push_back(val); 16 | temp=temp->next; 17 | } 18 | return v; 19 | } -------------------------------------------------------------------------------- /Linked Lists/InsertHead_Doubly;;.cpp: -------------------------------------------------------------------------------- 1 | //Given a doubly linked list of size n, you need to insert an element data before the head and make it the new head. 2 | 3 | //solution 4 | Node *insertInHead(Node * head, int data) 5 | { 6 | Node* newn = new Node(data); 7 | 8 | if(head==NULL) 9 | head=newn; 10 | else 11 | { 12 | Node* temp=head; 13 | newn->next=head; 14 | head->prev=newn; 15 | head=newn; 16 | } 17 | return head; 18 | } -------------------------------------------------------------------------------- /Linked Lists/InsertTail_Doublyll.cpp: -------------------------------------------------------------------------------- 1 | //Given a doubly linked list of size n, you need to insert an element data after the tail. 2 | //solution 3 | 4 | Node *insertInTail(Node * head, int data) 5 | { 6 | Node* newn=new Node(data); 7 | 8 | if(head==NULL) 9 | head=newn; 10 | else 11 | { 12 | Node* temp=head; 13 | while(temp->next!=NULL) 14 | temp=temp->next; 15 | 16 | temp->next=newn; 17 | newn->prev=temp; 18 | } 19 | return head; 20 | } -------------------------------------------------------------------------------- /Linked Lists/JoinTwo_LinkedzLists.cpp: -------------------------------------------------------------------------------- 1 | //Given two linked lists of size n1 and n2 respectively, 2 | //you have to join the head of second list to the tail of first so that we can traverse both the lists using head of 1st list. 3 | 4 | //solution 5 | Node * joinTheLists(Node * head1, Node * head2) 6 | { 7 | if(head1==NULL) 8 | head1=head2; 9 | 10 | Node* temp=head1; 11 | 12 | while(temp->next!=NULL) 13 | temp=temp->next; 14 | 15 | temp->next=head2; 16 | 17 | return head1; 18 | } -------------------------------------------------------------------------------- /Stack/Python/stack_using_collection.deque.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | 3 | stack = deque() 4 | 5 | # append() function to push element in the stack 6 | stack.append('a') 7 | stack.append('b') 8 | stack.append('c') 9 | 10 | print('Initial stack:') 11 | print(stack) 12 | 13 | # pop() fucntion to pop element from stack 14 | 15 | print('\nElements poped from stack:') 16 | print(stack.pop()) 17 | print(stack.pop()) 18 | print(stack.pop()) 19 | 20 | print('\nStack after elements are poped:') 21 | print(stack) -------------------------------------------------------------------------------- /Linked Lists/Check_Circularll.cpp: -------------------------------------------------------------------------------- 1 | //Given a singly linked list, find if the linked list is circular or not. A linked list is called circular if it not NULL terminated and all nodes are connected in the form of a cycle. An empty linked list is considered as circular. 2 | //solution 3 | 4 | bool isCircular(Node *head) 5 | { 6 | if(head==NULL || head->next==head) return true; 7 | Node* temp=head; 8 | while(temp->next!=NULL && temp->next!=head) 9 | temp=temp->next; 10 | 11 | return (temp->next==head)?true:false; 12 | } -------------------------------------------------------------------------------- /sumFenwickTree.cpp: -------------------------------------------------------------------------------- 1 | struct FenwickTree { 2 | vector bit; // binary indexed tree 3 | int n; 4 | 5 | FenwickTree (int n) { 6 | this->n = n + 1; 7 | bit.assign(n + 1, 0); 8 | } 9 | 10 | int sum(int idx) { 11 | int ret = 0; 12 | for ( ; idx > 0; idx -= idx & -idx) 13 | ret += bit[idx]; 14 | return ret; 15 | } 16 | 17 | void add(int idx, int delta) { 18 | for ( ; idx < n; idx += idx & -idx) 19 | bit[idx] += delta; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /Vector/C++/Vectors_cpp: -------------------------------------------------------------------------------- 1 | @aryansingho7 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | int main(){ 7 | 8 | vector v; 9 | v.push_back(1); 10 | v.push_back(2); 11 | v.push_back(3); 12 | v.push_back(4); 13 | v.push_back(5); 14 | cout<<"size : "< 2 | using namespace std; 3 | void create(int ar[],int start,int end) 4 | { 5 | 6 | if(start > end) 7 | return; 8 | 9 | int mid = (start+end)/2; 10 | cout<>t; 22 | while(t--) 23 | { 24 | int n; 25 | cin>>n; 26 | int a[n]; 27 | for(int i=0;i>a[i]; 30 | } 31 | 32 | create(a,0,n-1); 33 | 34 | 35 | cout<next!=head) temp=temp->next; 14 | temp->next=temp1->next; 15 | head=temp1->next; 16 | temp1->next=NULL; 17 | return head; 18 | } -------------------------------------------------------------------------------- /Stack/Python/stack_using_queue.LifoQueue.py: -------------------------------------------------------------------------------- 1 | from queue import LifoQueue 2 | 3 | # Initializing a stack 4 | stack = LifoQueue(maxsize = 3) 5 | 6 | # qsize() show the number of elements in the stack 7 | print(stack.qsize()) 8 | 9 | # put() function to push element in the stack 10 | stack.put('a') 11 | stack.put('b') 12 | stack.put('c') 13 | 14 | print("Full: ", stack.full()) 15 | print("Size: ", stack.qsize()) 16 | 17 | # get() fucntion to pop element from stack 18 | 19 | print('\nElements poped from the stack') 20 | print(stack.get()) 21 | print(stack.get()) 22 | print(stack.get()) 23 | 24 | print("\nEmpty: ", stack.empty()) -------------------------------------------------------------------------------- /Linked Lists/InsertTail_Circularll.cpp: -------------------------------------------------------------------------------- 1 | //Given a circular linked list of size N, you need to insert an element data after the tail. 2 | //The tail of the linked list is connected to head. 3 | 4 | //solution 5 | Node *insertInTail(Node * head, int data) 6 | { 7 | Node* newn=new Node(data); 8 | if(head==NULL) 9 | { 10 | head=newn; 11 | newn->next=head; 12 | } 13 | else 14 | { 15 | Node* temp=head; 16 | 17 | while(temp->next!=head) 18 | { 19 | temp=temp->next; 20 | } 21 | temp->next=newn; 22 | newn->next=head; 23 | } 24 | return head; 25 | } -------------------------------------------------------------------------------- /Vector/C++/Sum of Elements in Vector.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | int n; 7 | cout<<"Enter no. of Elements : "; 8 | cin>>n; 9 | 10 | vector v; 11 | int a; 12 | 13 | cout<<"Enter the Elements : "; 14 | for(int i=0;i>a; 17 | v.push_back(a); 18 | } 19 | 20 | cout << "\nVector: "; 21 | for (int i = 0; i < n ;i++) 22 | cout << v[i] << " "; 23 | cout << endl; 24 | 25 | cout << "\nSum = " 26 | << accumulate(v.begin(), v.end(), 0); 27 | return 0; 28 | } -------------------------------------------------------------------------------- /search.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | 5 | int search(int arr[], int n, int x) 6 | { 7 | int i; 8 | for (i = 0; i < n; i++) 9 | if (arr[i] == x) 10 | return i; 11 | return -1; 12 | } 13 | 14 | // Driver code 15 | int main() 16 | { 17 | int arr[] = { 3, 4, 1, 7, 5 }; 18 | int n = sizeof(arr) / sizeof(arr[0]); 19 | int x = 4; 20 | 21 | int index = search(arr, n, x); 22 | if (index == -1) 23 | cout << "Element is not present in the array"; 24 | else 25 | cout << "Element found at position " << index; 26 | 27 | return 0; 28 | } -------------------------------------------------------------------------------- /Strings/C++/string_concatenation.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() { 5 | 6 | //Declaring String 7 | string name1 = "ACES "; 8 | string name2 = "DYPCOE"; 9 | 10 | // Direct Concatenation 11 | cout<<"Direct Concatenation : "<< name1 + name2 <next=head; 11 | } 12 | 13 | else 14 | { 15 | Node* temp=head; 16 | do{ 17 | temp=temp->next; 18 | }while(temp->next!=head); 19 | newn->next=head; 20 | head=newn; 21 | temp->next=head; 22 | } 23 | return head; 24 | } -------------------------------------------------------------------------------- /Strings/C++/removing_spaces_from_string.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // Function to remove all spaces from a given string 5 | void removeSpaces(char *str) 6 | { 7 | // To keep track of non-space character count 8 | int count = 0; 9 | 10 | // Traverse the given string. If current character 11 | // is not space, then place it at index 'count++' 12 | for (int i = 0; str[i]; i++) 13 | if (str[i] != ' ') 14 | str[count++] = str[i]; 15 | str[count] = '\0'; 16 | } 17 | 18 | 19 | int main() 20 | { 21 | char str[] = "AC ES -D YP CO E "; 22 | removeSpaces(str); 23 | cout << str<next==head) 10 | return NULL; 11 | Node *temp=head->next; 12 | head->next=head->next->next; 13 | delete(temp); 14 | return head; 15 | } 16 | else 17 | { 18 | Node *temp=head; 19 | Node *cur; 20 | for(int i=0;inext; 21 | cur=temp->next; 22 | temp->next=temp->next->next; 23 | delete(cur); 24 | return head; 25 | } 26 | } -------------------------------------------------------------------------------- /Heap/Python/heap.py: -------------------------------------------------------------------------------- 1 | #Python Program to create a heapsort, pushing all values onto a heap and 2 | #then popping off the smallest values one at a time 3 | 4 | import heapq #importing heapq file 5 | def heapsort(h): #initialize the class definition 6 | heap = [] 7 | for value in h: 8 | heapq.heappush(heap, value) #push function to push all values onto a heap 9 | return [heapq.heappop(heap) for i in range(len(heap))] #inner for loop to return the sortted values 10 | 11 | x=input('Enter the values: ').split() #split function to take input from user 12 | #note : Use spacebar while writing input 13 | 14 | print(heapsort(x)) 15 | 16 | #Time complexity : O(nLogn) 17 | #space complexity : O(1) -------------------------------------------------------------------------------- /Searching and Sorting/Python/Python.py: -------------------------------------------------------------------------------- 1 | #Insertion sort 2 | 3 | class Point: 4 | def __init__(self, a): #initialize the class definition 5 | self.a = a 6 | 7 | 8 | def insertion_sort(alist): 9 | for i in range(1, len(alist)): 10 | temp = alist[i] #initialize temp to alist 11 | j = i - 1 12 | while (j >= 0 and temp < alist[j]): 13 | alist[j + 1] = alist[j] 14 | j = j - 1 15 | alist[j + 1] = temp 16 | 17 | 18 | alist = input('Enter the list of numbers: ').split() 19 | alist = [int(x) for x in alist] 20 | insertion_sort(alist) #calling class definition 21 | for point in alist: 22 | print('Sorted list: ', end='') 23 | print(alist) 24 | 25 | #Time Complexity: O(n2) 26 | -------------------------------------------------------------------------------- /Searching and Sorting/C++/selection-sort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | void selection_sort(int a[], int n) 4 | { 5 | for(int i=0;i>n; 24 | int a[1000]; 25 | int i; 26 | for( i=0; i>a[i]; 29 | } 30 | 31 | selection_sort(a, n); 32 | for(i=0; i= 0 and temp < alist[j]): 11 | alist[j + 1] = alist[j] 12 | j = j - 1 13 | alist[j + 1] = temp 14 | 15 | 16 | alist = input('Enter the list of numbers: ').split() 17 | alist = [int(x) for x in alist] 18 | insertion_sort(alist) #calling class definition 19 | for point in alist: 20 | print('Sorted list: ', end='') 21 | print(alist) 22 | 23 | #Time Complexity: O(n2) 24 | -------------------------------------------------------------------------------- /sort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | void selectionSort(int a[], int n) { 4 | int i, j, min, temp; 5 | for (i = 0; i < n - 1; i++) { 6 | min = i; 7 | for (j = i + 1; j < n; j++) 8 | if (a[j] < a[min]) 9 | min = j; 10 | temp = a[i]; 11 | a[i] = a[min]; 12 | a[min] = temp; 13 | } 14 | } 15 | int main() { 16 | int a[] = { 22, 91, 35, 78, 10, 8, 75, 99, 1, 67 }; 17 | int n = sizeof(a)/ sizeof(a[0]); 18 | int i; 19 | cout<<"Given array is:"< 2 | using namespace std; 3 | 4 | int main() { 5 | 6 | //Declaring String 7 | string name1 = "ACES-DYPCOE"; 8 | char myString[] = "ACES-DYPCOE"; 9 | 10 | //calculating length using length() function 11 | cout<<"using Length() : "<next=head; 12 |        head=newn; 13 |    } 14 |    return head; 15 | } 16 | 17 | // function appends the data at the end of the list 18 | Node *insertAtEnd(Node *head, int newData)  { 19 |   Node *newn=new Node(newData); 20 |   if(head==NULL) 21 |      head=newn; 22 |    else 23 |    { 24 |        Node* temp=head; 25 |        while(temp->next!=NULL) 26 |            temp=temp->next; 27 | 28 |        temp->next=newn; 29 |    } 30 |    return head; 31 | } -------------------------------------------------------------------------------- /Vector/C++/Quickly find multiple left rotations of an array.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // Function to left rotate an array k times 5 | void leftRotate(int arr[], int n, int k) 6 | { 7 | // Print array after k rotations 8 | cout<<"\nAns :" 9 | for (int i = k; i < k + n; i++) 10 | cout << arr[i%n] << " "; 11 | } 12 | 13 | 14 | int main() 15 | { 16 | int n; 17 | cout<<"Enter Number of Elements in array : "; 18 | cin>>n; 19 | 20 | cout<<"\nEnter Elements : "; 21 | int arr[n]; 22 | for(int i=0;i>arr[i]; 24 | 25 | 26 | int k; 27 | cout<<"Enter number of Left rotations to be performed : "; 28 | cin>>k; 29 | leftRotate(arr, n, k); 30 | 31 | return 0; 32 | } -------------------------------------------------------------------------------- /LinkedList/Java/CheckHasCycle.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode(int x) { 7 | * val = x; 8 | * next = null; 9 | * } 10 | * } 11 | */ 12 | public class Solution { 13 | public boolean hasCycle(ListNode head) { 14 | ListNode slowptr = head; 15 | ListNode fastptr = head; 16 | while(slowptr!= null && fastptr!=null){ 17 | slowptr = slowptr.next; 18 | if(fastptr.next!=null){ 19 | fastptr = fastptr.next.next; 20 | } 21 | else{ 22 | return false; 23 | } 24 | if(slowptr == fastptr){ 25 | return true; 26 | } 27 | } 28 | return false; 29 | } 30 | } -------------------------------------------------------------------------------- /Linked Lists/Max&Min_LinkedList.cpp: -------------------------------------------------------------------------------- 1 | //Given a singly linked list of N elements. The task is to find the maximum and minimum element. 2 | //solution 3 | 4 | //to find max element 5 | int maximum(Node *head) 6 | { 7 | vectorv; 8 | int max=0; 9 | if(head==NULL) 10 | return max; 11 | Node* temp=head; 12 | while(temp!=NULL) 13 | { 14 | v.push_back(temp->data); 15 | temp=temp->next; 16 | } 17 | return *max_element(v.begin(),v.end()); 18 | } 19 | 20 | //to find min element 21 | int minimum(Node *head) 22 | { 23 | vectorv; 24 | int max=0; 25 | if(head==NULL) 26 | return max; 27 | Node* temp=head; 28 | while(temp!=NULL) 29 | { 30 | v.push_back(temp->data); 31 | temp=temp->next; 32 | } 33 | return *min_element(v.begin(),v.end()); 34 | } -------------------------------------------------------------------------------- /Queue/C++/queue_using_lib.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | // Queue implementation in C++ using std::queue 6 | int main() 7 | { 8 | queue q; 9 | 10 | // Insert operation 11 | q.push("A"); 12 | q.push("B"); 13 | q.push("C"); 14 | q.push("D"); 15 | 16 | // Returns the number of elements present in the queue 17 | cout << "Queue size is " << q.size() << endl; 18 | 19 | // Prints the front of the queue ("A") 20 | cout << "Front element is: " << q.front() << endl; 21 | 22 | // Prints the rear of the queue ("D") 23 | cout << "Rear element is: " << q.back() << endl; 24 | 25 | q.pop(); 26 | q.pop(); 27 | 28 | cout << "Queue size is " << q.size() << endl; 29 | 30 | // check if queue is empty 31 | if (q.empty()) 32 | cout << "Queue is Empty\n"; 33 | else 34 | cout << "Queue is not Empty\n"; 35 | 36 | return 0; 37 | } -------------------------------------------------------------------------------- /Recursion/C++/Fast_Modular_Exponent.cpp: -------------------------------------------------------------------------------- 1 | // mind blowing algorithm I learned recently 2 | // the follwing recursive funtion helps to calculate the exponent of a number.( even large numbers can be accomodated without memory overflow) 3 | // time complexity O(logn) 4 | 5 | #include 6 | 7 | using namespace std; 8 | 9 | int fastexpor(int a, long long n, int mod) 10 | { 11 | if(n==0) 12 | return 1; 13 | if(n%2==0) 14 | return fastexpor((1LL * a * a)%mod, n/2 , mod); 15 | return (1LL * a * fastexpor(a, n-1, mod))%mod; 16 | 17 | } 18 | 19 | 20 | int main() 21 | { 22 | int base, exponent; 23 | cout<<"enter the base of the exponent you want to calculate"<>base; 25 | cout<<"enter the exponent for the base"<>exponent; 27 | cout<next==head) 16 | { 17 | temp->next=head; 18 | head->next=temp; 19 | return ; 20 | } 21 | temp->next=head->next; 22 | head->next=temp; 23 | } 24 | else{ 25 | for(i=0;inext; 27 | if(cur==head){ 28 | return ; 29 | } 30 | 31 | } 32 | temp->next=cur->next; 33 | cur->next=temp; 34 | } 35 | } -------------------------------------------------------------------------------- /Queue/C++/queue_using_list.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | // Queue implementation in C++ using std::list 6 | int main() 7 | { 8 | list q; 9 | 10 | // Insert operation 11 | q.push_back("A"); 12 | q.push_back("B"); 13 | q.push_back("C"); 14 | q.push_back("D"); 15 | 16 | // Returns the number of elements present in the queue 17 | cout << "Queue size is " << q.size() << endl; 18 | 19 | // Prints the front of the queue ("A") 20 | cout << "Front element is: " << q.front() << endl; 21 | 22 | // Prints the rear of the queue ("D") 23 | cout << "Rear element is: " << q.back() << endl; 24 | 25 | // delete operation 26 | q.pop_front(); 27 | q.pop_front(); 28 | 29 | cout << "Queue size is " << q.size() << endl; 30 | 31 | // check if queue is empty 32 | if (q.empty()) 33 | cout << "Queue is Empty\n"; 34 | else 35 | cout << "Queue is not Empty\n"; 36 | 37 | return 0; 38 | } -------------------------------------------------------------------------------- /Strings/Java/Palindrome.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | public class Palindrome 3 | { 4 | public static void main(String[] args)throws IOException 5 | { 6 | InputStreamReader read = new InputStreamReader(System.in); 7 | BufferedReader in = new BufferedReader(read); 8 | 9 | System.out.println("Enter the string:"); 10 | String na = in.readLine(); 11 | 12 | Palindrome p = new Palindrome(); 13 | 14 | boolean answer = p.checkPalindrome(na); 15 | 16 | System.out.println(answer); 17 | } 18 | 19 | public boolean checkPalindrome(String na) 20 | { 21 | int len = na.length(); 22 | boolean answer = true; 23 | for(int i=0,j=len-1 ; i<(len/2) ; i++,j--) 24 | { 25 | if(na.charAt(i) != na.charAt(j)) 26 | { 27 | answer = false; 28 | break; 29 | } 30 | 31 | } 32 | return answer; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /Searching and Sorting/C++/pigeonhole_sort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #define MAX 7 4 | void pigeonhole_sort(int, int, int *); 5 | int main() { 6 | int i, min, max; 7 | int a[]={7,4,2,6,3,1,5}; 8 | min = a[0]; 9 | max = a[0]; 10 | for (i = 1; i < MAX; i++) { 11 | if (a[i] < min) { 12 | min = a[i]; 13 | } 14 | if (a[i] > max) { 15 | max = a[i]; 16 | } 17 | } 18 | pigeonhole_sort(min, max, a); 19 | for (i = 0; i < MAX; i++) { 20 | cout<< a[i]<<"\t"; 21 | } 22 | } 23 | void pigeonhole_sort(int mi, int ma, int * a) { 24 | int size, count = 0, i; 25 | int *current; 26 | current = a; 27 | size = ma - mi + 1; 28 | int holes[size]; 29 | for (i = 0; i < size; i++) { 30 | holes[i] = 0; 31 | } 32 | for (i = 0; i < size; i++, current++) { 33 | holes[*current-mi] += 1; 34 | } 35 | for (count = 0, current = &a[0]; count < size; count++) { 36 | while (holes[count]--> 0) { 37 | *current++ = count + mi; 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /Vertical Order Traversal of a Binary Tree: -------------------------------------------------------------------------------- 1 | 2 | void solve(TreeNode * root, map>>&mp , int hd, int depth){ 3 | if(root==NULL){ 4 | return ; 5 | } 6 | mp[hd].push_back({depth,root->val}); 7 | solve(root->left , mp,hd-1,depth+1); 8 | solve(root->right,mp,hd+1,depth+1); 9 | } 10 | 11 | 12 | class Solution { 13 | public: 14 | vector> verticalTraversal(TreeNode* root) { 15 | vector>A; 16 | if(root==NULL){ 17 | return A; 18 | } 19 | 20 | map>>mp; 21 | solve(root,mp,0,0); 22 | 23 | for(auto it=mp.begin();it!=mp.end();it++){ 24 | sort(it->second.begin(),it->second.end()); 25 | vectorB; 26 | for(int i=0;isecond.size();i++){ 27 | B.push_back(it->second[i].second); 28 | } 29 | 30 | A.push_back(B); 31 | 32 | } 33 | 34 | return A; 35 | 36 | } 37 | }; 38 | -------------------------------------------------------------------------------- /BST/C++/minimum_Heightof_BST.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | struct Node 5 | { 6 | int data; 7 | struct Node* left, *right; 8 | }; 9 | 10 | Node *newNode(int data) 11 | { 12 | Node *temp = new Node; 13 | temp->data = data; 14 | temp->left = temp->right = NULL; 15 | return (temp); 16 | } 17 | 18 | int minDepth(Node *root) 19 | { 20 | if (root == NULL) 21 | return 0; 22 | 23 | if (root->left == NULL && root->right == NULL) 24 | return 1; 25 | 26 | 27 | if (root->left!=NULL) 28 | return minDepth(root->right) + 1; 29 | 30 | if (root->right!=NULL) 31 | return minDepth(root->left) + 1; 32 | 33 | return min(minDepth(root->left), minDepth(root->right)) + 1; 34 | } 35 | 36 | int main() 37 | { 38 | //create a BST 39 | Node *root = newNode(1); 40 | root->left = newNode(2); 41 | root->right = newNode(3); 42 | root->left->left = newNode(4); 43 | root->left->right = newNode(5); 44 | 45 | cout <<"The minimum depth of binary tree is : "<< minDepth(root); 46 | return 0; 47 | } 48 | -------------------------------------------------------------------------------- /Stack/Other/C Sharp/README.md: -------------------------------------------------------------------------------- 1 | # Stack in C# 2 | 3 | ## A stack is a linear data structure that stores items in a Last-In/First-Out (LIFO) or First-In/Last-Out (FILO). 4 | 5 | ### Operations: 6 | 7 | 1. **Push**: Adds an item in the stack. If the stack is full, then it is said to be a stack Overflow condition. 8 | 2. **Pop**: Removes an item from the stack. The items are popped in the reversed order in which they are pushed. If the stack is empty, then it is said to be a stack Underflow condition. 9 | 3. **Peek**: Return the topmost element of stack. 10 | 11 | 12 | ## Stack class 13 | 14 | Stack class comes under **System.Collections** namespace. 15 | 16 | ### Characteristics of Stack Class: 17 | 18 | 1. The capacity of a Stack is the number of elements the Stack can hold. As elements are added to a Stack, the capacity is automatically increased as required through reallocation. 19 | 2. If Count is less than the capacity of the stack, Push is an O(1) operation. If the capacity needs to be increased to accommodate the new element, Push becomes an O(n) operation, where n is Count. Pop is an O(1) operation. 20 | 3. Stack accepts null as a valid value and allows duplicate elements. -------------------------------------------------------------------------------- /Strings/C++/string_library.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int main() { 6 | 7 | // Declaring the Strings 8 | char name1[] = "ACES"; 9 | char name2[] = "DYPCOE"; 10 | char fullName[] = "ACES-DYPOCE"; 11 | char copiedString[20]; 12 | 13 | 14 | // Copying String 15 | strcpy(copiedString, fullName); 16 | cout<<"Copied String: "< 2 | 3 | int linearSearch(int arr[], int size, int element){ 4 | for (int i = 0; i < size; i++) 5 | { 6 | if(arr[i]==element){ 7 | return i; 8 | } 9 | } 10 | return -1; 11 | } 12 | 13 | int binarySearch(int arr[], int size, int element){ 14 | int low, mid, high; 15 | low = 0; 16 | high = size-1; 17 | // Keep searching until low <= high 18 | while(low<=high){ 19 | mid = (low + high)/2; 20 | if(arr[mid] == element){ 21 | return mid; 22 | } 23 | if(arr[mid] 9 | using namespace std; 10 | 11 | int a[11], b[11], c[11]; 12 | void updateval(int x, int y, int val) 13 | { 14 | b[x-1] += val; 15 | b[y] -= val; 16 | } 17 | 18 | void buildfinalarray() 19 | { 20 | for(int i=1; i<=10; i++) 21 | { 22 | c[i] = c[i-1]+b[i]; 23 | a[i] += c[i]; 24 | 25 | } 26 | for(int j=0; j<=10; j++) 27 | { 28 | cout<>a[i]; 38 | b[i]=0; 39 | c[i]=0; 40 | } 41 | updateval(2,6,10); 42 | buildfinalarray(); 43 | 44 | int n; 45 | cin>>n; 46 | return 0; 47 | 48 | 49 | } 50 | -------------------------------------------------------------------------------- /Searching and Sorting/Python/shell_sort.py: -------------------------------------------------------------------------------- 1 | #Shell sort algorithm using python 2 | #Shell sort algorithm is an improved form of insertion sort algorithm as it compares elements separated by a gap of several position. 3 | #In Shell sort algorithm, the elements in an array are sorted in multiple passes and in each pass, data are taken with smaller and smaller gap sizes. 4 | # However, the finale of shell sort algorithm is a plain insertion sort algorithm. 5 | 6 | def shellsort(a): #initialize the function definition 7 | gap=len(a)//2 #Return the number of items in a container 8 | while gap>0: 9 | for i in range(gap,len(a)): 10 | j=a[i] ##initialize j to a[i] 11 | pos=i #initialize pos to i 12 | while pos>=gap and j= endIndex: 12 | return 13 | pivotIndex = startIndex 14 | leftIndex = startIndex + 1 15 | rightIndex = endIndex 16 | while rightIndex >= leftIndex: 17 | if array[leftIndex] > array[pivotIndex] and array[rightIndex] < array[pivotIndex]: 18 | array[leftIndex], array[rightIndex] = array[rightIndex], array[leftIndex] 19 | if array[leftIndex] <= array[pivotIndex]: 20 | leftIndex += 1 21 | if array[rightIndex] >= array[pivotIndex]: 22 | rightIndex -= 1 23 | array[rightIndex], array[pivotIndex] = array[pivotIndex], array[rightIndex] 24 | leftSubArrayIsSmaller = rightIndex - 1 - startIndex < endIndex - (rightIndex + 1) 25 | if leftSubArrayIsSmaller: 26 | quickSortHelper(array, startIndex, rightIndex - 1) 27 | quickSortHelper(array, rightIndex + 1, endIndex) 28 | else: 29 | quickSortHelper(array, rightIndex + 1, endIndex) 30 | quickSortHelper(array, startIndex, rightIndex - 1) 31 | -------------------------------------------------------------------------------- /Number Theory/SieveOfEratosthenes.cpp: -------------------------------------------------------------------------------- 1 | 2 | // Sieve of Eratosthenes is one of the most efficient algorithms to find all prime 3 | // numbers less than a given 'n' 4 | 5 | // #ALgorithm: 6 | // 1. Create a list of n+1 elements and initialize them to True. 7 | // 2. Initialize a variable, lets say 'p' to 2, the first prime number. 8 | // 3. Starting from 'p' check every element until 'n',if it is 'True' in list, modify the element at positions of multiples of'p' to 'False' 9 | 10 | // #Time Complexity: 11 | // O(nloglogn) 12 | 13 | // #Space Complexity: 14 | // O(n) 15 | // 16 | 17 | #include 18 | using namespace std; 19 | 20 | //Sieve Of Eratosthenes Function: 21 | void soe(int n) 22 | { 23 | bool isprime[n+1]; 24 | memset(isprime, true, sizeof(isprime)); //Memset is used to assign values to a list 25 | 26 | for(int p=2;p*p<=n;++p) 27 | { 28 | if(isprime[p]==true) 29 | { 30 | //Update all multiples of p to False 31 | for(int i=p*p;i<=n;i+=p) 32 | isprime[i]=false; 33 | } 34 | } 35 | 36 | //Print all Prime Numbers 37 | for(int p=2;p<=n;++p) 38 | { 39 | if(isprime[p]==true) 40 | cout<>n; 49 | 50 | cout<<"\n Prime Numbers less than "<= low: 13 | #updationg value of mid using current high and low. 14 | mid = (high + low)//2 15 | 16 | #if x is greater than middle element then x in latter half of array. 17 | if (x > arr[mid]): 18 | low = mid + 1 19 | 20 | #if x is smaller than middle element then x in former half of array. 21 | elif (x < arr[mid]): 22 | high = mid - 1 23 | 24 | #the only remaining condition is that middle element is x in that case we return value of middle 25 | else: 26 | return mid 27 | 28 | #if location of x is not found in above loop that suggests x is not present in the array, so we return -1. 29 | return -1 30 | 31 | arr = [11,23,45,63,72,89,94,112,234] 32 | loc = binary_search_iterative(arr,23) 33 | #Output - 1 34 | print(loc) 35 | 36 | '''Great Video on Binary search- https://www.youtube.com/watch?v=KXJSjte_OAI''' 37 | -------------------------------------------------------------------------------- /Graph/C++/DetectCycleInADirectedGraph.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | 5 | /* Function to check if the given graph contains cycle 6 | * V: number of vertices 7 | * adj[]: representation of graph 8 | */ 9 | bool check_cycle(vector g[],int *visit,int *cycle,int k){ 10 | cycle[k] = 1; 11 | visit[k] = 1; 12 | 13 | for(auto i = g[k].begin();i!=g[k].end();i++){ 14 | if(cycle[*i] == 1){ 15 | return true; 16 | } 17 | 18 | else if(cycle[*i] == 0) 19 | if(visit[*i] != 0 && check_cycle(g,visit,cycle,*i))return true; 20 | 21 | } 22 | cycle[k] = 0; 23 | return false; 24 | } 25 | 26 | 27 | bool isCyclic(int V, vector adj[]) 28 | { 29 | int visited[V] = {0}; 30 | int cycleCheck[V] = {0}; 31 | for(int i=0;i> t; 48 | 49 | while(t--){ 50 | 51 | int v, e; 52 | cin >> v >> e; 53 | 54 | vector adj[v]; 55 | 56 | for(int i =0;i> u >> v; 59 | adj[u].push_back(v); 60 | } 61 | 62 | cout << isCyclic(v, adj) << endl; 63 | 64 | } 65 | 66 | return 0; 67 | } -------------------------------------------------------------------------------- /Graph/C++/DFS_traversal.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | 5 | 6 | 7 | /* Function to do DFS of graph 8 | 9 | g : adjacency list of graph 10 | N : number of vertices 11 | 12 | return a list containing the DFS traversal of the given graph 13 | */ 14 | 15 | 16 | 17 | void rec_dfs(vector g[],vector &result,int k,int *visit){ 18 | 19 | result.push_back(k); 20 | visit[k] = 1; 21 | 22 | for(i:g[k]){ 23 | if(visit[i] == 0){ 24 | rec_dfs(g,result,i,visit); 25 | } 26 | } 27 | 28 | 29 | return; 30 | } 31 | 32 | 33 | vector dfs(vector g[], int N) 34 | { 35 | vector result; 36 | 37 | int visit[N] = {0}; 38 | 39 | rec_dfs(g,result,0,visit); 40 | 41 | 42 | 43 | return result; 44 | 45 | } 46 | 47 | 48 | 49 | int main() 50 | { 51 | int T; 52 | cin>>T; 53 | while(T--) 54 | { 55 | 56 | int N, E; 57 | cin>>N>>E; 58 | 59 | vector g[N]; 60 | bool vis[N]; 61 | 62 | memset(vis, false, sizeof(vis)); 63 | 64 | for(int i=0;i>u>>v; 68 | g[u].push_back(v); 69 | g[v].push_back(u); 70 | } 71 | 72 | vector res = dfs(g, N); 73 | for (int i = 0; i < res.size (); i++) 74 | cout << res[i] << " "; 75 | cout< arr[j]) 18 | { 19 | //swap elements 20 | temp = arr[j-1]; 21 | arr[j-1] = arr[j]; 22 | arr[j] = temp; 23 | } 24 | 25 | } 26 | } 27 | } 28 | 29 | public static void main(String[] args)throws IOException 30 | { 31 | InputStreamReader read = new InputStreamReader(System.in); 32 | BufferedReader in = new BufferedReader(read); 33 | Scanner sc = new Scanner(System.in); 34 | 35 | System.out.print("Length of Array: "); 36 | int n = sc.nextInt(); 37 | 38 | int arr[] = new int[n]; 39 | System.out.println("Enter elements: "); 40 | for(int i=0;i 2 | #include 3 | 4 | using namespace std; 5 | 6 | //function to dispay stack 7 | void dispStack(stack st){ 8 | //declare temp. statck 9 | stack s = st; 10 | while(!s.empty()){ 11 | cout< st; 22 | 23 | //insert elements 24 | st.push(10); 25 | st.push(20); 26 | st.push(30); 27 | st.push(40); 28 | st.push(50); 29 | 30 | //display stack coun, top element and stack elements 31 | cout<<"Total stack elements are: "< arr[j+1] : 24 | arr[j], arr[j+1] = arr[j+1], arr[j] 25 | 26 | 27 | arr = [64,23,56,21,10,15] 28 | print("Given Array is: ",arr) 29 | bubbleSort(arr) 30 | print ("Sorted array is:") 31 | for i in range(len(arr)): 32 | print (arr[i]) 33 | 34 | 35 | ''' 36 | OUTPUT : 37 | //*****BUBBLE SORT*****// 38 | Given Array is: [64, 23, 56, 21, 10, 15] 39 | Sorted array is: 40 | 10 41 | 15 42 | 21 43 | 23 44 | 56 45 | 64 46 | ''' 47 | 48 | ''' 49 | Time Complexity : 50 | 1.Worst and Average Case Time Complexity: O(n*n) Worst case occurs when array 51 | is reverse sorted. 52 | 53 | 2.Best Case Time Complexity: O(n) Best case occurs when array is already sorted 54 | ''' -------------------------------------------------------------------------------- /Stack.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | #include 4 | #include 5 | 6 | #define MAX_SIZE 5 7 | 8 | using namespace std; 9 | 10 | int main() { 11 | int item, choice, i; 12 | int arr_stack[MAX_SIZE]; 13 | int top = 0; 14 | int exit = 1; 15 | 16 | cout << "\nSimple Stack Example - Array - C++"; 17 | do { 18 | cout << "\n\nnStack Main Menu"; 19 | 20 | cout << "\n1.Push \n2.Pop \n3.Display \nOthers to exit"; 21 | cout << "\nEnter Your Choice : "; 22 | cin>>choice; 23 | switch (choice) { 24 | case 1: 25 | if (top == MAX_SIZE) 26 | cout << "\n## Stack is Full!"; 27 | else { 28 | cout << "\nEnter The Value to be pushed : "; 29 | cin>>item; 30 | cout << "\n## Position : " << top << ", Pushed Value :" << item; 31 | arr_stack[top++] = item; 32 | } 33 | break; 34 | case 2: 35 | if (top == 0) 36 | cout << "\n## Stack is Empty!"; 37 | else { 38 | --top; 39 | cout << "\n## Position : " << top << ", Popped Value :" << arr_stack[top]; 40 | } 41 | break; 42 | case 3: 43 | cout << "\n## Stack Size : " << top; 44 | for (i = (top - 1); i >= 0; i--) 45 | cout << "\n## Position : " << i << ", Value :" << arr_stack[i]; 46 | break; 47 | default: 48 | exit = 0; 49 | break; 50 | } 51 | } while (exit); 52 | 53 | return 0; 54 | } -------------------------------------------------------------------------------- /Queue/C++/queue_using_array.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int queue[100], n = 100, front = - 1, rear = - 1; 5 | 6 | // checking overflow condition and insert operation 7 | void Insert() { 8 | int val; 9 | if (rear == n - 1) 10 | cout<<"Queue Overflow"<>val; 16 | rear++; 17 | queue[rear] = val; 18 | } 19 | } 20 | 21 | // checking underflow condition and delete operation 22 | void Delete() { 23 | if (front == - 1 || front > rear) { 24 | cout<<"Queue Underflow "; 25 | return ; 26 | } else { 27 | cout<<"Element deleted from queue is : "<< queue[front] <>ch; 54 | switch (ch) { 55 | case 1: Insert(); 56 | break; 57 | case 2: Delete(); 58 | break; 59 | case 3: Display(); 60 | break; 61 | case 4: cout<<"Exit"< 2 | using namespace std; 3 | 4 | //*** to intialize a node ***// 5 | struct Node { 6 | int data; 7 | Node* left; 8 | Node* right; 9 | }; 10 | 11 | 12 | //*** to create a new node ***// 13 | Node* newNode(int key) 14 | { 15 | Node* temp=new Node(); 16 | temp->data=key; 17 | temp->left=temp->right=NULL; 18 | } 19 | 20 | //*** function to print inorderBST ***// 21 | void printInorder(Node* node) 22 | { 23 | if (node == NULL) 24 | return; 25 | 26 | printInorder(node->left); 27 | 28 | cout<data<<" "; 29 | 30 | printInorder(node->right); 31 | 32 | } 33 | 34 | //*** function to insert a numer non-recursively ***// 35 | Node* insert(Node* root, int data) 36 | { 37 | Node* value=newNode(data); 38 | 39 | Node *temp_parent=NULL, *temp=root; 40 | 41 | while(temp!=NULL) 42 | { 43 | temp_parent=temp; 44 | if(temp->data > data) //iterating loop untill we reach at a leaf node of tree 45 | temp=temp->left; 46 | else 47 | temp=temp->right; 48 | 49 | } 50 | if (temp_parent==NULL) 51 | temp_parent=value; 52 | else if(temp_parent->data >data) 53 | temp_parent->left= value; 54 | else 55 | temp_parent->right= value; 56 | 57 | return temp_parent; 58 | 59 | } 60 | 61 | int main() 62 | { 63 | int n,i; 64 | cout<<"Enter number of nodes:- "; 65 | cin>>n; 66 | cout<>a[i]; 72 | 73 | 74 | cout< 2 | #include 3 | 4 | struct Box 5 | { 6 | int h, w, d; 7 | }; 8 | 9 | int min (int x, int y) 10 | { return (x < y)? x : y; } 11 | 12 | int max (int x, int y) 13 | { return (x > y)? x : y; } 14 | 15 | int compare (const void *a, const void * b) 16 | { 17 | return ( (*(Box *)b).d * (*(Box *)b).w ) - 18 | ( (*(Box *)a).d * (*(Box *)a).w ); 19 | } 20 | 21 | int maxStackHeight( Box arr[], int n ) 22 | { 23 | Box rot[3*n]; 24 | int index = 0; 25 | for (int i = 0; i < n; i++) 26 | { 27 | rot[index].h = arr[i].h; 28 | rot[index].d = max(arr[i].d, arr[i].w); 29 | rot[index].w = min(arr[i].d, arr[i].w); 30 | index++; 31 | 32 | rot[index].h = arr[i].w; 33 | rot[index].d = max(arr[i].h, arr[i].d); 34 | rot[index].w = min(arr[i].h, arr[i].d); 35 | index++; 36 | 37 | rot[index].h = arr[i].d; 38 | rot[index].d = max(arr[i].h, arr[i].w); 39 | rot[index].w = min(arr[i].h, arr[i].w); 40 | index++; 41 | } 42 | 43 | n = 3*n; 44 | 45 | qsort (rot, n, sizeof(rot[0]), compare); 46 | 47 | int msh[n]; 48 | for (int i = 0; i < n; i++ ) 49 | msh[i] = rot[i].h; 50 | 51 | for (int i = 1; i < n; i++ ) 52 | for (int j = 0; j < i; j++ ) 53 | if ( rot[i].w < rot[j].w && 54 | rot[i].d < rot[j].d && 55 | msh[i] < msh[j] + rot[i].h 56 | ) 57 | { 58 | msh[i] = msh[j] + rot[i].h; 59 | } 60 | 61 | 62 | int max = -1; 63 | for ( int i = 0; i < n; i++ ) 64 | if ( max < msh[i] ) 65 | max = msh[i]; 66 | 67 | return max; 68 | } 69 | 70 | int main() 71 | { 72 | Box arr[] = { {4, 6, 7}, {1, 2, 3}, {4, 5, 6}, {10, 12, 32} }; 73 | int n = sizeof(arr)/sizeof(arr[0]); 74 | 75 | printf("The maximum possible height of stack is %d\n", 76 | maxStackHeight (arr, n) ); 77 | 78 | return 0; 79 | } 80 | -------------------------------------------------------------------------------- /Linked Lists/linkedlistSearch.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | int pass = 0; 3 | 4 | using namespace std; 5 | 6 | class Node{ 7 | public: 8 | int data; 9 | Node *next; 10 | }; 11 | 12 | Node* swapping(Node* p1, Node* p2){ 13 | int temp = p1->data; 14 | p1->data = p2->data; 15 | p2->data = temp; 16 | } 17 | 18 | Node* display(Node* head, int n){ 19 | for(int i=0;idata<<" "; 21 | head = head->next; 22 | 23 | } 24 | } 25 | 26 | void sort(Node *head, int n){ 27 | int swaps = 0; 28 | Node *ptr1 = head; 29 | Node *ptr2 = ptr1->next; 30 | 31 | for(int i = 0;idata > ptr2->data) { 34 | swapping(ptr1, ptr2); 35 | swaps = 1; 36 | 37 | } 38 | ptr1 = ptr1->next; 39 | ptr2 = ptr2->next; 40 | 41 | } 42 | ptr1 = head; 43 | ptr2 = ptr1->next; 44 | if(!swaps) 45 | break; 46 | pass = pass+1; 47 | } 48 | } 49 | 50 | Node* insert(Node *head, int n){ 51 | Node *ptr = head; 52 | for(int i = 0;i>ptr->data; 55 | if(i==n-1){ 56 | break; 57 | } 58 | ptr->next = new Node(); 59 | ptr = ptr->next; 60 | } 61 | ptr->next = NULL; 62 | 63 | } 64 | int main(){ 65 | int n, val; 66 | Node* head = NULL; 67 | head = new Node(); 68 | cout<<"Enter the no of elements: "; 69 | cin>>n; 70 | insert(head, n); 71 | cout<<"Linkedlist before sorting : "; 72 | display(head, n); 73 | 74 | cout<<"\nLinkedlist after sorting : "; 75 | sort(head, n); 76 | display(head, n); 77 | cout<<"\nNo. of passes : "< 20 | 21 | using namespace std; 22 | 23 | 24 | bool dfs(int u, std::vector > &adj, std::vector& visited, int parent){ 25 | 26 | visited[u] =true; 27 | 28 | for(int v : adj[u]){ 29 | 30 | if(!visited[v]){ 31 | if(dfs(v, adj, visited, u)) 32 | return true; 33 | } 34 | else if(v!=parent) return true; 35 | } 36 | return false; 37 | } 38 | 39 | 40 | int main() 41 | { 42 | int A; // number of edges 43 | vector> B; //edges 44 | 45 | cin>>A; 46 | for (int i =0; i x(2); 48 | cin>>x[0]; 49 | cin>>x[1]; 50 | B.push_back(x); 51 | } 52 | 53 | vector> adj(A); //adjacency list 54 | 55 | for(int i=0; i visited(A,false); 65 | 66 | for(int i=0; i 2 | #define ll long long 3 | using namespace std; 4 | 5 | 6 | // There are n cities and m roads between them. 7 | // Your task is to process q queries where you have to determine 8 | // the length of the shortest route between two given cities. 9 | 10 | 11 | // 1≤n≤500 12 | // 1≤m≤n^2 13 | // 1≤q≤10^5 14 | // 1≤a,b≤n 15 | // 1≤c≤10^9 16 | 17 | ''' 18 | Input: 19 | 4 3 5 20 | 1 2 5 21 | 1 3 9 22 | 2 3 3 23 | 1 2 24 | 2 1 25 | 1 3 26 | 1 4 27 | 3 2 28 | 29 | Output: 30 | 5 31 | 5 32 | 8 33 | -1 34 | 3 35 | 36 | ''' 37 | 38 | const ll int INF = LONG_MAX; 39 | 40 | int main(){ 41 | 42 | // n, m and q: the number of cities, roads, and queries. 43 | 44 | int n,m,q; 45 | 46 | cin>>n>>m>>q; 47 | 48 | // Let d be the matrix of distances, i.e., d[u][v] tells us the distance between u and v 49 | 50 | vector> d(n, vector(n,INF)); 51 | 52 | for(int i=0; i>u>>v>>c; 56 | d[u-1][v-1] = min(d[u-1][v-1],c); 57 | d[v-1][u-1] = min(d[v-1][u-1],c); 58 | } 59 | 60 | 61 | for(int i=0; i> vp; 80 | for(int i=0; i>u>>v; 83 | vp.push_back({u,v}); 84 | 85 | } 86 | 87 | for(auto e : vp){ 88 | int u = e.first; 89 | int v = e.second; 90 | if(d[u-1][v-1]!=INF) cout< 2 | using namespace std; 3 | 4 | typedef struct Node{ 5 | int data; 6 | struct Node*next; 7 | }Node; 8 | 9 | Node* insert(Node*head ,int x ) //function to insert node in ll 10 | { 11 | //New node to be inserted 12 | Node * p = new Node; 13 | p->data = x; 14 | p->next = NULL; 15 | //if it's first node 16 | if(head == NULL) 17 | { 18 | head = p; 19 | } 20 | 21 | //if head node is there 22 | 23 | else{ 24 | Node*temp = head; 25 | while(temp->next!=NULL) 26 | { 27 | temp=temp->next; 28 | } 29 | temp->next = p; 30 | } 31 | return head; 32 | } 33 | 34 | Node* reverse(Node*head) //function to reverse 35 | { 36 | // Initialize current, previous and 37 | // next pointers 38 | Node* current = head; 39 | Node *prev = NULL, *next = NULL; 40 | 41 | while (current != NULL) { 42 | // Store next 43 | next = current->next; 44 | 45 | // Reverse current node's pointer 46 | current->next = prev; 47 | 48 | // Move pointers one position ahead. 49 | prev = current; 50 | current = next; 51 | } 52 | head = prev; 53 | return head; 54 | } 55 | 56 | void print(Node*head) 57 | { 58 | Node*temp = head; 59 | while(temp!=NULL) 60 | { 61 | cout<data<<" "; 62 | temp=temp->next; 63 | } 64 | 65 | } 66 | 67 | int main() 68 | { 69 | 70 | Node * head = NULL; //initilaise head to NULL 71 | head = insert(head,1); 72 | head = insert(head,2); 73 | head = insert(head,3); 74 | print(head); 75 | head = reverse(head); //reverse linked list 76 | print(head); 77 | 78 | return 0; 79 | 80 | } 81 | 82 | // Time Complexity: O(n) 83 | 84 | -------------------------------------------------------------------------------- /Tree/C++/rightleaf.cpp: -------------------------------------------------------------------------------- 1 | // { Driver Code Starts 2 | #include 3 | using namespace std; 4 | 5 | struct Node 6 | { 7 | int data; 8 | struct Node *left; 9 | struct Node *right; 10 | 11 | Node(int x){ 12 | data = x; 13 | left = NULL; 14 | right = NULL; 15 | } 16 | }; 17 | 18 | void inorder(Node *root) 19 | { 20 | if (root == NULL)return; 21 | inorder(root->left); 22 | cout << root->data << " "; 23 | inorder(root->right); 24 | } 25 | 26 | int rightLeafSum(Node* root); 27 | 28 | /* Driver program to test size function*/ 29 | int main() 30 | { 31 | int t; 32 | scanf("%d", &t); 33 | while (t--) 34 | { 35 | map m; 36 | int n; 37 | scanf("%d",&n); 38 | struct Node *root = NULL; 39 | struct Node *child; 40 | while (n--) 41 | { 42 | Node *parent; 43 | char lr; 44 | int n1, n2; 45 | scanf("%d %d %c", &n1, &n2, &lr); 46 | if (m.find(n1) == m.end()) 47 | { 48 | parent = new Node(n1); 49 | m[n1] = parent; 50 | if (root == NULL) 51 | root = parent; 52 | } 53 | else 54 | parent = m[n1]; 55 | child = new Node(n2); 56 | if (lr == 'L') 57 | parent->left = child; 58 | else 59 | parent->right = child; 60 | m[n2] = child; 61 | } 62 | // inorder(root); 63 | // cout<right && !root->right->left && !root->right->right) 86 | return root->right->data + rightLeafSum(root->left); 87 | 88 | 89 | return rightLeafSum(root->left) + rightLeafSum(root->right); 90 | } 91 | -------------------------------------------------------------------------------- /LinkedList/Java/IntersectionOfTwoLinkedLists.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode(int x) { 7 | * val = x; 8 | * next = null; 9 | * } 10 | * } 11 | */ 12 | public class Solution { 13 | public ListNode getIntersectionNode(ListNode headA, ListNode headB) { 14 | int l1 = 0; 15 | int l2 = 0; 16 | ListNode cur = headA; 17 | 18 | ListNode res = null; 19 | while(cur!=null){ 20 | cur = cur.next; 21 | l1++; 22 | } 23 | cur = headB; 24 | while(cur!=null){ 25 | cur = cur.next; 26 | l2++; 27 | } 28 | if(l1 == l2){ 29 | if(headA == headB){ 30 | return headA; 31 | } 32 | } 33 | int maxLimit = 0; 34 | if(l1 > l2){ 35 | maxLimit = l1 - l2; 36 | cur = headA; 37 | ListNode curB = headB; 38 | for(int i = 0;i 27 | 28 | using namespace std; 29 | 30 | const long long INF = 1e9; 31 | 32 | // creating a new struct edge 33 | 34 | struct edge{ 35 | int a,b,c; 36 | }; 37 | 38 | 39 | // bellman ford algorithm to detect negative cycle in a directed graph 40 | void bellman_ford(vector &edges, int n){ 41 | 42 | int m = edges.size(); 43 | 44 | vector p(n, -1); 45 | vector d(n,INF); 46 | 47 | d[0] = 0; 48 | int x; 49 | for(int i=0; i d[edges[j].a] + edges[j].c){ 54 | d[edges[j].b] = max(-INF ,d[edges[j].a] + edges[j].c); 55 | p[edges[j].b] = edges[j].a; 56 | x = edges[j].b; 57 | } 58 | 59 | } 60 | } 61 | 62 | // Time Complexity - O(nm) 63 | // Space Complexity - O(m + n) 64 | 65 | if (x==-1){ 66 | cout<<"NO"< cycle; 75 | 76 | int v = x; 77 | while(!(v==x && cycle.size()>1)){ 78 | cycle.push_back(v); 79 | v = p[v]; 80 | } 81 | 82 | reverse(cycle.begin(), cycle.end()); 83 | 84 | cout<<"YES"<>n>>m; 103 | vector edges; 104 | for(int i=0; i>u>>v>>c; 107 | edge a = {u-1,v-1,c}; 108 | edges.push_back(a); 109 | 110 | } 111 | 112 | bellman_ford(edges, n); 113 | 114 | } -------------------------------------------------------------------------------- /Searching and Sorting/Python/merge_sort.py: -------------------------------------------------------------------------------- 1 | ''' Merge Sort is a Divide and Conquer algorithm. It divides input 2 | array in two halves, calls itself for the two halves and then merges the 3 | two sorted halves.The merge() function is used for merging two halves. 4 | The merge(arr, l, m, r) is key process that assumes that arr[l..m] and 5 | arr[m+1..r] are sorted and merges the two sorted sub-arrays into one''' 6 | 7 | '''////ALGORITHM//// 8 | 9 | #MergeSort(arr[], l, r) 10 | If r > l 11 | 1. Find the middle point to divide the array into two halves: 12 | middle m = (l+r)/2 13 | 2. Call mergeSort for first half: 14 | Call mergeSort(arr, l, m) 15 | 3. Call mergeSort for second half: 16 | Call mergeSort(arr, m+1, r) 17 | 4. Merge the two halves sorted in step 2 and 3: 18 | Call merge(arr, l, m, r)''' 19 | 20 | 21 | '''Python program for implementation of MergeSort''' 22 | 23 | 24 | def mergeSort(arr): 25 | if len(arr) > 1: 26 | mid = len(arr) // 2 # Finding the mid of the array 27 | left = arr[:mid] # Dividing the array elements 28 | right = arr[mid:] # into 2 halves 29 | 30 | mergeSort(left) # Sorting the first half 31 | mergeSort(right) # Sorting the second half 32 | 33 | i = j = k = 0 34 | 35 | while i < len(left) and j < len(right): 36 | if left[i] < right[j]: 37 | arr[k] = left[i] 38 | i += 1 39 | else: 40 | arr[k] = right[j] 41 | j += 1 42 | k += 1 43 | 44 | # Checking if any element was left 45 | while i < len(left): 46 | arr[k] = left[i] 47 | i += 1 48 | k += 1 49 | 50 | while j < len(right): 51 | arr[k] = right[j] 52 | j += 1 53 | k += 1 54 | 55 | 56 | # printing the list 57 | def printList(arr): 58 | for i in range(len(arr)): 59 | print(arr[i], end=" ") 60 | print() 61 | 62 | 63 | arr = [12, 11, 13, 5, 6, 7] 64 | print("Given array is: ") 65 | printList(arr) 66 | mergeSort(arr) 67 | print("Sorted array is: ") 68 | printList(arr) 69 | 70 | 71 | -------------------------------------------------------------------------------- /QUEUE_Hctober.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #define SIZE 5 3 | 4 | using namespace std; 5 | 6 | class Queue { 7 | private: 8 | int items[SIZE], front, rear; 9 | 10 | public: 11 | Queue() { 12 | front = -1; 13 | rear = -1; 14 | } 15 | 16 | bool isFull() { 17 | if (front == 0 && rear == SIZE - 1) { 18 | return true; 19 | } 20 | return false; 21 | } 22 | 23 | bool isEmpty() { 24 | if (front == -1) 25 | return true; 26 | else 27 | return false; 28 | } 29 | 30 | void enQueue(int element) { 31 | if (isFull()) { 32 | cout << "Queue is full"; 33 | } else { 34 | if (front == -1) front = 0; 35 | rear++; 36 | items[rear] = element; 37 | cout << endl 38 | << "Inserted " << element << endl; 39 | } 40 | } 41 | 42 | int deQueue() { 43 | int element; 44 | if (isEmpty()) { 45 | cout << "Queue is empty" << endl; 46 | return (-1); 47 | } else { 48 | element = items[front]; 49 | if (front >= rear) { 50 | front = -1; 51 | rear = -1; 52 | } 53 | else { 54 | front++; 55 | } 56 | cout << endl 57 | << "Deleted -> " << element << endl; 58 | return (element); 59 | } 60 | } 61 | 62 | void display() { 63 | 64 | int i; 65 | if (isEmpty()) { 66 | cout << endl 67 | << "Empty Queue" << endl; 68 | } else { 69 | cout << endl 70 | << "Front index-> " << front; 71 | cout << endl 72 | << "Items -> "; 73 | for (i = front; i <= rear; i++) 74 | cout << items[i] << " "; 75 | cout << endl 76 | << "Rear index-> " << rear << endl; 77 | } 78 | } 79 | }; 80 | 81 | int main() { 82 | Queue q; 83 | 84 | 85 | q.deQueue(); 86 | 87 | 88 | q.enQueue(1); 89 | q.enQueue(2); 90 | q.enQueue(3); 91 | q.enQueue(4); 92 | q.enQueue(5); 93 | 94 | 95 | q.enQueue(6); 96 | 97 | q.display(); 98 | 99 | 100 | q.deQueue(); 101 | 102 | 103 | q.display(); 104 | 105 | return 0; 106 | } -------------------------------------------------------------------------------- /Strings/C++/README.md: -------------------------------------------------------------------------------- 1 | # Strings 2 | 3 | ## Definition: String is a sequence of characters which is represented within double Quotes. 4 | 5 | ## String Library 6 | **cstring library** provides functions for string operations. 7 | 8 | 1. **strxfrm()**- Transforms a given null terminated byte string into an implementation defined form. 9 | 2. **strcoll()**- Compares two null terminating string. 10 | 3. **strlen()**- returns the length of the given string. 11 | 4. **strerror()**- returns the textual description of the system error code. 12 | 5. **memset()**- copies a single character for a specified number of time to an object. 13 | 6. **strtok()**- returns the next token in a null terminated byte string. 14 | 7. **strstr()**- finds the first occurrence of a substring in a string. 15 | 8. **strspn()**- takes two string dest and src and gives the length of maximum initial segment of the string dest that consists of characters that are present in the string src. 16 | 9. **strrchr()**- searches for the last occurrence of a character in a string. 17 | 10. **strpbrk()**- searches for a set of characters present in a string in another string. 18 | 11. **strcspn()**- takes two null terminated byte string: dest and src as its argument and searches dest for any characters that is present in src. 19 | 12. **strchr()**- searches for the first occurrence of a character in a string. 20 | 13. **memchr()**- searches for the first occurrence of a character in a specified number of characters. 21 | 14. **strncmp()**- compares a specified number of characters of two null terminating strings. The comparison is done lexicographically. 22 | 15. **strcmp()**- compares two null terminating string. 23 | 16. **memcmp()**- compares a specified number of characters of two pointer objects 24 | 17. **strncat()**- appends a specified number of characters of a string to the end of another string. 25 | 18. **strcat()**- appends a copy of a string to the end of another string. 26 | 19. **strncpy()**- copies a specified bytes of characters from source to destination. 27 | 20. **strcpy()**- copies a character string from source to destination. 28 | 21. **memmove()**- specified bytes of data from source to the destination. 29 | 22. **memcpy()**- copies a specified bytes of data from source to the destination. 30 | -------------------------------------------------------------------------------- /Queue/C++/queue_using_linkedlist.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | 5 | struct node { 6 | int data; 7 | struct node *next; 8 | }; 9 | 10 | struct node* front = NULL; 11 | struct node* rear = NULL; 12 | struct node* temp; 13 | 14 | // Insert code 15 | void Insert() { 16 | int val; 17 | cout<<"Insert the element in queue : "<>val; 19 | if (rear == NULL) { 20 | rear = (struct node *)malloc(sizeof(struct node)); 21 | rear->next = NULL; 22 | rear->data = val; 23 | front = rear; 24 | } else { 25 | temp=(struct node *)malloc(sizeof(struct node)); 26 | rear->next = temp; 27 | temp->data = val; 28 | temp->next = NULL; 29 | rear = temp; 30 | } 31 | } 32 | 33 | // Delete code 34 | void Delete() { 35 | temp = front; 36 | if (front == NULL) { 37 | cout<<"Underflow"<next != NULL) { 42 | temp = temp->next; 43 | cout<<"Element deleted from queue is : "<data<data<data<<" "; 64 | temp = temp->next; 65 | } 66 | cout<>ch; 79 | switch (ch) { 80 | case 1: Insert(); 81 | break; 82 | case 2: Delete(); 83 | break; 84 | case 3: Display(); 85 | break; 86 | case 4: cout<<"Exit"< //Header file 6 | using namespace std; //For cin and cout 7 | int main(){ 8 | int n, arr[n], num, temp; //Declarartion of required variables 9 | cout<<"Enter the number of elements of the array: "; 10 | cin>>n; //Getting the number of elements of the array from the user 11 | cout<>num; 14 | arr[i] = num; 15 | } 16 | for (int i = 0; i < n-1; i++){ //Outer for loop 17 | bool sorted = true; // declaring a sorted variable which will check if array is already sorted or not 18 | for(int j = 0; j < n-1-i; j++){ //Inner for loop 19 | if(arr[j] > arr[j+1]){ //Checking if the element if larger than the next element 20 | temp = arr[j+1]; //Swapping the elements, temp is used to store the temporary variable 21 | arr[j+1] = arr[j]; 22 | arr[j] = temp; 23 | sorted = false; // sorted value will be updated to false if there is swapping of elements occured 24 | } 25 | } 26 | if(sorted){ // If the elements aren't swapped and sorted is true only then array is already sorted 27 | break; 28 | } 29 | } 30 | cout<<"Array after sorting is:"< 8 | using namespace std; 9 | /* Convert the Given array of elements into Max Heap where "i"th element is parent, 10 | "2*i"th element is left child and "2*(i+1)" is right child in array representation */ 11 | void CreateMaxHeap(int A[],int n) 12 | { 13 | int temp=A[n],i=n; 14 | while(i>1 && temp > A[i/2]) 15 | { 16 | A[i]=A[i/2]; 17 | i=i/2; 18 | } 19 | A[i]=temp; 20 | } 21 | 22 | void DisplayHeap(int A[],int size) // Display the Sorted elements in heap after deletion 23 | { 24 | for(int i=1;i<=size;i++) 25 | { 26 | cout << A[i] << " "; 27 | } 28 | cout < A[j]) //Inorder to maintain Max heap,Elements in array is arranged 43 | { 44 | j=j+1; 45 | } 46 | if(A[j] > A[i]) 47 | { 48 | tmp=A[i]; 49 | A[i]=A[j]; 50 | A[j]=tmp; 51 | i=j; 52 | j=2*i; 53 | } 54 | else 55 | { 56 | break; 57 | } 58 | 59 | } 60 | } 61 | 62 | int main() 63 | { 64 | int A[8]={0,30,25,40,10,50,20,5}; 65 | for(int i=2;i<=7;i++) 66 | { 67 | CreateMaxHeap(A,i); //Max Heap is created 68 | } 69 | cout << "After performing Heap sort via deletion:" << endl; 70 | for(int i=7;i>=1;i--) 71 | { 72 | DeleteHeap(A,i); 73 | } 74 | DisplayHeap(A,7); // Display Sorted elements in increasing order 75 | return 0; 76 | } 77 | -------------------------------------------------------------------------------- /Searching and Sorting/C++/mergesort.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Merge sort is an efficient, general-purpose, comparison-based sorting algorithm. 3 | It is a divide and conquer algorithm that was invented by John von Neumann in 1945. 4 | 5 | */ 6 | 7 | #include //Header file 8 | using namespace std; //For cin and cout 9 | 10 | 11 | //Implement merge function 12 | void merge( int a[], int start, int end){ 13 | 14 | int temp[10000]; //Temprory array to store while merging the arrays 15 | int mid= ( start + end ) / 2; 16 | 17 | int i= start, j= mid+1, k= start; 18 | 19 | //Compare and fill temp 20 | while( i<= mid && j<= end ){ 21 | 22 | if(a[i]= end ){ 53 | return; 54 | } 55 | 56 | //Find the mid index 57 | int mid= ( start + end ) / 2; 58 | 59 | //Recursively sort the array in two halves 60 | //Sort first half 61 | mergeSort( a, start, mid); 62 | //Sort second half 63 | mergeSort( a, mid + 1, end); 64 | 65 | //Merge the sorted halves 66 | merge( a, start, end); 67 | 68 | return; 69 | 70 | } 71 | 72 | 73 | int main(){ 74 | 75 | int n; 76 | cout<<"Enter the number of elements of the array to be sorted: "; 77 | cin>>n; 78 | 79 | int a[n]; 80 | cout<<"Enter the elements of the array: "; 81 | 82 | for(int i= 0; i>a[i]; 84 | } 85 | 86 | //Call the merge sort function on the array - mergeSort( array_name, start, end); 87 | mergeSort( a, 0, n-1 ); 88 | 89 | //Print the sorted array 90 | for(int i= 0; i< n; i++){ 91 | cout< 2 | #include 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | // node declaration 8 | struct n { 9 | int p; 10 | int info; 11 | struct n *l; 12 | }; 13 | class Priority_Queue { 14 | private: 15 | //Declare a front pointer f and initialize it to NULL. 16 | n *f; 17 | public: 18 | Priority_Queue() { //constructor 19 | f = NULL; 20 | } 21 | void insert(int i, int p) { 22 | n *t, *q; 23 | t = new n; 24 | t->info = i; 25 | t->p = p; 26 | if (f == NULL || p < f->p) { 27 | t->l= f; 28 | f = t; 29 | } else { 30 | q = f; 31 | while (q->l != NULL && q->l->p <= p) 32 | q = q->l; 33 | t->l = q->l; 34 | q->l = t; 35 | } 36 | } 37 | 38 | void del() { 39 | n *t; 40 | if(f == NULL) 41 | cout<<"Queue Underflow\n"; 42 | else { 43 | t = f; 44 | cout<<"Deleted item is: "<info<l; 46 | free(t); 47 | } 48 | } 49 | 50 | void show() { //display queue 51 | n *ptr; 52 | ptr = f; 53 | if (f == NULL) 54 | cout<<"Queue is empty\n"; 55 | else { 56 | cout<<"Queue is :\n"; 57 | cout<<"Priority Item\n"; 58 | while(ptr != NULL) { 59 | cout<p<<" "<info<l; 61 | } 62 | } 63 | } 64 | }; 65 | 66 | // driver code 67 | int main() { 68 | int c, i, p; 69 | Priority_Queue pq; 70 | do { 71 | cout<<"1.Insert\n"; 72 | cout<<"2.Delete\n"; 73 | cout<<"3.Display\n"; 74 | cout<<"4.Exit\n"; 75 | cout<<"Enter your choice : "; 76 | cin>>c; 77 | switch(c) { 78 | case 1: 79 | cout<<"Input the item value to be added in the queue : "; 80 | cin>>i; 81 | cout<<"Enter its priority : "; 82 | cin>>p; 83 | pq.insert(i, p); 84 | break; 85 | case 2: 86 | pq.del(); 87 | break; 88 | case 3: 89 | pq.show(); 90 | break; 91 | case 4: 92 | break; 93 | default: 94 | cout<<"Wrong choice\n"; 95 | } 96 | } 97 | while(c != 4); 98 | return 0; 99 | } -------------------------------------------------------------------------------- /Searching and Sorting/C++/quicksort.cpp: -------------------------------------------------------------------------------- 1 | #include //Header file 2 | using namespace std; //For cin and cout 3 | 4 | /* 5 | Quicksort is a divide-and-conquer algorithm. It works by selecting a 'pivot' element from the array 6 | and partitioning the other elements into two sub-arrays, according to whether they are less than or greater than the pivot. 7 | The sub-arrays are then sorted recursively. This can be done in-place, requiring small additional amounts of memory to perform the sorting. 8 | 9 | */ 10 | 11 | //Implement partitionPivot function 12 | int partitionPivot( int a[], int start, int end ){ 13 | 14 | int i= start-1; 15 | int j= start; 16 | int pivot= a[end]; 17 | 18 | //Traverse the array - whenever an element smaller than pivot occurs, swap it with (i+1)th element 19 | for(j= start; j<= end-1; j++){ 20 | 21 | if(a[j] <= pivot){ 22 | i++; 23 | swap(a[i],a[j]); 24 | } 25 | } 26 | 27 | //Place the pivot element at i+1 (between smaller and larger elements) 28 | swap(a[i+1],a[end]); 29 | 30 | //Return position of pivot 31 | return i+1; 32 | } 33 | 34 | //Implement Quick Sort function 35 | void quickSort( int a[], int start, int end ){ 36 | 37 | //base case 38 | //If start (index) crosses end (index), there are no elements to sort further, thus return 39 | if( start >= end ){ 40 | return; 41 | } 42 | 43 | //Taking end element as pivot, place the pivot element in its right position such that 44 | //elements left to the pivot are smaller than pivot and elements right to the pivot are greater than pivot 45 | //Return pivot's position (index) 46 | int p= partitionPivot( a, start, end ); 47 | 48 | //Recursively sort left and right part of the pivot element 49 | //Left part of the pivot 50 | quickSort( a, start, p-1 ); 51 | //Right part of the pivot 52 | quickSort( a, p+1, end); 53 | 54 | return; 55 | } 56 | 57 | int main(){ 58 | 59 | int n; 60 | cout<<"Enter the number of elements: "; 61 | cin>>n; 62 | 63 | int a[n]; 64 | cout<>a[i]; 68 | } 69 | 70 | //Call the quick sort function on the array - quickSort( array_name, start, end); 71 | quickSort( a, 0, n-1 ); 72 | 73 | //Print the sorted array 74 | cout< 18 | 19 | using namespace std; 20 | 21 | #define MAX 1000 22 | 23 | class Stack { 24 | int top; 25 | 26 | public: 27 | int a[MAX]; // Maximum size of Stack 28 | 29 | Stack() { top = -1; } 30 | bool push(int x); 31 | int pop(); 32 | int peek(); 33 | bool isEmpty(); 34 | }; 35 | 36 | bool Stack::push(int x) 37 | { 38 | if (top >= (MAX - 1)) { 39 | cout << "Stack Overflow"; 40 | return false; 41 | } 42 | else { 43 | a[++top] = x; 44 | cout << x << " pushed into stack\n"; 45 | return true; 46 | } 47 | } 48 | 49 | int Stack::pop() 50 | { 51 | if (top < 0) { 52 | cout << "Stack Underflow"; 53 | return 0; 54 | } 55 | else { 56 | int x = a[top--]; 57 | return x; 58 | } 59 | } 60 | int Stack::peek() 61 | { 62 | if (top < 0) { 63 | cout << "Stack is Empty"; 64 | return 0; 65 | } 66 | else { 67 | int x = a[top]; 68 | return x; 69 | } 70 | } 71 | 72 | bool Stack::isEmpty() 73 | { 74 | return (top < 0); 75 | } 76 | 77 | // Driver program to test above functions 78 | int main() 79 | { 80 | class Stack s; 81 | s.push(10); 82 | s.push(20); 83 | s.push(30); 84 | cout << s.pop() << " Popped from stack\n"; 85 | 86 | return 0; 87 | } 88 | 89 | 90 | 91 | 92 | /* 93 | Output : 94 | 95 | 10 pushed into stack 96 | 20 pushed into stack 97 | 30 pushed into stack 98 | 30 popped from stack 99 | */ 100 | 101 | 102 | 103 | /* 104 | Time Complexity: 105 | push(), pop(), isEmpty() and peek() all take O(1) time. 106 | We do not run any loop in any of these operations. 107 | */ -------------------------------------------------------------------------------- /Searching and Sorting/Python/Quick_sort.py: -------------------------------------------------------------------------------- 1 | #Quick sort is the widely used sorting algorithm that makes n log n comparisons in average case for sorting of an array of n elements. 2 | #This algorithm follows divide and conquer approach. The algorithm processes the array in the following way. 3 | #1. Set the first index of the array to left and loc variable. Set the last index of the array to right variable. i.e. left = 0, loc = 0, en d 4 | # = n - 1, where n is the length of the array. 5 | # 2. Start from the right of the array and scan the complete array from right to beginning comparing each element of the array with the element pointed by loc. 6 | # Ensure that, a[loc] is less than a[right] 7 | # 1.If this is the case, then continue with the comparison until right becomes equal to the loc. 8 | # 2.If a[loc] > a[right], then swap the two values. And go to step 3. 9 | # 3.Set, loc = right 10 | # 3.start from element pointed by left and compare each element in its way with the element pointed by the variable loc. Ensure that a[loc] > a[left] 11 | # 1.if this is the case, then continue with the comparison until loc becomes equal to left. 12 | # 2.[loc] < a[right], then swap the two values and go to step 2. 13 | # 3.Set, loc = left. 14 | 15 | # Python program for implementation of Quicksort Sort 16 | 17 | def partition(arr, low, high): 18 | i = (low - 1) # index of smaller element 19 | pivot = arr[high] # pivot 20 | 21 | for j in range(low, high): 22 | 23 | # If current element is smaller than or 24 | # equal to pivot 25 | if arr[j] <= pivot: 26 | # increment index of smaller element 27 | i = i + 1 28 | arr[i], arr[j] = arr[j], arr[i] 29 | 30 | arr[i + 1], arr[high] = arr[high], arr[i + 1] 31 | return (i + 1) 32 | 33 | 34 | # The main function that implements QuickSort 35 | # arr[] --> Array to be sorted, 36 | # low --> Starting index, 37 | # high --> Ending index 38 | 39 | # Function to do Quick sort 40 | 41 | 42 | def quickSort(arr, low, high): 43 | if len(arr) == 1: 44 | return arr 45 | if low < high: 46 | # pi is partitioning index, arr[p] is now 47 | # at right place 48 | pi = partition(arr, low, high) 49 | 50 | # Separately sort elements before 51 | # partition and after partition 52 | quickSort(arr, low, pi - 1) 53 | quickSort(arr, pi + 1, high) 54 | 55 | 56 | # Driver code to test above 57 | arr = [10, 7, 8, 9, 1, 5] 58 | n = len(arr) 59 | quickSort(arr, 0, n - 1) 60 | print("Sorted array is:") 61 | for i in range(n): 62 | print("%d" % arr[i]) 63 | 64 | #Time complexity : O(n log n) 65 | #space complexity : O(log n) -------------------------------------------------------------------------------- /Tree/C++/leafnodesum.cpp: -------------------------------------------------------------------------------- 1 | // { Driver Code Starts 2 | //Author- SAJAL AGRAWAL 3 | //sajal.agrawal1997@gmail.com 4 | 5 | #include 6 | #include 7 | #include 8 | 9 | struct Node 10 | { 11 | int data; 12 | struct Node *left; 13 | struct Node *right; 14 | 15 | Node(int x){ 16 | data = x; 17 | left = NULL; 18 | right = NULL; 19 | } 20 | }; 21 | 22 | Node *insert(Node *r,int num); 23 | int sumOfLeafNodes(Node *r); 24 | void preOrderDisplay(Node *r); 25 | void inOrderDisplay(Node *r); 26 | void postOrderDisplay(Node *r); 27 | int search(Node *r, int num); 28 | 29 | int main(void) { 30 | int t,n,data; 31 | scanf("%d",&t); 32 | while(t--){ 33 | Node *root=NULL; 34 | scanf("%d",&n); 35 | //printf("n=%d\n",n); 36 | while(n--){ 37 | scanf("%d",&data); 38 | //printf("data=%d\n",data); 39 | root=insert(root,data); 40 | } 41 | //inOrderDisplay(root); 42 | printf("%d\n",sumOfLeafNodes(root)); 43 | } 44 | return 0; 45 | } 46 | 47 | Node *insert(Node *r,int num){ 48 | if(r==NULL){ 49 | r = new Node(num); 50 | }else{ 51 | if(numdata){ 52 | r->left=insert(r->left,num); 53 | }else{ 54 | r->right=insert(r->right,num); 55 | } 56 | } 57 | return r; 58 | } 59 | 60 | void preOrderDisplay(Node *r){ 61 | if(r!=NULL){ 62 | printf("%d ",r->data); 63 | preOrderDisplay(r->left); 64 | preOrderDisplay(r->right); 65 | } 66 | } 67 | 68 | void inOrderDisplay(Node *r){ 69 | if(r!=NULL){ 70 | inOrderDisplay(r->left); 71 | printf("%d ",r->data); 72 | inOrderDisplay(r->right); 73 | } 74 | } 75 | 76 | void postOrderDisplay(Node *r){ 77 | if(r!=NULL){ 78 | postOrderDisplay(r->left); 79 | postOrderDisplay(r->right); 80 | printf("%d ",r->data); 81 | } 82 | } 83 | 84 | int search(Node *r,int num){ 85 | if(r==NULL)return 0; 86 | else if(r->data==num)return 0; 87 | else if(r->data > num) 88 | search(r->left,num); 89 | else 90 | search(r->right,num); 91 | }// } Driver Code Ends 92 | 93 | 94 | /* The structure of Node 95 | struct Node{ 96 | int data; 97 | Node *left,*right; 98 | }; */ 99 | 100 | 101 | /*You are required to complete below method */ 102 | int sumOfLeafNodes(Node *r ){ 103 | /*Your code here */ 104 | 105 | if(!r) 106 | return 0; 107 | else{ 108 | if(!r->left && !r->right) 109 | {return r->data;} 110 | else{ 111 | return (sumOfLeafNodes(r->left)+sumOfLeafNodes(r->right)); 112 | } 113 | } 114 | } 115 | -------------------------------------------------------------------------------- /Searching and Sorting/Python/selection_and_bubble_sort.py: -------------------------------------------------------------------------------- 1 | #The selection sort algorithm sorts an array by repeatedly finding the minimum element (considering ascending order) from unsorted part and putting it at the beginning. The algorithm maintains two subarrays in a given array. 2 | #1) The subarray which is already sorted. 3 | #2) Remaining subarray which is unsorted. 4 | #In every iteration of selection sort, the minimum element (considering ascending order) from the unsorted subarray is picked and moved to the sorted subarray. 5 | 6 | #Bubble Sort Algorithm is the simplest sorting algorithm in which each element is compared to its adjacent element 7 | #and if first elememt is greater than second element ,then the swapping occurs. 8 | #The swapping occurs till the array is sorted. 9 | 10 | def selectionsort(array, size): #initialize the class definition 11 | for step in range(size): 12 | min_indx = step #initialize min_indx to step 13 | for i in range(step + 1, size): #inner for loop 14 | if array[i] < array[min_indx]: #Checking if the element is larger than the next element 15 | min_indx = i 16 | 17 | (array[step], array[min_indx]) = (array[min_indx], array[step]); 18 | return array 19 | 20 | 21 | def bubblesort(arr, n): 22 | for i in range(n - 1): 23 | for j in range(n - i - 1): #inner for loop 24 | if arr[j] > arr[j + 1]: #Checking if the element is less than the next element 25 | (arr[j], arr[j + 1]) = (arr[j + 1], arr[j]) 26 | return arr 27 | 28 | 29 | def display(arr, cnt): 30 | size = len(arr) 31 | while cnt > 0: #while loop for printing out the array after sorting 32 | print(arr[size - 1]); 33 | size = size - 1; 34 | cnt = cnt - 1; 35 | 36 | 37 | data = list(); 38 | num = input("Enter the number of elements:"); #input 39 | for i in range(int(num)): 40 | n = input("num:"); 41 | data.append(float(n)); 42 | choice = 1; 43 | while choice != 3: #while loop for making a choice between selection sort and bubble sort 44 | print("1. selection sort:"); 45 | print("2. Bubble sort:"); 46 | print("3. Exit"); 47 | choice = int(input("choice:")); 48 | if choice == 1: 49 | arr = selectionsort(data[:], len(data)); #calling class definition 50 | print(arr); 51 | display(arr, 5); 52 | if choice == 2: 53 | arr = bubblesort(data, len(data)); #calling class definition 54 | print(arr); 55 | display(arr, 5); 56 | 57 | #Time complexities: 58 | # 1)selection sort: О(n2) 59 | # 2)bubble sort: O(n2) 60 | 61 | #space complexities: 62 | # 1)selection sort: O(1) 63 | # 2)bubble sort: O(1) -------------------------------------------------------------------------------- /Stack/Other/C Sharp/stack.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace StackImplementation 4 | { 5 | internal class Stack 6 | { 7 | 8 | // declaring the stack 9 | static readonly int MAX = 1000; 10 | int top; 11 | int[] stack = new int[MAX]; 12 | 13 | bool IsEmpty() 14 | { 15 | return (top < 0); 16 | } 17 | public Stack() 18 | { 19 | top = -1; 20 | } 21 | 22 | // checking overflow condition & push operation 23 | 24 | internal bool Push(int data) 25 | { 26 | if (top >= MAX) 27 | { 28 | Console.WriteLine("Stack Overflow"); 29 | return false; 30 | } 31 | else 32 | { 33 | stack[++top] = data; 34 | return true; 35 | } 36 | } 37 | // checking underflow condition & pop Operation 38 | 39 | internal int Pop() 40 | { 41 | if (top < 0) 42 | { 43 | Console.WriteLine("Stack Underflow"); 44 | return 0; 45 | } 46 | else 47 | { 48 | int value = stack[top--]; 49 | return value; 50 | } 51 | } 52 | 53 | // Top() of the stack 54 | internal void Peek() 55 | { 56 | if (top < 0) 57 | { 58 | Console.WriteLine("Stack Underflow"); 59 | return; 60 | } 61 | else 62 | Console.WriteLine("The topmost element of Stack is : {0}", stack[top]); 63 | } 64 | 65 | internal void PrintStack() 66 | { 67 | if (top < 0) 68 | { 69 | Console.WriteLine("Stack Underflow"); 70 | return; 71 | } 72 | else 73 | { 74 | Console.WriteLine("Items in the Stack are :"); 75 | for (int i = top; i >= 0; i--) 76 | { 77 | Console.WriteLine(stack[i]); 78 | } 79 | } 80 | } 81 | } 82 | 83 | // Driver codes 84 | class Program 85 | { 86 | static void Main(string[] args) 87 | { 88 | Stack myStack = new Stack(); 89 | 90 | myStack.Push(10); 91 | myStack.Push(20); 92 | myStack.Push(30); 93 | myStack.Push(40); 94 | myStack.PrintStack(); 95 | myStack.Peek(); 96 | Console.WriteLine("Item popped from Stack : {0}", myStack.Pop()); 97 | myStack.PrintStack(); 98 | } 99 | } 100 | } -------------------------------------------------------------------------------- /Searching and Sorting/Python/Binary_Search.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Binary Search: Search a sorted array by repeatedly dividing the search 3 | interval in half. Begin with an interval covering the whole array. 4 | If the value of the search key is less than the item in the middle of 5 | the interval, narrow the interval to the lower half. Otherwise narrow it 6 | to the upper half. Repeatedly check until the value is found or the 7 | interval is empty. 8 | 9 | The idea of binary search is to use the information that the array is 10 | sorted and reduce the time complexity to O(Log n). 11 | 12 | ALGORITHM 13 | We basically ignore half of the elements just after one comparison. 14 | 15 | 1.Compare x with the middle element. 16 | 2.If x matches with middle element, we return the mid index. 17 | 3.Else If x is greater than the mid element, then x can only lie in 18 | right half subarray after the mid element. So we recur for right half. 19 | 4.Else (x is smaller) recur for the left half. 20 | ''' 21 | 22 | '''Recursive implementation of Binary Search''' 23 | 24 | 25 | def binarySearch(arr, l, r, x): 26 | if r >= l: 27 | 28 | mid = l + (r - l) // 2 29 | 30 | # If element is present at the middle itself 31 | if arr[mid] == x: 32 | return mid 33 | 34 | # If element is smaller than mid, then it can only be present 35 | # in left subarray 36 | elif arr[mid] > x: 37 | return binarySearch(arr, l, mid - 1, x) 38 | 39 | # Else the element can only be present 40 | # in right subarray 41 | else: 42 | return binarySearch(arr, mid + 1, r, x) 43 | 44 | else: 45 | return -1 46 | 47 | 48 | arr = [2, 3, 4, 10, 40] 49 | x = 10 50 | 51 | result = binarySearch(arr, 0, len(arr) - 1, x) 52 | 53 | if result != -1: 54 | print("Element is present at index % d" % result) 55 | else: 56 | print("Element is not present in array") 57 | 58 | ''' 59 | OUTPUT: Element is present at index 3 60 | ''' 61 | 62 | '''Iterative implementation of Binary Search''' 63 | 64 | 65 | def binarySearch(arr, l, r, x): 66 | while l <= r: 67 | 68 | mid = l + (r - l) // 2; 69 | 70 | # Check if x is present at mid 71 | if arr[mid] == x: 72 | return mid 73 | 74 | # If x is greater, ignore left half 75 | elif arr[mid] < x: 76 | l = mid + 1 77 | 78 | # If x is smaller, ignore right half 79 | else: 80 | r = mid - 1 81 | 82 | return -1 83 | 84 | 85 | arr = [2, 3, 4, 10, 40] 86 | x = 4 87 | 88 | result = binarySearch(arr, 0, len(arr) - 1, x) 89 | 90 | if result != -1: 91 | print("Element is present at index % d" % result) 92 | else: 93 | print("Element is not present in array") 94 | 95 | 96 | ''' 97 | OUTPUT: Element is present at index 2 98 | ''' -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Data-Structure 2 | Repository for cool algorithms and Data Structures. Contibute by adding your code's for various operation on Data structure and trivial problem that can be solved by using them . 3 | 4 | # How to contribute: 5 | Please comment your code thoroughly as to make it possible for anyone to understand. If possible, check your code using unit tests. Avoid all the bad implementations, make your code as clean as possible. After that, find the folder that fits the category of your code and submit a PR. Star this repo if the information here is useful to you. 6 | 7 | # Contributing Guidelines : 8 | Thanks for taking the time to contribute to this project. Before making PRs, please note the following: 9 | 10 | **A few norms you should follow :** 11 | - Proper intendation is must! 12 | - Include Sample comments so that code is understandable and easy to follow. 13 | - Mention the complexity of a function in a comment. 14 | - Time complexity 15 | - Space complexity 16 | - Place your code in right directory. 17 | - Give your files names that are relevant and meaningful for example : linked_list_insertion.cpp 18 | 19 | # Steps to Contribute : 20 | 21 | - **Fork this repository** :On top right corner click there . 22 | - **Clone the repository** : Now clone the forked repository to your machine. Go to your GitHub account, open the forked repository, click on the code button and then click the copy to clipboard icon. 23 | 24 | Open a terminal and run the following git command: 25 | ``` 26 | git clone "url you just copied" 27 | ``` 28 | - **Create a branch**: 29 | Change to the repository directory on your computer (if you are not already there): 30 | ``` 31 | cd Data-Structure 32 | ``` 33 | Now create a branch using the git checkout command: 34 | ``` 35 | git checkout -b your-new-branch-name 36 | ``` 37 | For example: 38 | ``` 39 | git checkout -b add-tree-insertion 40 | ``` 41 | (The name of the branch does not need to have the word add in it, but it's a reasonable thing to include because the purpose of this branch is to add your name to a list.) 42 | 43 | - **Make necessary changes and commit those changes** 44 | - Add file in respective folders follow rules of contribution 45 | ``` 46 | git add insertion_in_tree.py 47 | ``` 48 | Now commit those changes using the git commit command: 49 | ``` 50 | git commit -m "Add insertion in tree" 51 | ``` 52 | 53 | - **Push changes to GitHub** 54 | Push your changes using the command git push: 55 | ``` 56 | git push origin 57 | ``` 58 | 59 | - **Submit your changes for review** 60 | If you go to your repository on GitHub, you'll see a ```Compare & pull request button.``` Click on that button. 61 | 62 | - **Now submit the pull request.** 63 | Soon I'll be merging all your changes into the master branch of this project. You will get a notification email once the changes have been merged. 64 | 65 | 66 | 67 | **Keep On Exploring Open Source then :purple_heart:!** 68 | -------------------------------------------------------------------------------- /Queue/C++/dequeue.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #define SIZE 10 4 | 5 | class dequeue { 6 | int a[20],f,r; 7 | public: 8 | dequeue(); 9 | void insert_at_beg(int); 10 | void insert_at_end(int); 11 | void delete_fr_front(); 12 | void delete_fr_rear(); 13 | void show(); 14 | }; 15 | 16 | dequeue::dequeue() { 17 | f=-1; 18 | r=-1; 19 | } 20 | 21 | void dequeue::insert_at_end(int i) { 22 | if(r>=SIZE-1) { 23 | cout<<"\n insertion is not possible, overflow!!!!"; 24 | } else { 25 | if(f==-1) { 26 | f++; 27 | r++; 28 | } else { 29 | r=r+1; 30 | } 31 | a[r]=i; 32 | cout<<"\nInserted item is"<>c; 101 | switch(c) { 102 | case 1: 103 | cout<<"enter the element to be inserted"; 104 | cin>>i; 105 | d.insert_at_beg(i); 106 | break; 107 | case 2: 108 | cout<<"enter the element to be inserted"; 109 | cin>>i; 110 | d.insert_at_end(i); 111 | break; 112 | case 3: 113 | d.show(); 114 | break; 115 | case 4: 116 | d.delete_fr_front(); 117 | break; 118 | case 5: 119 | d.delete_fr_rear(); 120 | break; 121 | case 6: 122 | exit(1); 123 | break; 124 | default: 125 | cout<<"invalid choice"; 126 | break; 127 | } 128 | } while(c!=7); 129 | } -------------------------------------------------------------------------------- /BST/Python/Python.py: -------------------------------------------------------------------------------- 1 | #Include python Code 2 | 3 | """ 4 | Few important time complexities ivolved are:- 5 | Searching -> O(n) 6 | Inserting -> O(h) 7 | Deleting -> O(h) 8 | """ 9 | 10 | class Node: 11 | def __init__(self, val): 12 | self.val = val 13 | self.left = None 14 | self.right = None 15 | 16 | class BST: 17 | def __init__(self): 18 | self.root = None 19 | 20 | def insert(self, data): 21 | if self.root is None: 22 | self.root = Node(data) 23 | else: 24 | self._insert(self.root, data) 25 | 26 | def _insert(self, curr, data): 27 | if curr.val>data: 28 | if curr.left: 29 | self._insert(curr.left, data) 30 | else: 31 | curr.left = Node(data) 32 | 33 | elif curr.val 3 | using namespace std; 4 | #define MAX_HEIGHT 100000 5 | 6 | // Tree Node 7 | struct Node 8 | { 9 | int data; 10 | Node* left; 11 | Node* right; 12 | }; 13 | 14 | // Utility function to create a new Tree Node 15 | Node* newNode(int val) 16 | { 17 | Node* temp = new Node; 18 | temp->data = val; 19 | temp->left = NULL; 20 | temp->right = NULL; 21 | 22 | return temp; 23 | } 24 | 25 | 26 | 27 | int leftLeavesSum(Node *root); 28 | 29 | // Function to Build Tree 30 | Node* buildTree(string str) 31 | { 32 | // Corner Case 33 | if(str.length() == 0 || str[0] == 'N') 34 | return NULL; 35 | 36 | // Creating vector of strings from input 37 | // string after spliting by space 38 | vector ip; 39 | 40 | istringstream iss(str); 41 | for(string str; iss >> str; ) 42 | ip.push_back(str); 43 | 44 | // Create the root of the tree 45 | Node* root = newNode(stoi(ip[0])); 46 | 47 | // Push the root to the queue 48 | queue queue; 49 | queue.push(root); 50 | 51 | // Starting from the second element 52 | int i = 1; 53 | while(!queue.empty() && i < ip.size()) { 54 | 55 | // Get and remove the front of the queue 56 | Node* currNode = queue.front(); 57 | queue.pop(); 58 | 59 | // Get the current node's value from the string 60 | string currVal = ip[i]; 61 | 62 | // If the left child is not null 63 | if(currVal != "N") { 64 | 65 | // Create the left child for the current node 66 | currNode->left = newNode(stoi(currVal)); 67 | 68 | // Push it to the queue 69 | queue.push(currNode->left); 70 | } 71 | 72 | // For the right child 73 | i++; 74 | if(i >= ip.size()) 75 | break; 76 | currVal = ip[i]; 77 | 78 | // If the right child is not null 79 | if(currVal != "N") { 80 | 81 | // Create the right child for the current node 82 | currNode->right = newNode(stoi(currVal)); 83 | 84 | // Push it to the queue 85 | queue.push(currNode->right); 86 | } 87 | i++; 88 | } 89 | 90 | return root; 91 | } 92 | 93 | void inorder(Node *root, vector &v) 94 | { 95 | if(root==NULL) 96 | return; 97 | 98 | inorder(root->left, v); 99 | v.push_back(root->data); 100 | inorder(root->right, v); 101 | } 102 | 103 | int main() { 104 | //freopen("input.txt","r", stdin); 105 | //freopen("output.txt","w", stdout); 106 | int t; 107 | string tc; 108 | getline(cin, tc); 109 | t=stoi(tc); 110 | //cout << t << endl; 111 | while(t--) 112 | { 113 | string s; 114 | getline(cin, s); 115 | Node* root = buildTree(s); 116 | 117 | //getline(cin, s); 118 | 119 | cout << leftLeavesSum(root) << endl; 120 | 121 | //cout<<"~"<left && !root->left->left && !root->left->right) 143 | return (root->left->data+leftLeavesSum(root->right)); 144 | 145 | return leftLeavesSum(root->left)+leftLeavesSum(root->right); 146 | } 147 | -------------------------------------------------------------------------------- /Tree/C++/isBST.cpp: -------------------------------------------------------------------------------- 1 | // { Driver Code Starts 2 | #include 3 | using namespace std; 4 | #define MAX_HEIGHT 100000 5 | 6 | // Tree Node 7 | struct Node { 8 | int data; 9 | Node *left; 10 | Node *right; 11 | 12 | Node(int val) { 13 | data = val; 14 | left = right = NULL; 15 | } 16 | }; 17 | 18 | 19 | 20 | bool isBST(struct Node* node); 21 | int isBSTUtil(struct Node* node, int min, int max); 22 | 23 | // Function to Build Tree 24 | Node* buildTree(string str) 25 | { 26 | // Corner Case 27 | if(str.length() == 0 || str[0] == 'N') 28 | return NULL; 29 | 30 | // Creating vector of strings from input 31 | // string after spliting by space 32 | vector ip; 33 | 34 | istringstream iss(str); 35 | for(string str; iss >> str; ) 36 | ip.push_back(str); 37 | 38 | // Create the root of the tree 39 | Node* root = new Node(stoi(ip[0])); 40 | 41 | // Push the root to the queue 42 | queue queue; 43 | queue.push(root); 44 | 45 | // Starting from the second element 46 | int i = 1; 47 | while(!queue.empty() && i < ip.size()) { 48 | 49 | // Get and remove the front of the queue 50 | Node* currNode = queue.front(); 51 | queue.pop(); 52 | 53 | // Get the current node's value from the string 54 | string currVal = ip[i]; 55 | 56 | // If the left child is not null 57 | if(currVal != "N") { 58 | 59 | // Create the left child for the current node 60 | currNode->left = new Node(stoi(currVal)); 61 | 62 | // Push it to the queue 63 | queue.push(currNode->left); 64 | } 65 | 66 | // For the right child 67 | i++; 68 | if(i >= ip.size()) 69 | break; 70 | currVal = ip[i]; 71 | 72 | // If the right child is not null 73 | if(currVal != "N") { 74 | 75 | // Create the right child for the current node 76 | currNode->right = new Node(stoi(currVal)); 77 | 78 | // Push it to the queue 79 | queue.push(currNode->right); 80 | } 81 | i++; 82 | } 83 | 84 | return root; 85 | } 86 | 87 | void inorder(Node *root, vector &v) 88 | { 89 | if(root==NULL) 90 | return; 91 | 92 | inorder(root->left, v); 93 | v.push_back(root->data); 94 | inorder(root->right, v); 95 | } 96 | 97 | int main() { 98 | 99 | int t; 100 | string tc; 101 | getline(cin, tc); 102 | t=stoi(tc); 103 | while(t--) 104 | { 105 | string s; 106 | getline(cin, s); 107 | Node* root = buildTree(s); 108 | cout << isBST(root) << endl; 109 | } 110 | return 0; 111 | } 112 | 113 | 114 | 115 | // } Driver Code Ends 116 | 117 | 118 | /* A binary tree node has data, pointer to left child 119 | and a pointer to right child 120 | struct Node { 121 | int data; 122 | Node *left; 123 | Node *right; 124 | 125 | Node(int val) { 126 | data = val; 127 | left = right = NULL; 128 | } 129 | }; 130 | */ 131 | 132 | bool level(Node*root,Node* &prev) 133 | { 134 | 135 | if(root) 136 | { 137 | if(!level(root->left,prev)) 138 | return false; 139 | 140 | if(prev!=NULL && root->data<=prev->data) 141 | return false; 142 | 143 | prev=root; 144 | 145 | return level(root->right,prev); 146 | } 147 | 148 | return true; 149 | 150 | } 151 | 152 | 153 | // return true if the given tree is a BST, else return false 154 | bool isBST(Node* root) { 155 | // Your code here 156 | 157 | Node*prev=NULL; 158 | 159 | return level(root,prev); 160 | } 161 | 162 | 163 | 164 | 165 | // { Driver Code Starts 166 | // } Driver Code Ends 167 | -------------------------------------------------------------------------------- /Tree/C++/removehalfnode.cpp: -------------------------------------------------------------------------------- 1 | // { Driver Code Starts 2 | #include 3 | using namespace std; 4 | 5 | struct Node { 6 | int data; 7 | Node *left; 8 | Node *right; 9 | 10 | Node(int val) { 11 | data = val; 12 | left = right = NULL; 13 | } 14 | }; 15 | // Function to Build Tree 16 | Node* buildTree(string str) 17 | { 18 | // Corner Case 19 | if(str.length() == 0 || str[0] == 'N') 20 | return NULL; 21 | 22 | // Creating vector of strings from input 23 | // string after spliting by space 24 | vector ip; 25 | 26 | istringstream iss(str); 27 | for(string str; iss >> str; ) 28 | ip.push_back(str); 29 | 30 | // Create the root of the tree 31 | Node* root = new Node(stoi(ip[0])); 32 | 33 | // Push the root to the queue 34 | queue queue; 35 | queue.push(root); 36 | 37 | // Starting from the second element 38 | int i = 1; 39 | while(!queue.empty() && i < ip.size()) { 40 | 41 | // Get and remove the front of the queue 42 | Node* currNode = queue.front(); 43 | queue.pop(); 44 | 45 | // Get the current node's value from the string 46 | string currVal = ip[i]; 47 | 48 | // If the left child is not null 49 | if(currVal != "N") { 50 | 51 | // Create the left child for the current node 52 | currNode->left = new Node(stoi(currVal)); 53 | 54 | // Push it to the queue 55 | queue.push(currNode->left); 56 | } 57 | 58 | // For the right child 59 | i++; 60 | if(i >= ip.size()) 61 | break; 62 | currVal = ip[i]; 63 | 64 | // If the right child is not null 65 | if(currVal != "N") { 66 | 67 | // Create the right child for the current node 68 | currNode->right = new Node(stoi(currVal)); 69 | 70 | // Push it to the queue 71 | queue.push(currNode->right); 72 | } 73 | i++; 74 | } 75 | 76 | return root; 77 | } 78 | void inorder(Node * node) 79 | { 80 | if(node==NULL) 81 | return; 82 | 83 | inorder(node->left); 84 | cout<data<<" "; 85 | inorder(node->right); 86 | } 87 | Node* RemoveHalfNodes(Node* root) ; 88 | 89 | int main() 90 | { 91 | 92 | int t; 93 | scanf("%d ",&t); 94 | while(t--) 95 | { 96 | string s; 97 | getline(cin,s); 98 | Node* root = buildTree(s); 99 | Node * fresh = RemoveHalfNodes(root); 100 | inorder(fresh); 101 | cout<left==NULL && root->right==NULL) 129 | return root; 130 | 131 | if(root->left==NULL || root->right==NULL ) 132 | { 133 | Node*temp; 134 | if(root->left) 135 | temp=root->left; 136 | else 137 | if(root->right) 138 | temp=root->right; 139 | 140 | delete root; 141 | return RemoveHalfNodes(temp); 142 | } 143 | root->left = RemoveHalfNodes(root->left); 144 | root->right = RemoveHalfNodes(root->right); 145 | 146 | return root; 147 | } 148 | -------------------------------------------------------------------------------- /Segment Tree/C++/segmenttree.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void buildtree(int *tree,int *a, int index, int s, int e) 5 | { 6 | 7 | //base case 8 | if(s > e) 9 | return; 10 | 11 | //base class leaf node 12 | if(s == e) 13 | { 14 | tree[index] = a[s]; 15 | return; 16 | } 17 | 18 | //recursive case 19 | int mid = (s + e)/2; 20 | 21 | //build left sub tree 22 | buildtree(tree,a,2*index,s, mid); 23 | 24 | //build right sub tree 25 | buildtree(tree, a, 2*index+1, mid+1, e); 26 | 27 | //getting min value 28 | int left = tree[2*index]; 29 | int right = tree[2*index + 1]; 30 | 31 | tree[index] = min(left, right); 32 | 33 | } 34 | 35 | int query(int *tree,int index, int s, int e, int qs, int qe) 36 | { 37 | //complete overlap condition 38 | if(qs <= s and qe >= e) 39 | return tree[index]; 40 | 41 | //No overlap condition 42 | if(qe < s or qs > e) 43 | return INT_MAX; 44 | 45 | //Partial Overlap 46 | int mid = (s+e)/2; 47 | //getting results from left and right 48 | int left = query(tree, index*2, s, mid,qs,qe); 49 | int right = query(tree, index*2+1, mid+1, e,qs,qe); 50 | 51 | //returning the minimum one 52 | return min(left, right); 53 | } 54 | 55 | //to update a single node 56 | void updatenode(int *tree, int index, int s, int e, int i, int val) 57 | { 58 | //no overlap 59 | if(i < s or i > e) 60 | return; 61 | 62 | //reached leaf node 63 | if(s == e) 64 | { 65 | tree[index] = val; 66 | return; 67 | } 68 | 69 | //partial overlap (i.e. i is lying between s and e) 70 | int mid = (s + e)/2; 71 | updatenode(tree, 2*index, s, mid, i, val); 72 | updatenode(tree, 2*index + 1, mid + 1, e, i, val); 73 | 74 | //updating parent nodes 75 | tree[index] = min(tree[2*index], tree[2*index + 1]); 76 | 77 | return; 78 | } 79 | 80 | //incrementing a range with a particular value 81 | void updaterange(int *tree, int index, int s, int e, int rs, int re, int inc) 82 | { 83 | 84 | //no overlap 85 | if(re < s or rs > e) 86 | return; 87 | 88 | if(s==e) 89 | { 90 | tree[index] += inc; 91 | return; 92 | } 93 | 94 | int mid = (s + e)/2; 95 | updaterange(tree, 2*index, s, mid, rs, re, inc); 96 | updaterange(tree, 2*index + 1, mid + 1, e, rs, re, inc); 97 | 98 | //updating parent nodes 99 | tree[index] = min(tree[2*index], tree[2*index + 1]); 100 | return; 101 | } 102 | 103 | 104 | int main() 105 | { 106 | int n; 107 | cout<<"Enter the no. of elements: "; 108 | cin>>n; 109 | int a[n]; 110 | for(int i=0; i>a[i]; 114 | } 115 | //starting and ending values 116 | int s = 0; 117 | int e = n-1; 118 | 119 | 120 | //making a tree array of size(4*n + 1).[4*n + 1 is an upper bound] 121 | int tree[(4*n) + 1]; 122 | 123 | //building the tree 124 | buildtree(tree, a, 1, s, e); 125 | 126 | int q; 127 | cout<<"Enter the number of queries: "; 128 | cin>>q; 129 | 130 | int l, r, i, val; 131 | 132 | while(q--) 133 | { 134 | int ch; 135 | cout<<"Press 1 to get the minimum value between a range"<>ch; 140 | 141 | switch(ch) 142 | { 143 | case 1: cout<<"Range starts from (0 based indexing): "; 144 | cin>>l; 145 | cout<<"Range ends at (0 based indexing): "; 146 | cin>>r; 147 | cout<<"minimum number in range "<>i; 152 | cout<<"Enter the updated value: "; 153 | cin>>val; 154 | updatenode(tree, 1, s, e, i, val); 155 | cout<<"value updated successfully."<>l; 160 | cout<<"Range ends at (0 based indexing): "; 161 | cin>>r; 162 | cout<<"Range updated from "< 5 | using namespace std; 6 | 7 | struct Node 8 | { 9 | int data; 10 | Node *left, *right; 11 | Node(int val) 12 | { 13 | data = val; 14 | left = right = NULL; 15 | } 16 | }; 17 | 18 | Node* buildTree(string str) 19 | { 20 | // Corner Case 21 | if(str.length() == 0 || str[0] == 'N') 22 | return NULL; 23 | 24 | // Creating vector of strings from input 25 | // string after spliting by space 26 | vector ip; 27 | 28 | istringstream iss(str); 29 | for(string str; iss >> str; ) 30 | ip.push_back(str); 31 | 32 | // Create the root of the tree 33 | Node* root = new Node(stoi(ip[0])); 34 | 35 | // Push the root to the queue 36 | queue queue; 37 | queue.push(root); 38 | 39 | // Starting from the second element 40 | int i = 1; 41 | while(!queue.empty() && i < ip.size()) { 42 | 43 | // Get and remove the front of the queue 44 | Node* currNode = queue.front(); 45 | queue.pop(); 46 | 47 | // Get the current node's value from the string 48 | string currVal = ip[i]; 49 | 50 | // If the left child is not null 51 | if(currVal != "N") { 52 | 53 | // Create the left child for the current node 54 | currNode->left = new Node(stoi(currVal)); 55 | 56 | // Push it to the queue 57 | queue.push(currNode->left); 58 | } 59 | 60 | // For the right child 61 | i++; 62 | if(i >= ip.size()) 63 | break; 64 | currVal = ip[i]; 65 | 66 | // If the right child is not null 67 | if(currVal != "N") { 68 | 69 | // Create the right child for the current node 70 | currNode->right = new Node(stoi(currVal)); 71 | 72 | // Push it to the queue 73 | queue.push(currNode->right); 74 | } 75 | i++; 76 | } 77 | 78 | return root; 79 | } 80 | 81 | bool isBST(Node* n, int lower, int upper) 82 | { 83 | if(!n) return true; 84 | if( n->data <= lower || n->data >= upper ) return false; 85 | return ( isBST( n->left, lower, n->data ) && isBST( n->right, n->data, upper ) ); 86 | } 87 | 88 | bool compare( Node* a, Node* b, vector> &mismatch ) 89 | { 90 | if( !a && !b ) return true; 91 | if( !a || !b ) return false; 92 | 93 | if( a->data != b->data ) 94 | mismatch.push_back( pair (a->data,b->data) ); 95 | 96 | return ( compare( a->left, b->left, mismatch ) && compare( a->right, b->right, mismatch ) ); 97 | } 98 | 99 | struct Node *correctBST( struct Node* root ); 100 | 101 | int main() 102 | { 103 | int t; 104 | cin>>t; 105 | getchar(); 106 | 107 | while(t--) 108 | { 109 | string s; 110 | getline(cin,s); 111 | 112 | Node* root = buildTree(s); 113 | Node* duplicate = buildTree(s); 114 | 115 | root = correctBST(root); 116 | 117 | // check 1: is tree now a BST 118 | if( ! isBST(root, INT_MIN, INT_MAX) ) 119 | { 120 | cout<< "0\n"; 121 | continue; 122 | } 123 | 124 | // check 2: comparing with duplicate tree 125 | 126 | vector> mismatch; 127 | // a vector to store data of mismatching nodes 128 | 129 | if( ! compare( root, duplicate, mismatch) ) 130 | { 131 | // false output from this function indicates change in structure of tree 132 | cout<< "0\n"; 133 | continue; 134 | } 135 | 136 | // finally, analysing the mismatching nodes 137 | if( mismatch.size() !=2 || mismatch[0].first!=mismatch[1].second || mismatch[0].second!=mismatch[1].first ) 138 | cout<<"0\n"; 139 | else cout<<"1\n"; 140 | } 141 | return 0; 142 | } 143 | // } Driver Code Ends 144 | 145 | 146 | /*Complete the function 147 | Node is as follows: 148 | 149 | struct Node 150 | { 151 | int data; 152 | struct Node *left, *right; 153 | Node(int x){ 154 | int data = x; 155 | left = right = NULL; 156 | } 157 | }; 158 | 159 | */ 160 | void defect(Node*root,Node* &prev,Node* &first,Node* &second) 161 | { 162 | if(!root) 163 | return; 164 | 165 | defect(root->left,prev,first,second); 166 | 167 | if(prev!=NULL && prev->data>root->data) 168 | { 169 | if(!first) 170 | { 171 | first=prev; 172 | } 173 | second=root; 174 | } 175 | prev=root; 176 | 177 | defect(root->right,prev,first,second); 178 | 179 | } 180 | 181 | 182 | struct Node *correctBST( struct Node* root ) 183 | { 184 | Node*first =NULL,*second = NULL,*prev = NULL; 185 | 186 | defect(root,prev,first,second); 187 | swap(first->data,second->data); 188 | 189 | return root; 190 | } 191 | 192 | -------------------------------------------------------------------------------- /Queue/C++/circularqueue.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | /////////////////////////////////////////////////////////////////////////////////// 5 | // Slightly different approach ,with 'void' return type // 6 | /////////////////////////////////////////////////////////////////////////////////// 7 | 8 | typedef struct node 9 | { 10 | int data; 11 | struct node* next; 12 | }NODE,*PNODE; 13 | /////////////////////////////////////////////////////////////////////////////////// 14 | 15 | class CircularQueue 16 | { 17 | PNODE head,tail; //maintaining two pointers 18 | //there is no as such termination in CLL unlike linear linkedlist 19 | int ct; 20 | public: 21 | CircularQueue(); //constructor 22 | ~CircularQueue(); //To deallocate the used memory 23 | 24 | void Insert(int); 25 | 26 | void Remove(); 27 | 28 | void DisplayQueue(); //to Display the Queue 29 | int Count(); //Display total number of nodes present in Linked List 30 | }; 31 | /////////////////////////////////////////////////////////////////////////////////// 32 | //Initializing memory 33 | CircularQueue::CircularQueue() 34 | { 35 | head=tail=NULL; 36 | ct=0; 37 | } 38 | /////////////////////////////////////////////////////////////////////////////////// 39 | //To get total number of nodes/elements present in the Linked List 40 | int CircularQueue::Count() 41 | { 42 | ct=0; 43 | PNODE temp=head; 44 | while(temp->next!=head) 45 | { 46 | ct++; 47 | temp=temp->next; 48 | } 49 | ct++; 50 | return ct; 51 | } 52 | /////////////////////////////////////////////////////////////////////////////////// 53 | //Display entire Linked List 54 | void CircularQueue::DisplayQueue() 55 | { 56 | PNODE temp=head; 57 | while(temp->next!=head) 58 | { 59 | cout<data<<" "; 60 | temp=temp->next; 61 | } 62 | cout<data<<" "; 63 | } 64 | /////////////////////////////////////////////////////////////////////////////////// 65 | //Inserting element at the end of Linked List 66 | void CircularQueue::Insert(int n) 67 | { 68 | PNODE temp=head; 69 | PNODE newn=new node; 70 | newn->data=n; 71 | newn->next=NULL; 72 | if(head==NULL && tail==NULL) 73 | { 74 | head=newn; 75 | tail=newn; 76 | } 77 | else 78 | { 79 | tail->next=newn; 80 | tail=tail->next; 81 | } 82 | tail->next=head; 83 | 84 | } 85 | /////////////////////////////////////////////////////////////////////////////////// 86 | //Delete first element of Linked List 87 | void CircularQueue::Remove() 88 | { 89 | //Empty Linked list 90 | if(head==NULL && tail==NULL) 91 | { 92 | cout<<"\nNothing to delete"; 93 | return; 94 | } 95 | 96 | //Linked list containing only one element 97 | else if(head==tail) 98 | { 99 | delete head; 100 | head=tail=NULL; 101 | } 102 | //Multiple nodes 103 | else 104 | { 105 | head=head->next; 106 | delete tail->next; 107 | tail->next=head; 108 | } 109 | } 110 | /////////////////////////////////////////////////////////////////////////////////// 111 | //Destructor: to deallocate the used memory 112 | CircularQueue::~CircularQueue() 113 | { 114 | PNODE temp=head; 115 | if(head==NULL && tail==NULL) 116 | return; 117 | else 118 | { 119 | while(head!=tail) 120 | { 121 | head=head->next; 122 | delete temp; 123 | temp=head; 124 | } 125 | } 126 | } 127 | /////////////////////////////////////////////////////////////////////////////////// 128 | //main function of the program 129 | /////////////////////////////////////////////////////////////////////////////////// 130 | int main() 131 | { 132 | CircularQueue obj; 133 | 134 | //Here one can opt for menu driven approach also! 135 | cout<<"\n"; 136 | obj.Insert(40); 137 | obj.DisplayQueue(); 138 | obj.Insert(70);cout<<"\n"; 139 | obj.DisplayQueue(); 140 | obj.Insert(100);cout<<"\n"; 141 | obj.DisplayQueue(); 142 | cout<<"\nSuccessfully inserted in queue"; 143 | obj.DisplayQueue();cout<<"\n"; 144 | cout<<"\nTotal number of elements "< 2 | #include 3 | #include 4 | using namespace std; 5 | class ArrayADT 6 | { 7 | private: 8 | int cap; 9 | int lastindex; 10 | int *p; 11 | public: 12 | ArrayADT() 13 | { 14 | cap=0; 15 | lastindex=-1; 16 | p=NULL; 17 | } 18 | ~ArrayADT() 19 | { 20 | delete[]p; 21 | } 22 | void create_array(int k); 23 | void set_item(int index,int value); 24 | int get_item(int index); 25 | void edit_item(int index,int value); 26 | void remove_item(int index); 27 | int count_item(); 28 | void sort_item(); 29 | void reverse_item(); 30 | }; 31 | void ArrayADT::create_array(int k) 32 | { 33 | cap=k; 34 | lastindex=-1; 35 | p=new int[k]; 36 | } 37 | void ArrayADT::set_item(int index,int value) 38 | { 39 | if(index<0 || index>lastindex+1) 40 | cout<<"Invalid index: "<lastindex) 65 | cout<<"invalid Index :"<lastindex) 74 | cout<<"Invalid index: "<lastindex) 83 | cout<<"Invalid index :"<p[i+1]) 113 | { 114 | t=p[i]; 115 | p[i]=p[i+1]; 116 | p[i+1]=t; 117 | } 118 | } 119 | } 120 | } 121 | } 122 | void ArrayADT::reverse_item() 123 | { 124 | int i,n,t; 125 | n=count_item(); 126 | if(n==0 || n==1) 127 | cout<<"Reverse is not possible:"<>k; 151 | return(k); 152 | } 153 | int main() 154 | { 155 | int k,i,t,m; 156 | ArrayADT a; 157 | cout<<"Enter capacity of an array :"<>k; 159 | if (k<=0) 160 | cout<<"invalid Capacity:"<>t; 171 | cout<<"Enter any item : \n"; 172 | cin>>m; 173 | a.set_item(t,m); 174 | break; 175 | case 2: 176 | for(i=0;i>t; 183 | cout<<"Enter any item : \n"; 184 | cin>>m; 185 | a.edit_item(t,m); 186 | break; 187 | case 4: 188 | cout<<"Enter any index: \n"; 189 | cin>>t; 190 | a.remove_item(t); 191 | break; 192 | case 5: 193 | m=a.count_item(); 194 | if(m==0) 195 | cout<<"No item is present :\n"; 196 | else 197 | cout<<"Number of item in the list is :"< 9 | using namespace std; 10 | 11 | /////////////////////////////////////////////////////////////////////////////////// 12 | // Slightly different approach ,with 'void' return type // 13 | /////////////////////////////////////////////////////////////////////////////////// 14 | 15 | typedef struct node 16 | { 17 | int data; 18 | struct node* next; 19 | }NODE,*PNODE; 20 | /////////////////////////////////////////////////////////////////////////////////// 21 | 22 | class SinglyLinearLL 23 | { 24 | PNODE head; 25 | int ct; 26 | public: 27 | SinglyLinearLL(); //constructor 28 | ~SinglyLinearLL(); //To deallocate the used memory 29 | 30 | void InsertFirst(int); 31 | void InsertLast(int); 32 | void InsertAtPos(int,int); 33 | 34 | void DeleteFirst(); 35 | void DeleteLast(); 36 | void DeleteAtPos(int); 37 | 38 | void DisplayLL(); //to Display the Linked List 39 | int Count(); //Display total number of nodes present in Linked List 40 | }; 41 | /////////////////////////////////////////////////////////////////////////////////// 42 | //Initializing memory 43 | SinglyLinearLL::SinglyLinearLL() 44 | { 45 | head=NULL; 46 | ct=0; 47 | } 48 | /////////////////////////////////////////////////////////////////////////////////// 49 | //To get total number of nodes/elements present in the Linked List 50 | int SinglyLinearLL::Count() 51 | { 52 | ct=0; 53 | PNODE temp=head; 54 | while(temp!=NULL) 55 | { 56 | ct++; 57 | temp=temp->next; 58 | } 59 | return ct; 60 | } 61 | /////////////////////////////////////////////////////////////////////////////////// 62 | //Display entire Linked List 63 | void SinglyLinearLL::DisplayLL() 64 | { 65 | PNODE temp=head; 66 | while(temp!=NULL) 67 | { 68 | cout<data<<" "; 69 | temp=temp->next; 70 | } 71 | } 72 | /////////////////////////////////////////////////////////////////////////////////// 73 | //Inserting element at the beginning of Linked List 74 | void SinglyLinearLL::InsertFirst(int n) 75 | { 76 | PNODE temp=head; 77 | PNODE newn=new node; 78 | newn->data=n; 79 | newn->next=NULL; 80 | if(temp==NULL) 81 | { 82 | head=newn; 83 | }else if(temp!=NULL) 84 | { 85 | newn->next=head; 86 | head=newn; 87 | } 88 | } 89 | /////////////////////////////////////////////////////////////////////////////////// 90 | //Inserting element at the end of Linked List 91 | void SinglyLinearLL::InsertLast(int n) 92 | { 93 | PNODE temp=head; 94 | PNODE newn=new node; 95 | newn->data=n; 96 | newn->next=NULL; 97 | if(head==NULL) 98 | { 99 | head=newn; 100 | } 101 | else 102 | { 103 | while(temp->next!=NULL) 104 | { 105 | temp=temp->next; 106 | } 107 | temp->next=newn; 108 | } 109 | } 110 | /////////////////////////////////////////////////////////////////////////////////// 111 | //Inserting element at desired Position in the Linked List 112 | void SinglyLinearLL::InsertAtPos(int pos,int n) 113 | { 114 | int tot=Count(); 115 | if(pos<1 || pos>tot+1) 116 | { 117 | cout<<"\nPosition invalid (element cannot be inserted"; 118 | return; 119 | } 120 | else if(pos==1) 121 | { 122 | //To insert element at beginning 123 | InsertFirst(n); 124 | } 125 | else if(pos==tot+1) 126 | { 127 | //To insert element at end 128 | InsertLast(n); 129 | } 130 | else 131 | { 132 | PNODE temp=head; 133 | PNODE newn=new node; 134 | newn->next=NULL; 135 | newn->data=n; 136 | for(int i=1;inext; 139 | } 140 | newn->next=temp->next; 141 | temp->next=newn; 142 | } 143 | } 144 | /////////////////////////////////////////////////////////////////////////////////// 145 | //Delete first element of Linked List 146 | void SinglyLinearLL::DeleteFirst() 147 | { 148 | if(head==NULL) 149 | { 150 | cout<<"\nNothing to delete"; 151 | return; 152 | } 153 | else 154 | { 155 | PNODE temp=head; 156 | head=head->next; 157 | delete temp; 158 | } 159 | } 160 | /////////////////////////////////////////////////////////////////////////////////// 161 | //Delete last element from the Linked List 162 | void SinglyLinearLL::DeleteLast() 163 | { 164 | if(head==NULL) 165 | { 166 | cout<<"\nNothing to delete\n"; 167 | return; 168 | } 169 | else if(head->next==NULL) 170 | { 171 | delete head; 172 | head=NULL; 173 | } 174 | else 175 | { 176 | PNODE temp=head; 177 | while(temp->next->next!=NULL) 178 | { 179 | temp=temp->next; 180 | } 181 | delete temp->next; 182 | temp->next=NULL; 183 | } 184 | } 185 | /////////////////////////////////////////////////////////////////////////////////// 186 | //Delete element from desired position in the Linked List 187 | void SinglyLinearLL::DeleteAtPos(int pos) 188 | { 189 | int tot=Count(); 190 | if(head==NULL) 191 | { 192 | cout<<"\nNothing to delete\n"; 193 | return; 194 | } 195 | if(pos<1 || pos>tot) 196 | { 197 | cout<<"\nPosition invalid\n"; 198 | } 199 | else if(pos==1) 200 | { 201 | DeleteFirst(); 202 | } 203 | else if(pos==tot) 204 | { 205 | DeleteLast(); 206 | } 207 | else 208 | { 209 | PNODE temp=head; 210 | PNODE curr=NULL; 211 | for(int i=1;inext; 214 | } 215 | curr=temp->next; 216 | temp->next=temp->next->next; 217 | delete curr; 218 | } 219 | } 220 | /////////////////////////////////////////////////////////////////////////////////// 221 | //Destructor: to deallocate the used memory 222 | SinglyLinearLL::~SinglyLinearLL() 223 | { 224 | PNODE temp=head; 225 | if(head==NULL) 226 | return; 227 | else if(head!=NULL) 228 | { 229 | while(head!=NULL) 230 | { 231 | head=head->next; 232 | delete temp; 233 | temp=head; 234 | } 235 | } 236 | 237 | } 238 | /////////////////////////////////////////////////////////////////////////////////// 239 | //main function of the program 240 | /////////////////////////////////////////////////////////////////////////////////// 241 | int main() 242 | { 243 | SinglyLinearLL obj; 244 | 245 | //Here one can opt for menu driven approach also! 246 | obj.InsertFirst(30); 247 | obj.InsertFirst(20); 248 | obj.InsertFirst(10); 249 | 250 | cout<<"\nSuccessfully inserted element from beginning\n"; 251 | 252 | obj.DisplayLL(); 253 | cout<<"\nTotal number of elements "< 10 | using namespace std; 11 | 12 | /////////////////////////////////////////////////////////////////////////////////// 13 | // Slightly different approach ,with 'void' return type // 14 | // Doubly linear linked list is maintained using two pointers // 15 | // Due to which it is possible to traverse in reverse as well as forward direction.// 16 | /////////////////////////////////////////////////////////////////////////////////// 17 | 18 | typedef struct node 19 | { 20 | int data; 21 | struct node* next; 22 | struct node* prev; 23 | }NODE,*PNODE; 24 | /////////////////////////////////////////////////////////////////////////////////// 25 | 26 | class DoublyLinearLL 27 | { 28 | PNODE head; 29 | int ct; 30 | public: 31 | DoublyLinearLL(); //constructor 32 | ~DoublyLinearLL(); //To deallocate the used memory 33 | 34 | void InsertFirst(int); 35 | void InsertLast(int); 36 | void InsertAtPos(int,int); 37 | 38 | void DeleteFirst(); 39 | void DeleteLast(); 40 | void DeleteAtPos(int); 41 | 42 | void DisplayDLL(); //to Display the Linked List 43 | int Count(); //Display total number of nodes present in Linked List 44 | }; 45 | /////////////////////////////////////////////////////////////////////////////////// 46 | //Initializing memory 47 | DoublyLinearLL::DoublyLinearLL() 48 | { 49 | head=NULL; 50 | ct=0; 51 | } 52 | /////////////////////////////////////////////////////////////////////////////////// 53 | //To get total number of nodes/elements present in the Linked List 54 | int DoublyLinearLL::Count() 55 | { 56 | ct=0; 57 | PNODE temp=head; 58 | while(temp!=NULL) 59 | { 60 | ct++; 61 | temp=temp->next; 62 | } 63 | return ct; 64 | } 65 | /////////////////////////////////////////////////////////////////////////////////// 66 | //Display entire Linked List 67 | void DoublyLinearLL::DisplayDLL() 68 | { 69 | PNODE temp=head; 70 | while(temp!=NULL) 71 | { 72 | cout<data<<" "; 73 | temp=temp->next; 74 | } 75 | } 76 | /////////////////////////////////////////////////////////////////////////////////// 77 | //Inserting element at the beginning of Linked List 78 | void DoublyLinearLL::InsertFirst(int n) 79 | { 80 | PNODE newn=new node; 81 | newn->data=n; 82 | newn->next=NULL; 83 | newn->prev=NULL; 84 | if(head==NULL) 85 | { 86 | head=newn; 87 | } 88 | else 89 | { 90 | newn->next=head; 91 | head->prev=newn; 92 | head=newn; 93 | } 94 | } 95 | /////////////////////////////////////////////////////////////////////////////////// 96 | //Inserting element at the end of Linked List 97 | void DoublyLinearLL::InsertLast(int n) 98 | { 99 | PNODE temp=head; 100 | PNODE newn=new node; 101 | newn->data=n; 102 | newn->next=NULL; 103 | newn->prev=NULL; 104 | 105 | if(head==NULL) 106 | { 107 | head=newn; 108 | } 109 | else 110 | { 111 | while(temp->next!=NULL) 112 | { 113 | temp=temp->next; 114 | } 115 | temp->next=newn; 116 | temp->next->prev=temp; 117 | } 118 | } 119 | /////////////////////////////////////////////////////////////////////////////////// 120 | //Inserting element at desired Position in the Linked List 121 | void DoublyLinearLL::InsertAtPos(int pos,int n) 122 | { 123 | int tot=Count(); 124 | if(pos<1 || pos>tot+1) 125 | { 126 | cout<<"\nPosition invalid (element cannot be inserted"; 127 | return; 128 | } 129 | else if(pos==1) 130 | { 131 | //To insert element at beginning 132 | InsertFirst(n); 133 | } 134 | else if(pos==tot+1) 135 | { 136 | //To insert element at end 137 | InsertLast(n); 138 | } 139 | else 140 | { 141 | PNODE temp=head; 142 | PNODE newn=new node; 143 | newn->next=NULL; 144 | newn->data=n; 145 | for(int i=1;inext; 148 | } 149 | newn->next=temp; 150 | newn->prev=temp->prev; 151 | temp->prev->next=newn; 152 | temp->prev=newn; 153 | } 154 | } 155 | /////////////////////////////////////////////////////////////////////////////////// 156 | //Delete first element of Linked List 157 | void DoublyLinearLL::DeleteFirst() 158 | { 159 | if(head==NULL) 160 | { 161 | cout<<"\nNothing to delete"; 162 | return; 163 | } 164 | else 165 | { 166 | PNODE temp=head; 167 | temp->next->prev=NULL; 168 | head=head->next; 169 | delete temp; 170 | } 171 | } 172 | /////////////////////////////////////////////////////////////////////////////////// 173 | //Delete last element from the Linked List 174 | void DoublyLinearLL::DeleteLast() 175 | { 176 | if(head==NULL) 177 | { 178 | cout<<"\nNothing to delete\n"; 179 | return; 180 | } 181 | else if(head->next==NULL) 182 | { 183 | delete head; 184 | head=NULL; 185 | } 186 | else 187 | { 188 | PNODE temp=head; 189 | while(temp->next!=NULL) 190 | { 191 | temp=temp->next; 192 | } 193 | temp->prev->next=NULL; 194 | delete temp; 195 | } 196 | } 197 | /////////////////////////////////////////////////////////////////////////////////// 198 | //Delete element from desired position in the Linked List 199 | void DoublyLinearLL::DeleteAtPos(int pos) 200 | { 201 | int tot=Count(); 202 | if(head==NULL) 203 | { 204 | cout<<"\nNothing to delete\n"; 205 | return; 206 | } 207 | if(pos<1 || pos>tot) 208 | { 209 | cout<<"\nPosition invalid\n"; 210 | } 211 | else if(pos==1) 212 | { 213 | DeleteFirst(); 214 | } 215 | else if(pos==tot) 216 | { 217 | DeleteLast(); 218 | } 219 | else 220 | { 221 | PNODE temp=head; 222 | PNODE curr=NULL; 223 | for(int i=1;inext; 226 | } 227 | temp->next->prev=temp->prev; 228 | temp->prev->next=temp->next; 229 | delete temp; 230 | } 231 | } 232 | /////////////////////////////////////////////////////////////////////////////////// 233 | //Destructor: to deallocate the used memory 234 | DoublyLinearLL::~DoublyLinearLL() 235 | { 236 | PNODE temp=head; 237 | if(head==NULL) 238 | return; 239 | else if(head!=NULL) 240 | { 241 | while(head!=NULL) 242 | { 243 | head=head->next; 244 | delete temp; 245 | temp=head; 246 | } 247 | } 248 | } 249 | /////////////////////////////////////////////////////////////////////////////////// 250 | //main function of the program 251 | /////////////////////////////////////////////////////////////////////////////////// 252 | int main() 253 | { 254 | DoublyLinearLL obj; 255 | 256 | //Here one can opt for menu driven approach also! 257 | obj.InsertFirst(30); 258 | obj.DisplayDLL();cout<<"\n"; 259 | obj.InsertFirst(20); 260 | obj.DisplayDLL();cout<<"\n"; 261 | obj.InsertFirst(10); 262 | obj.DisplayDLL(); 263 | cout<<"\nSuccessfully inserted element from beginning"; 264 | cout<<"Total number of elements "< 9 | using namespace std; 10 | 11 | /////////////////////////////////////////////////////////////////////////////////// 12 | // Slightly different approach ,with 'void' return type // 13 | /////////////////////////////////////////////////////////////////////////////////// 14 | 15 | typedef struct node 16 | { 17 | int data; 18 | struct node* next; 19 | }NODE,*PNODE; 20 | /////////////////////////////////////////////////////////////////////////////////// 21 | 22 | class SinglyCircularLL 23 | { 24 | PNODE head,tail; //maintaining two pointers 25 | //there is no as such termination in CLL unlike linear linkedlist 26 | int ct; 27 | public: 28 | SinglyCircularLL(); //constructor 29 | ~SinglyCircularLL(); //To deallocate the used memory 30 | 31 | void InsertFirst(int); 32 | void InsertLast(int); 33 | void InsertAtPos(int,int); 34 | 35 | void DeleteFirst(); 36 | void DeleteLast(); 37 | void DeleteAtPos(int); 38 | 39 | void DisplayCLL(); //to Display the Linked List 40 | int Count(); //Display total number of nodes present in Linked List 41 | }; 42 | /////////////////////////////////////////////////////////////////////////////////// 43 | //Initializing memory 44 | SinglyCircularLL::SinglyCircularLL() 45 | { 46 | head=tail=NULL; 47 | ct=0; 48 | } 49 | /////////////////////////////////////////////////////////////////////////////////// 50 | //To get total number of nodes/elements present in the Linked List 51 | int SinglyCircularLL::Count() 52 | { 53 | ct=0; 54 | PNODE temp=head; 55 | while(temp->next!=head) 56 | { 57 | ct++; 58 | temp=temp->next; 59 | } 60 | ct++; 61 | return ct; 62 | } 63 | /////////////////////////////////////////////////////////////////////////////////// 64 | //Display entire Linked List 65 | void SinglyCircularLL::DisplayCLL() 66 | { 67 | PNODE temp=head; 68 | while(temp->next!=head) 69 | { 70 | cout<data<<" "; 71 | temp=temp->next; 72 | } 73 | cout<data<<" "; 74 | } 75 | /////////////////////////////////////////////////////////////////////////////////// 76 | //Inserting element at the beginning of Linked List 77 | void SinglyCircularLL::InsertFirst(int n) 78 | { 79 | PNODE temp=head; 80 | PNODE newn=new node; 81 | newn->data=n; 82 | newn->next=NULL; 83 | 84 | //Empty linked list 85 | if(head==NULL && tail==NULL) 86 | { 87 | head=newn; 88 | tail=newn; 89 | }else 90 | { 91 | newn->next=head; 92 | head=newn; 93 | } 94 | tail->next=head; 95 | } 96 | /////////////////////////////////////////////////////////////////////////////////// 97 | //Inserting element at the end of Linked List 98 | void SinglyCircularLL::InsertLast(int n) 99 | { 100 | PNODE temp=head; 101 | PNODE newn=new node; 102 | newn->data=n; 103 | newn->next=NULL; 104 | if(head==NULL && tail==NULL) 105 | { 106 | head=newn; 107 | tail=newn; 108 | } 109 | else 110 | { 111 | tail->next=newn; 112 | tail=tail->next; 113 | } 114 | tail->next=head; 115 | 116 | } 117 | /////////////////////////////////////////////////////////////////////////////////// 118 | //Inserting element at desired Position in the Linked List 119 | void SinglyCircularLL::InsertAtPos(int pos,int n) 120 | { 121 | int tot=Count(); 122 | if(pos<1 || pos>tot+1) 123 | { 124 | cout<<"\nPosition invalid (element cannot be inserted"; 125 | return; 126 | } 127 | else if(pos==1) 128 | { 129 | //To insert element at beginning 130 | InsertFirst(n); 131 | } 132 | else if(pos==tot+1) 133 | { 134 | //To insert element at end 135 | InsertLast(n); 136 | } 137 | else 138 | { 139 | PNODE temp=head; 140 | PNODE newn=new node; 141 | newn->next=NULL; 142 | newn->data=n; 143 | for(int i=1;inext; 146 | } 147 | newn->next=temp->next; 148 | temp->next=newn; 149 | } 150 | } 151 | /////////////////////////////////////////////////////////////////////////////////// 152 | //Delete first element of Linked List 153 | void SinglyCircularLL::DeleteFirst() 154 | { 155 | //Empty Linked list 156 | if(head==NULL && tail==NULL) 157 | { 158 | cout<<"\nNothing to delete"; 159 | return; 160 | } 161 | 162 | //Linked list containing only one element 163 | else if(head==tail) 164 | { 165 | delete head; 166 | head=tail=NULL; 167 | } 168 | //Multiple nodes 169 | else 170 | { 171 | head=head->next; 172 | delete tail->next; 173 | tail->next=head; 174 | } 175 | } 176 | /////////////////////////////////////////////////////////////////////////////////// 177 | //Delete last element from the Linked List 178 | void SinglyCircularLL::DeleteLast() 179 | { 180 | //Empty Linked list 181 | if(head==NULL && tail==NULL) 182 | { 183 | cout<<"\nNothing to delete"; 184 | return; 185 | } 186 | 187 | //Linked list containing only one element 188 | else if(head==tail) 189 | { 190 | delete tail; 191 | head=tail=NULL; 192 | } 193 | //Multiple nodes 194 | else 195 | { 196 | PNODE temp=head; 197 | while(temp->next!=tail) 198 | { 199 | temp=temp->next; 200 | } 201 | delete tail; 202 | tail=temp; 203 | tail->next=head; 204 | } 205 | } 206 | /////////////////////////////////////////////////////////////////////////////////// 207 | //Delete element from desired position in the Linked List 208 | void SinglyCircularLL::DeleteAtPos(int pos) 209 | { 210 | int tot=Count(); 211 | if(head==NULL && tail==NULL) 212 | { 213 | cout<<"\nNothing to delete\n"; 214 | return; 215 | } 216 | if(pos<1 || pos>tot) 217 | { 218 | cout<<"\nPosition invalid\n"; 219 | } 220 | else if(pos==1) 221 | { 222 | DeleteFirst(); 223 | } 224 | else if(pos==tot) 225 | { 226 | DeleteLast(); 227 | } 228 | else 229 | { 230 | PNODE temp=head; 231 | PNODE curr=NULL; 232 | for(int i=1;inext; 235 | } 236 | curr=temp->next; 237 | temp->next=curr->next; 238 | delete curr; 239 | } 240 | } 241 | /////////////////////////////////////////////////////////////////////////////////// 242 | //Destructor: to deallocate the used memory 243 | SinglyCircularLL::~SinglyCircularLL() 244 | { 245 | PNODE temp=head; 246 | if(head==NULL && tail==NULL) 247 | return; 248 | else 249 | { 250 | while(head!=tail) 251 | { 252 | head=head->next; 253 | delete temp; 254 | temp=head; 255 | } 256 | } 257 | } 258 | /////////////////////////////////////////////////////////////////////////////////// 259 | //main function of the program 260 | /////////////////////////////////////////////////////////////////////////////////// 261 | int main() 262 | { 263 | SinglyCircularLL obj; 264 | 265 | //Here one can opt for menu driven approach also! 266 | obj.InsertFirst(30); 267 | obj.DisplayCLL();cout<<"\n"; 268 | obj.InsertFirst(20); 269 | obj.DisplayCLL();cout<<"\n"; 270 | obj.InsertFirst(10); 271 | obj.DisplayCLL(); 272 | cout<<"\nSuccessfully inserted element from beginning"; 273 | cout<<"Total number of elements "< 10 | using namespace std; 11 | 12 | /////////////////////////////////////////////////////////////////////////////////// 13 | // Slightly different approach ,with 'void' return type // 14 | // Doubly Circular linked list is maintained using two pointers (head and tail) // 15 | // Due to which it is possible to traverse in reverse as well as forward direction.// 16 | // There no as such termination ,because last node does not contain NULL value // 17 | /////////////////////////////////////////////////////////////////////////////////// 18 | 19 | typedef struct node 20 | { 21 | int data; 22 | struct node* next; 23 | struct node* prev; 24 | }NODE,*PNODE; 25 | /////////////////////////////////////////////////////////////////////////////////// 26 | 27 | class DoublyCircularLL 28 | { 29 | PNODE head,tail; //maintaining two pointers 30 | //there is no as such termination in CLL unlike linear linkedlist 31 | int ct; 32 | public: 33 | DoublyCircularLL(); //constructor 34 | ~DoublyCircularLL(); //To deallocate the used memory 35 | 36 | void InsertFirst(int); 37 | void InsertLast(int); 38 | void InsertAtPos(int,int); 39 | 40 | void DeleteFirst(); 41 | void DeleteLast(); 42 | void DeleteAtPos(int); 43 | 44 | void DisplayCLL(); //to Display the Linked List 45 | int Count(); //Display total number of nodes present in Linked List 46 | }; 47 | /////////////////////////////////////////////////////////////////////////////////// 48 | //Initializing memory 49 | DoublyCircularLL::DoublyCircularLL() 50 | { 51 | head=tail=NULL; 52 | ct=0; 53 | } 54 | /////////////////////////////////////////////////////////////////////////////////// 55 | //To get total number of nodes/elements present in the Linked List 56 | int DoublyCircularLL::Count() 57 | { 58 | //do-while loop can also be used here 59 | ct=0; 60 | PNODE temp=head; 61 | while(temp->next!=head) 62 | { 63 | ct++; 64 | temp=temp->next; 65 | } 66 | ct++; 67 | return ct; 68 | } 69 | /////////////////////////////////////////////////////////////////////////////////// 70 | //Display entire Linked List 71 | void DoublyCircularLL::DisplayCLL() 72 | { 73 | PNODE temp=head; 74 | while(temp->next!=head) 75 | { 76 | cout<data<<" "; 77 | temp=temp->next; 78 | } 79 | cout<data<<" "; 80 | } 81 | /////////////////////////////////////////////////////////////////////////////////// 82 | //Inserting element at the beginning of Linked List 83 | void DoublyCircularLL::InsertFirst(int n) 84 | { 85 | PNODE temp=head; 86 | PNODE newn=new node; 87 | newn->data=n; 88 | newn->next=NULL; 89 | newn->prev=NULL; 90 | 91 | //Empty linked list 92 | if(head==NULL && tail==NULL) 93 | { 94 | head=newn; 95 | tail=newn; 96 | } 97 | //multiple nodes 98 | else 99 | { 100 | newn->next=head; 101 | newn->prev=tail; 102 | head->prev=newn; 103 | head=newn; 104 | } 105 | tail->next=head; 106 | } 107 | /////////////////////////////////////////////////////////////////////////////////// 108 | //Inserting element at the end of Linked List 109 | void DoublyCircularLL::InsertLast(int n) 110 | { 111 | PNODE temp=head; 112 | PNODE newn=new node; 113 | newn->data=n; 114 | newn->next=NULL; 115 | if(head==NULL && tail==NULL) 116 | { 117 | head=newn; 118 | tail=newn; 119 | } 120 | else 121 | { 122 | newn->prev=tail; 123 | tail->next=newn; 124 | tail=newn; 125 | } 126 | tail->next=head; 127 | } 128 | /////////////////////////////////////////////////////////////////////////////////// 129 | //Inserting element at desired Position in the Linked List 130 | void DoublyCircularLL::InsertAtPos(int pos,int n) 131 | { 132 | int tot=Count(); 133 | if(pos<1 || pos>tot+1) 134 | { 135 | cout<<"\nPosition invalid (element cannot be inserted"; 136 | return; 137 | } 138 | else if(pos==1) 139 | { 140 | //To insert element at beginning 141 | InsertFirst(n); 142 | } 143 | else if(pos==tot+1) 144 | { 145 | //To insert element at end 146 | InsertLast(n); 147 | } 148 | else 149 | { 150 | PNODE temp=head; 151 | PNODE newn=new node; 152 | newn->next=NULL; 153 | newn->data=n; 154 | for(int i=1;inext; 157 | } 158 | newn->next=temp; 159 | newn->prev=temp->prev; 160 | temp->prev->next=newn; 161 | temp->prev=newn; 162 | } 163 | } 164 | /////////////////////////////////////////////////////////////////////////////////// 165 | //Delete first element of Linked List 166 | void DoublyCircularLL::DeleteFirst() 167 | { 168 | //Empty Linked list 169 | if(head==NULL && tail==NULL) 170 | { 171 | cout<<"\nNothing to delete"; 172 | return; 173 | } 174 | 175 | //Linked list containing only one element 176 | else if(head==tail) 177 | { 178 | delete head; 179 | head=tail=NULL; 180 | } 181 | //Multiple nodes 182 | else 183 | { 184 | head=head->next; 185 | delete tail->next; 186 | tail->next=head; 187 | head->prev=tail; 188 | } 189 | } 190 | /////////////////////////////////////////////////////////////////////////////////// 191 | //Delete last element from the Linked List 192 | void DoublyCircularLL::DeleteLast() 193 | { 194 | //Empty Linked list 195 | if(head==NULL && tail==NULL) 196 | { 197 | cout<<"\nNothing to delete"; 198 | return; 199 | } 200 | 201 | //Linked list containing only one element 202 | else if(head==tail) 203 | { 204 | delete tail; 205 | head=tail=NULL; 206 | } 207 | //Multiple nodes 208 | else 209 | { 210 | PNODE temp=head; 211 | while(temp->next!=tail) 212 | { 213 | temp=temp->next; 214 | } 215 | temp->next=head; 216 | tail=temp; 217 | head->prev=tail; 218 | } 219 | } 220 | /////////////////////////////////////////////////////////////////////////////////// 221 | //Delete element from desired position in the Linked List 222 | void DoublyCircularLL::DeleteAtPos(int pos) 223 | { 224 | int tot=Count(); 225 | if(head==NULL && tail==NULL) 226 | { 227 | cout<<"\nNothing to delete\n"; 228 | return; 229 | } 230 | if(pos<1 || pos>tot) 231 | { 232 | cout<<"\nPosition invalid\n"; 233 | } 234 | else if(pos==1) 235 | { 236 | DeleteFirst(); 237 | } 238 | else if(pos==tot) 239 | { 240 | DeleteLast(); 241 | } 242 | else 243 | { 244 | PNODE temp=head; 245 | PNODE curr=NULL; 246 | for(int i=1;inext; 249 | } 250 | temp->next->prev=temp->prev; 251 | temp->prev->next=temp->next; 252 | delete temp; 253 | } 254 | } 255 | /////////////////////////////////////////////////////////////////////////////////// 256 | //Destructor: to deallocate the used memory 257 | DoublyCircularLL::~DoublyCircularLL() 258 | { 259 | PNODE temp=head; 260 | if(head==NULL && tail==NULL) 261 | return; 262 | else 263 | { 264 | while(head!=tail) 265 | { 266 | head=head->next; 267 | delete temp; 268 | temp=head; 269 | } 270 | } 271 | } 272 | /////////////////////////////////////////////////////////////////////////////////// 273 | //main function of the program 274 | /////////////////////////////////////////////////////////////////////////////////// 275 | int main() 276 | { 277 | DoublyCircularLL obj; 278 | 279 | //Here one can opt for menu driven approach also! 280 | obj.InsertFirst(30); 281 | obj.DisplayCLL();cout<<"\n"; 282 | obj.InsertFirst(20); 283 | obj.DisplayCLL();cout<<"\n"; 284 | obj.InsertFirst(10); 285 | obj.DisplayCLL(); 286 | cout<<"\nSuccessfully inserted element from beginning"; 287 | cout<<"Total number of elements "<