From f658f2737f33bc8bc4da1bf41c9dec63449d26f5 Mon Sep 17 00:00:00 2001 From: Kshitiz Sharma Date: Tue, 6 Feb 2024 18:12:21 +0530 Subject: [PATCH] new commit --- .../KokoEatingBananas.cpp | 64 +- .../KthPositiveNumber.cpp | 28 +- LinearSearch.cpp => Arrays/LinearSearch.cpp | 62 +- .../MaximumProductSubarray.cpp | 52 +- .../MedianOf2SortedArray.java | 100 +- .../MedianOf2SortedArrays.cpp | 46 +- PeakElement.cpp => Arrays/PeakElement.cpp | 42 +- .../SearchinRotatedArray1.cpp | 56 +- .../SearchinRotatedArray2.cpp | 66 +- .../SegregateEven&oddLL.cpp | 66 +- .../SingleEleInSortedArray.cpp | 18 +- .../SmallestDivisor.cpp | 52 +- .../Unionof2sortedArray.cpp | 100 +- .../maximumSubarray.cpp | 52 +- Articulation.cpp => Graphs/Articulation.cpp | 172 +-- Articulation.exe => Graphs/Articulation.exe | Bin .../Dijkstra's_algorithm.cpp | 154 +-- Graph.cpp => Graphs/Graph.cpp | 104 +- Graph.exe => Graphs/Graph.exe | Bin PathinDAG.cpp => Graphs/PathinDAG.cpp | 190 +-- PathinDAG.exe => Graphs/PathinDAG.exe | Bin kosaraju.cpp => Graphs/kosaraju.cpp | 112 +- knapsnack.cpp => Greedy/knapsnack.cpp | 56 +- IntersextionOf2Array.cpp | 21 - .../CircularLinkedList.cpp | 396 +++---- .../CircularLinkedList.exe | Bin .../DeleteMiddleNodeofLL.cpp | 48 +- .../DoublyLinkedList.cpp | 352 +++--- .../DoublyLinkedList.exe | Bin FlattenLL.cpp => Linked Lists/FlattenLL.cpp | 54 +- .../Insertion-deletion.cpp | 262 ++--- .../IntersectionYshapedLL.cpp | 50 +- .../LinkedListPractice.exe | Bin .../LinkedListReversal.cpp | 44 +- Linkedlist.cpp => Linked Lists/Linkedlist.cpp | 1040 ++++++++--------- Linkedlist.exe => Linked Lists/Linkedlist.exe | Bin .../OccurenceOfKeyinDLL.cpp | 100 +- .../PalindromicLL.cpp | 88 +- ReverseDLL.cpp => Linked Lists/ReverseDLL.cpp | 68 +- RotateLL.cpp => Linked Lists/RotateLL.cpp | 60 +- Codechef.cpp => Misc/Codechef.cpp | 58 +- Codechef.exe => Misc/Codechef.exe | Bin Heap.cpp => Misc/Heap.cpp | 314 ++--- Heap.exe => Misc/Heap.exe | Bin Intersection.cpp => Misc/Intersection.cpp | 40 +- MaxOf2nums.cpp => Misc/MaxOf2nums.cpp | 26 +- MaxOf2nums.exe => Misc/MaxOf2nums.exe | Bin SudokuSolver.cpp => Misc/SudokuSolver.cpp | 154 +-- Tom&Jerry.cpp => Misc/Tom&Jerry.cpp | 32 +- Trie.cpp => Misc/Trie.cpp | 178 +-- Trie.exe => Misc/Trie.exe | Bin .../QueueUsingArray.java | 116 +- QueueusingLL.cpp => Queue/QueueusingLL.cpp | 150 +-- .../Celebrity problem.cpp | 127 +- RemoveBalls.cpp => Stack/RemoveBalls.cpp | 0 .../StackQuestions.cpp | 44 +- .../StackQuestions.exe | Bin .../StackUsingArray.cpp | 146 +-- stack.cpp => Stack/stack.cpp | 410 +++---- stack.exe => Stack/stack.exe | Bin numbertoWords.c => Strings/numbertoWords.c | 464 ++++---- BST.cpp => Trees/BST.cpp | 348 +++--- BST.exe => Trees/BST.exe | Bin BinaryTree.cpp => Trees/BinaryTree.cpp | 378 +++--- BinaryTree.exe => Trees/BinaryTree.exe | Bin BinaryTrees.cpp => Trees/BinaryTrees.cpp | 370 +++--- BinaryTrees.exe => Trees/BinaryTrees.exe | Bin LCAinBST.cpp => Trees/LCAinBST.cpp | 84 +- LargestBST.cpp => Trees/LargestBST.cpp | 80 +- .../MaximumPathSum.cpp | 32 +- PreorderToBST.cpp => Trees/PreorderToBST.cpp | 68 +- TreePractice.cpp => Trees/TreePractice.cpp | 144 +-- TreePractice.exe => Trees/TreePractice.exe | Bin trees.cpp => Trees/trees.cpp | 366 +++--- trees.exe => Trees/trees.exe | Bin tempCodeRunnerFile.cpp | 2 - 76 files changed, 4143 insertions(+), 4163 deletions(-) rename KokoEatingBananas.cpp => Arrays/KokoEatingBananas.cpp (95%) rename KthPositiveNumber.cpp => Arrays/KthPositiveNumber.cpp (96%) rename LinearSearch.cpp => Arrays/LinearSearch.cpp (95%) rename MaximumProductSubarray.cpp => Arrays/MaximumProductSubarray.cpp (95%) rename MedianOf2SortedArray.java => Arrays/MedianOf2SortedArray.java (92%) rename MedianOf2SortedArrays.cpp => Arrays/MedianOf2SortedArrays.cpp (96%) rename PeakElement.cpp => Arrays/PeakElement.cpp (94%) rename SearchinRotatedArray1.cpp => Arrays/SearchinRotatedArray1.cpp (96%) rename SearchinRotatedArray2.cpp => Arrays/SearchinRotatedArray2.cpp (95%) rename SegregateEven&oddLL.cpp => Arrays/SegregateEven&oddLL.cpp (95%) rename SingleEleInSortedArray.cpp => Arrays/SingleEleInSortedArray.cpp (95%) rename SmallestDivisor.cpp => Arrays/SmallestDivisor.cpp (95%) rename Unionof2sortedArray.cpp => Arrays/Unionof2sortedArray.cpp (92%) rename maximumSubarray.cpp => Arrays/maximumSubarray.cpp (94%) rename Articulation.cpp => Graphs/Articulation.cpp (95%) rename Articulation.exe => Graphs/Articulation.exe (100%) rename Dijkstra's_algorithm.cpp => Graphs/Dijkstra's_algorithm.cpp (96%) rename Graph.cpp => Graphs/Graph.cpp (95%) rename Graph.exe => Graphs/Graph.exe (100%) rename PathinDAG.cpp => Graphs/PathinDAG.cpp (95%) rename PathinDAG.exe => Graphs/PathinDAG.exe (100%) rename kosaraju.cpp => Graphs/kosaraju.cpp (95%) rename knapsnack.cpp => Greedy/knapsnack.cpp (95%) delete mode 100644 IntersextionOf2Array.cpp rename CircularLinkedList.cpp => Linked Lists/CircularLinkedList.cpp (95%) rename CircularLinkedList.exe => Linked Lists/CircularLinkedList.exe (100%) rename DeleteMiddleNodeofLL.cpp => Linked Lists/DeleteMiddleNodeofLL.cpp (95%) rename DoublyLinkedList.cpp => Linked Lists/DoublyLinkedList.cpp (95%) rename DoublyLinkedList.exe => Linked Lists/DoublyLinkedList.exe (100%) rename FlattenLL.cpp => Linked Lists/FlattenLL.cpp (95%) rename Insertion-deletion.cpp => Linked Lists/Insertion-deletion.cpp (94%) rename IntersectionYshapedLL.cpp => Linked Lists/IntersectionYshapedLL.cpp (96%) rename LinkedListPractice.exe => Linked Lists/LinkedListPractice.exe (100%) rename LinkedListReversal.cpp => Linked Lists/LinkedListReversal.cpp (94%) rename Linkedlist.cpp => Linked Lists/Linkedlist.cpp (95%) rename Linkedlist.exe => Linked Lists/Linkedlist.exe (100%) rename OccurenceOfKeyinDLL.cpp => Linked Lists/OccurenceOfKeyinDLL.cpp (96%) rename PalindromicLL.cpp => Linked Lists/PalindromicLL.cpp (96%) rename ReverseDLL.cpp => Linked Lists/ReverseDLL.cpp (95%) rename RotateLL.cpp => Linked Lists/RotateLL.cpp (95%) rename Codechef.cpp => Misc/Codechef.cpp (94%) rename Codechef.exe => Misc/Codechef.exe (100%) rename Heap.cpp => Misc/Heap.cpp (95%) rename Heap.exe => Misc/Heap.exe (100%) rename Intersection.cpp => Misc/Intersection.cpp (95%) rename MaxOf2nums.cpp => Misc/MaxOf2nums.cpp (94%) rename MaxOf2nums.exe => Misc/MaxOf2nums.exe (100%) rename SudokuSolver.cpp => Misc/SudokuSolver.cpp (96%) rename Tom&Jerry.cpp => Misc/Tom&Jerry.cpp (92%) rename Trie.cpp => Misc/Trie.cpp (95%) rename Trie.exe => Misc/Trie.exe (100%) rename QueueUsingArray.java => Queue/QueueUsingArray.java (95%) rename QueueusingLL.cpp => Queue/QueueusingLL.cpp (96%) rename Celebrity problem.cpp => Stack/Celebrity problem.cpp (92%) rename RemoveBalls.cpp => Stack/RemoveBalls.cpp (100%) rename StackQuestions.cpp => Stack/StackQuestions.cpp (94%) rename StackQuestions.exe => Stack/StackQuestions.exe (100%) rename StackUsingArray.cpp => Stack/StackUsingArray.cpp (93%) rename stack.cpp => Stack/stack.cpp (94%) rename stack.exe => Stack/stack.exe (100%) rename numbertoWords.c => Strings/numbertoWords.c (94%) rename BST.cpp => Trees/BST.cpp (95%) rename BST.exe => Trees/BST.exe (100%) rename BinaryTree.cpp => Trees/BinaryTree.cpp (95%) rename BinaryTree.exe => Trees/BinaryTree.exe (100%) rename BinaryTrees.cpp => Trees/BinaryTrees.cpp (95%) rename BinaryTrees.exe => Trees/BinaryTrees.exe (100%) rename LCAinBST.cpp => Trees/LCAinBST.cpp (95%) rename LargestBST.cpp => Trees/LargestBST.cpp (95%) rename MaximumPathSum.cpp => Trees/MaximumPathSum.cpp (96%) rename PreorderToBST.cpp => Trees/PreorderToBST.cpp (96%) rename TreePractice.cpp => Trees/TreePractice.cpp (95%) rename TreePractice.exe => Trees/TreePractice.exe (100%) rename trees.cpp => Trees/trees.cpp (95%) rename trees.exe => Trees/trees.exe (100%) delete mode 100644 tempCodeRunnerFile.cpp diff --git a/KokoEatingBananas.cpp b/Arrays/KokoEatingBananas.cpp similarity index 95% rename from KokoEatingBananas.cpp rename to Arrays/KokoEatingBananas.cpp index e739d33..7c3df93 100644 --- a/KokoEatingBananas.cpp +++ b/Arrays/KokoEatingBananas.cpp @@ -1,33 +1,33 @@ -class solution{ -public: -bool solveKoko(vector &piles,int H,int mid){ -int hours=0; - for(auto i:piles){ - int d=i/mid; - hours+=d; - if(i%mid!=0){ - hours++; - } - } - if(hours<=H){ - return true; - } - else{ - return false; - } -} -int Solve(int N, vector& piles, int H) { - // Code here - int s=1,e=INT_MAX; - while(s<=e){ - int mid=s+(e-s)/2; - if(solveKoko(piles,H,mid)){ - e=mid-1; - } - else{ - s=mid+1; - } - } - return s; - } +class solution{ +public: +bool solveKoko(vector &piles,int H,int mid){ +int hours=0; + for(auto i:piles){ + int d=i/mid; + hours+=d; + if(i%mid!=0){ + hours++; + } + } + if(hours<=H){ + return true; + } + else{ + return false; + } +} +int Solve(int N, vector& piles, int H) { + // Code here + int s=1,e=INT_MAX; + while(s<=e){ + int mid=s+(e-s)/2; + if(solveKoko(piles,H,mid)){ + e=mid-1; + } + else{ + s=mid+1; + } + } + return s; + } }; \ No newline at end of file diff --git a/KthPositiveNumber.cpp b/Arrays/KthPositiveNumber.cpp similarity index 96% rename from KthPositiveNumber.cpp rename to Arrays/KthPositiveNumber.cpp index 1bfb8f0..5fe0c79 100644 --- a/KthPositiveNumber.cpp +++ b/Arrays/KthPositiveNumber.cpp @@ -1,15 +1,15 @@ -class Solution { -public: - int findKthPositive(vector& arr, int k) { - int left = 0, right = arr.size() - 1; - while (left <= right) { - int mid = left + (right - left) / 2; - if (arr[mid] - mid - 1 < k) { - left = mid + 1; - } else { - right = mid - 1; - } - } - return left + k; - } +class Solution { +public: + int findKthPositive(vector& arr, int k) { + int left = 0, right = arr.size() - 1; + while (left <= right) { + int mid = left + (right - left) / 2; + if (arr[mid] - mid - 1 < k) { + left = mid + 1; + } else { + right = mid - 1; + } + } + return left + k; + } }; \ No newline at end of file diff --git a/LinearSearch.cpp b/Arrays/LinearSearch.cpp similarity index 95% rename from LinearSearch.cpp rename to Arrays/LinearSearch.cpp index 456390e..a8e9366 100644 --- a/LinearSearch.cpp +++ b/Arrays/LinearSearch.cpp @@ -1,31 +1,31 @@ -#include -using namespace std; - -bool search(int arr[], int size, int key) -{ - for (int i = 0; i < size; i++) - { - if (arr[i] == key) - { - return 1; - } - } - return 0; -} -int main() -{ - - int arr[10] = {10, 2, 245, 7, 56, 56, 542, 3, 12, 45}; - // Whether 1 is present or not? - cout << "Enter the key" << endl; - int key; - cin >> key; - bool found = search(arr, 10, key); - if (found) - { - cout << "Key is present" << endl; - } - else - { - cout << "Key is absent" << endl; - } +#include +using namespace std; + +bool search(int arr[], int size, int key) +{ + for (int i = 0; i < size; i++) + { + if (arr[i] == key) + { + return 1; + } + } + return 0; +} +int main() +{ + + int arr[10] = {10, 2, 245, 7, 56, 56, 542, 3, 12, 45}; + // Whether 1 is present or not? + cout << "Enter the key" << endl; + int key; + cin >> key; + bool found = search(arr, 10, key); + if (found) + { + cout << "Key is present" << endl; + } + else + { + cout << "Key is absent" << endl; + } diff --git a/MaximumProductSubarray.cpp b/Arrays/MaximumProductSubarray.cpp similarity index 95% rename from MaximumProductSubarray.cpp rename to Arrays/MaximumProductSubarray.cpp index 6d5fff6..adf0afb 100644 --- a/MaximumProductSubarray.cpp +++ b/Arrays/MaximumProductSubarray.cpp @@ -1,27 +1,27 @@ -class Solution { -public: -int fun(int mid, vector& nums){ - int ans = 0; - for(int i=0;i& nums, int threshold) { - int lo = 1, hi = 1e9, ans = 0; - - while(lo <= hi){ - int mid = (lo + hi)/2; - if(fun(mid, nums) <= threshold){ - ans = mid; - hi = mid - 1; - } - else{ - lo = mid + 1; - } - } - - return ans; - } +class Solution { +public: +int fun(int mid, vector& nums){ + int ans = 0; + for(int i=0;i& nums, int threshold) { + int lo = 1, hi = 1e9, ans = 0; + + while(lo <= hi){ + int mid = (lo + hi)/2; + if(fun(mid, nums) <= threshold){ + ans = mid; + hi = mid - 1; + } + else{ + lo = mid + 1; + } + } + + return ans; + } }; \ No newline at end of file diff --git a/MedianOf2SortedArray.java b/Arrays/MedianOf2SortedArray.java similarity index 92% rename from MedianOf2SortedArray.java rename to Arrays/MedianOf2SortedArray.java index dec6557..e33dcd7 100644 --- a/MedianOf2SortedArray.java +++ b/Arrays/MedianOf2SortedArray.java @@ -1,51 +1,51 @@ -class GFG - -{ - - static double medianOfArrays(int n, int m, int a[], int b[]) - - { - - int c[] = new int[m +n]; - - int s=0; - - for(int i=0;i& nums1, vector& nums2) { - vectorans; - for(int i=0; i& nums1, vector& nums2) { + vectorans; + for(int i=0; i& nums) { - int s = 0; - int e = nums.size()-1; - // int ans=0; - int mid = s + (e - s) / 2; - while (s < e) - { - if (nums[mid] < nums[mid + 1]) - { - s = mid + 1; - } - else - { - e = mid; - } - mid = s + (e - s) / 2; - } - return s; - } +class Solution { +public: + int findPeakElement(vector& nums) { + int s = 0; + int e = nums.size()-1; + // int ans=0; + int mid = s + (e - s) / 2; + while (s < e) + { + if (nums[mid] < nums[mid + 1]) + { + s = mid + 1; + } + else + { + e = mid; + } + mid = s + (e - s) / 2; + } + return s; + } }; \ No newline at end of file diff --git a/SearchinRotatedArray1.cpp b/Arrays/SearchinRotatedArray1.cpp similarity index 96% rename from SearchinRotatedArray1.cpp rename to Arrays/SearchinRotatedArray1.cpp index b7760cd..e08d200 100644 --- a/SearchinRotatedArray1.cpp +++ b/Arrays/SearchinRotatedArray1.cpp @@ -1,29 +1,29 @@ -class Solution { -public: - int search(vector& nums, int target) { - int s=0,e=nums.size()-1; - while(s<=e){ - int mid=s+(e-s)/2; - if(nums[mid]==target){ - return mid; - } - if(nums[s]<=nums[mid]){ - if(target>=nums[s] && target<=nums[mid]){ - e=mid-1; - } - else{ - s=mid+1; - } - } - else{ - if(target>=nums[mid] && target<=nums[e]){ - s=mid+1; - } - else{ - e=mid-1; - } - } - } - return -1; - } +class Solution { +public: + int search(vector& nums, int target) { + int s=0,e=nums.size()-1; + while(s<=e){ + int mid=s+(e-s)/2; + if(nums[mid]==target){ + return mid; + } + if(nums[s]<=nums[mid]){ + if(target>=nums[s] && target<=nums[mid]){ + e=mid-1; + } + else{ + s=mid+1; + } + } + else{ + if(target>=nums[mid] && target<=nums[e]){ + s=mid+1; + } + else{ + e=mid-1; + } + } + } + return -1; + } }; \ No newline at end of file diff --git a/SearchinRotatedArray2.cpp b/Arrays/SearchinRotatedArray2.cpp similarity index 95% rename from SearchinRotatedArray2.cpp rename to Arrays/SearchinRotatedArray2.cpp index 9cf4f32..1817848 100644 --- a/SearchinRotatedArray2.cpp +++ b/Arrays/SearchinRotatedArray2.cpp @@ -1,34 +1,34 @@ - -class Solution{ -bool Search(int N, vector& A, int Key) { - // Code here - int s=0,e=N-1; - while(s<=e){ - int mid=s+(e-s)/2; - if(A[mid]==Key){ - return true; - } - if(A[s]==A[mid] && A[e]==A[mid]){ - s++; - e--; - } - if(A[s]<=A[mid]){ - if(Key>=A[s] && Key<=A[mid]){ - e=mid-1; - } - else{ - s=mid+1; - } - } - else{ - if(Key>=A[mid] && Key<=A[e]){ - s=mid+1; - } - else{ - e=mid-1; - } - } - } - return false; - } + +class Solution{ +bool Search(int N, vector& A, int Key) { + // Code here + int s=0,e=N-1; + while(s<=e){ + int mid=s+(e-s)/2; + if(A[mid]==Key){ + return true; + } + if(A[s]==A[mid] && A[e]==A[mid]){ + s++; + e--; + } + if(A[s]<=A[mid]){ + if(Key>=A[s] && Key<=A[mid]){ + e=mid-1; + } + else{ + s=mid+1; + } + } + else{ + if(Key>=A[mid] && Key<=A[e]){ + s=mid+1; + } + else{ + e=mid-1; + } + } + } + return false; + } }; \ No newline at end of file diff --git a/SegregateEven&oddLL.cpp b/Arrays/SegregateEven&oddLL.cpp similarity index 95% rename from SegregateEven&oddLL.cpp rename to Arrays/SegregateEven&oddLL.cpp index a732095..f948fe1 100644 --- a/SegregateEven&oddLL.cpp +++ b/Arrays/SegregateEven&oddLL.cpp @@ -1,34 +1,34 @@ -class Solution -{ -public: - Node *divide(int N, Node *head) - { - // code here - vector Vodd, Veven; - Node *temp = head; - while (temp != NULL) - { - if (temp->data % 2 == 0) - { - Veven.push_back(temp->data); - } - else - { - Vodd.push_back(temp->data); - } - temp = temp->next; - } - temp = head; - for (int i = 0; i < Veven.size(); i++) - { - temp->data = Veven[i]; - temp = temp->next; - } - for (int i = 0; i < Vodd.size(); i++) - { - temp->data = Vodd[i]; - temp = temp->next; - } - return head; - } +class Solution +{ +public: + Node *divide(int N, Node *head) + { + // code here + vector Vodd, Veven; + Node *temp = head; + while (temp != NULL) + { + if (temp->data % 2 == 0) + { + Veven.push_back(temp->data); + } + else + { + Vodd.push_back(temp->data); + } + temp = temp->next; + } + temp = head; + for (int i = 0; i < Veven.size(); i++) + { + temp->data = Veven[i]; + temp = temp->next; + } + for (int i = 0; i < Vodd.size(); i++) + { + temp->data = Vodd[i]; + temp = temp->next; + } + return head; + } }; \ No newline at end of file diff --git a/SingleEleInSortedArray.cpp b/Arrays/SingleEleInSortedArray.cpp similarity index 95% rename from SingleEleInSortedArray.cpp rename to Arrays/SingleEleInSortedArray.cpp index 3b009d0..026056e 100644 --- a/SingleEleInSortedArray.cpp +++ b/Arrays/SingleEleInSortedArray.cpp @@ -1,10 +1,10 @@ -class Solution { -public: - int singleNonDuplicate(vector& nums) { - int ans=0; - for(int i=0;i& nums) { + int ans=0; + for(int i=0;i& nums){ - int ans = 0; - for(int i=0;i& nums, int threshold) { - int lo = 1, hi = 1e9, ans = 0; - - while(lo <= hi){ - int mid = (lo + hi)/2; - if(fun(mid, nums) <= threshold){ - ans = mid; - hi = mid - 1; - } - else{ - lo = mid + 1; - } - } - - return ans; - } +class Solution { +public: +int fun(int mid, vector& nums){ + int ans = 0; + for(int i=0;i& nums, int threshold) { + int lo = 1, hi = 1e9, ans = 0; + + while(lo <= hi){ + int mid = (lo + hi)/2; + if(fun(mid, nums) <= threshold){ + ans = mid; + hi = mid - 1; + } + else{ + lo = mid + 1; + } + } + + return ans; + } }; \ No newline at end of file diff --git a/Unionof2sortedArray.cpp b/Arrays/Unionof2sortedArray.cpp similarity index 92% rename from Unionof2sortedArray.cpp rename to Arrays/Unionof2sortedArray.cpp index dec6557..e33dcd7 100644 --- a/Unionof2sortedArray.cpp +++ b/Arrays/Unionof2sortedArray.cpp @@ -1,51 +1,51 @@ -class GFG - -{ - - static double medianOfArrays(int n, int m, int a[], int b[]) - - { - - int c[] = new int[m +n]; - - int s=0; - - for(int i=0;i -using namepsace std; - -class Solution -{ -public: - int maxSubArray(vector &nums) - { - - int n = nums.size(); - int ans = nums[0], currsum = nums[0]; - - for (int i = 1; i < n; i++) - { - - if (currsum < 0) - { - currsum = 0; - } - currsum += nums[i]; - - ans = max(ans, currsum); - } - - return ans; - } +#include +using namepsace std; + +class Solution +{ +public: + int maxSubArray(vector &nums) + { + + int n = nums.size(); + int ans = nums[0], currsum = nums[0]; + + for (int i = 1; i < n; i++) + { + + if (currsum < 0) + { + currsum = 0; + } + currsum += nums[i]; + + ans = max(ans, currsum); + } + + return ans; + } }; \ No newline at end of file diff --git a/Articulation.cpp b/Graphs/Articulation.cpp similarity index 95% rename from Articulation.cpp rename to Graphs/Articulation.cpp index 0a2be5f..8702213 100644 --- a/Articulation.cpp +++ b/Graphs/Articulation.cpp @@ -1,87 +1,87 @@ -#include -#include -using namespace std; -void dfs(int node, int parent, vector &disc, vector &low, unordered_map &vis, - unordered_map> &adj, vector &ap, int &timer) -{ - vis[node] = true; - disc[node] = low[node] = timer++; - int child = 0; - for (auto nbr : adj[node]) - { - if (nbr == parent) - { - continue; - } - if (!vis[nbr]) - { - dfs(nbr, node, disc, low, vis, adj, ap, timer); - low[node] = min(low[node], low[nbr]); - // check AP or not - if (low[nbr] >= disc[node] && parent != -1) - { - ap[node] = true; - } - child++; - } - else - { - low[node] = min(low[node], disc[nbr]); - } - } - if (parent == -1 && child > 1) - { - ap[node] = -1; - } -} -int main() -{ - int n = 5; - int e = 5; - vector> edges; - edges.push_back(make_pair(0, 3)); - edges.push_back(make_pair(3, 4)); - edges.push_back(make_pair(0, 4)); - edges.push_back(make_pair(0, 1)); - edges.push_back(make_pair(1, 2)); - // adj list - unordered_map> adj; - for (int i = 0; i < edges.size(); i++) - { - int u = edges[i].first; - int v = edges[i].second; - adj[u].push_back(v); - adj[v].push_back(u); - } - int timer = 0; - vector disc(n); - vector low(n); - unordered_map vis; - vector ap(n, 0); - for (int i = 0; i < n; i++) - { - disc[i] = -1; - low[i] = -1; - } - // dfs - for (int i = 0; i < n; i++) - { - if (!vis[i]) - { - dfs(i, -1, disc, low, vis, adj, ap, timer); - } - } - - // print ap - cout << "Articulation points are" << endl; - for (int i = 0; i < n; i++) - { - if (ap[i] != 0) - { - cout << i << " "; - } - cout << endl; - } - - return 0; +#include +#include +using namespace std; +void dfs(int node, int parent, vector &disc, vector &low, unordered_map &vis, + unordered_map> &adj, vector &ap, int &timer) +{ + vis[node] = true; + disc[node] = low[node] = timer++; + int child = 0; + for (auto nbr : adj[node]) + { + if (nbr == parent) + { + continue; + } + if (!vis[nbr]) + { + dfs(nbr, node, disc, low, vis, adj, ap, timer); + low[node] = min(low[node], low[nbr]); + // check AP or not + if (low[nbr] >= disc[node] && parent != -1) + { + ap[node] = true; + } + child++; + } + else + { + low[node] = min(low[node], disc[nbr]); + } + } + if (parent == -1 && child > 1) + { + ap[node] = -1; + } +} +int main() +{ + int n = 5; + int e = 5; + vector> edges; + edges.push_back(make_pair(0, 3)); + edges.push_back(make_pair(3, 4)); + edges.push_back(make_pair(0, 4)); + edges.push_back(make_pair(0, 1)); + edges.push_back(make_pair(1, 2)); + // adj list + unordered_map> adj; + for (int i = 0; i < edges.size(); i++) + { + int u = edges[i].first; + int v = edges[i].second; + adj[u].push_back(v); + adj[v].push_back(u); + } + int timer = 0; + vector disc(n); + vector low(n); + unordered_map vis; + vector ap(n, 0); + for (int i = 0; i < n; i++) + { + disc[i] = -1; + low[i] = -1; + } + // dfs + for (int i = 0; i < n; i++) + { + if (!vis[i]) + { + dfs(i, -1, disc, low, vis, adj, ap, timer); + } + } + + // print ap + cout << "Articulation points are" << endl; + for (int i = 0; i < n; i++) + { + if (ap[i] != 0) + { + cout << i << " "; + } + cout << endl; + } + + return 0; } \ No newline at end of file diff --git a/Articulation.exe b/Graphs/Articulation.exe similarity index 100% rename from Articulation.exe rename to Graphs/Articulation.exe diff --git a/Dijkstra's_algorithm.cpp b/Graphs/Dijkstra's_algorithm.cpp similarity index 96% rename from Dijkstra's_algorithm.cpp rename to Graphs/Dijkstra's_algorithm.cpp index f09d92a..c37fbcf 100644 --- a/Dijkstra's_algorithm.cpp +++ b/Graphs/Dijkstra's_algorithm.cpp @@ -1,78 +1,78 @@ -#include -using namespace std; -class Solution -{ -public: - vector dijkstra(int V, vector> adj[], int S) - { - vector dist(V); - for (int i = 0; i < V; i++) - { - dist[i] = INT_MAX; - } - set> s; - dist[S] = 0; - s.insert(make_pair(0, S)); - while (!s.empty()) - { - // fetch top record - auto top = *(s.begin()); - int nodeDistance = top.first; - int topNode = top.second; - // remove top record now - s.erase(s.begin()); - - for (auto neighbour : adj[topNode]) - { - if (nodeDistance + neighbour[topNode][0] < dist[topNode][1]) - { - auto record = s.find(make_pair(dist[neighbour.first], neighbour.first)); - // if record found,then erase it - if (record != s.end()) - { - s.erase(record); - } - // distance update - dist[neighbour.first] = nodeDistance + neighbour.second; - // record push in set - s.insert(make_pair(dist[neighbour.first], neighbour.first)); - } - } - } - return dist; - } -}; -int main() -{ - int t; - cin >> t; - while (t--) - { - int V, E; - cin >> V >> E; - vector> adj[V]; - int i = 0; - while (i++ < E) - { - int u, v, w; - cin >> u >> v >> w; - vector t1, t2; - t1.push_back(v); - t1.push_back(w); - adj[u].push_back(t1); - t2.push_back(u); - t2.push_back(w); - adj[v].push_back(t2); - } - int S; - cin >> S; - Solution obj; - vector res = obj.dijkstra(V, adj, S); - for (int i = 0; i < V; i++) - { - cout << res[i] << " "; - } - cout << endl; - } - return 0; +#include +using namespace std; +class Solution +{ +public: + vector dijkstra(int V, vector> adj[], int S) + { + vector dist(V); + for (int i = 0; i < V; i++) + { + dist[i] = INT_MAX; + } + set> s; + dist[S] = 0; + s.insert(make_pair(0, S)); + while (!s.empty()) + { + // fetch top record + auto top = *(s.begin()); + int nodeDistance = top.first; + int topNode = top.second; + // remove top record now + s.erase(s.begin()); + + for (auto neighbour : adj[topNode]) + { + if (nodeDistance + neighbour[topNode][0] < dist[topNode][1]) + { + auto record = s.find(make_pair(dist[neighbour.first], neighbour.first)); + // if record found,then erase it + if (record != s.end()) + { + s.erase(record); + } + // distance update + dist[neighbour.first] = nodeDistance + neighbour.second; + // record push in set + s.insert(make_pair(dist[neighbour.first], neighbour.first)); + } + } + } + return dist; + } +}; +int main() +{ + int t; + cin >> t; + while (t--) + { + int V, E; + cin >> V >> E; + vector> adj[V]; + int i = 0; + while (i++ < E) + { + int u, v, w; + cin >> u >> v >> w; + vector t1, t2; + t1.push_back(v); + t1.push_back(w); + adj[u].push_back(t1); + t2.push_back(u); + t2.push_back(w); + adj[v].push_back(t2); + } + int S; + cin >> S; + Solution obj; + vector res = obj.dijkstra(V, adj, S); + for (int i = 0; i < V; i++) + { + cout << res[i] << " "; + } + cout << endl; + } + return 0; } \ No newline at end of file diff --git a/Graph.cpp b/Graphs/Graph.cpp similarity index 95% rename from Graph.cpp rename to Graphs/Graph.cpp index c9d6aba..1353987 100644 --- a/Graph.cpp +++ b/Graphs/Graph.cpp @@ -1,53 +1,53 @@ -#include -#include -using namespace std; -template -class graph -{ -public: - unordered_map> adj; - void addEdge(T u, T v, bool direction) - { - // direction=0-->undirected graph - // direction=1-->directed graph - // create an edge from u to v - adj[u].push_back(v); - if (direction == 0) - { - adj[v].push_back(u); - } - } - void printAdjList() - { - for (auto i : adj) - { - cout << i.first << "-> "; - for (auto j : i.second) - { - cout << j << ","; - } - - cout << endl; - } - } -}; -int main() -{ - int n; - cout << "Enter the no.of nodes" << endl; - cin >> n; - int m; - cout << "Enter the no.of edges " << endl; - cin >> m; - graph g; - for (int i = 0; i < m; i++) - { - int u, v; - cin >> u >> v; - // creating an undirected graph - g.addEdge(u, v, 0); - } - // printing graph - g.printAdjList(); - return 0; +#include +#include +using namespace std; +template +class graph +{ +public: + unordered_map> adj; + void addEdge(T u, T v, bool direction) + { + // direction=0-->undirected graph + // direction=1-->directed graph + // create an edge from u to v + adj[u].push_back(v); + if (direction == 0) + { + adj[v].push_back(u); + } + } + void printAdjList() + { + for (auto i : adj) + { + cout << i.first << "-> "; + for (auto j : i.second) + { + cout << j << ","; + } + + cout << endl; + } + } +}; +int main() +{ + int n; + cout << "Enter the no.of nodes" << endl; + cin >> n; + int m; + cout << "Enter the no.of edges " << endl; + cin >> m; + graph g; + for (int i = 0; i < m; i++) + { + int u, v; + cin >> u >> v; + // creating an undirected graph + g.addEdge(u, v, 0); + } + // printing graph + g.printAdjList(); + return 0; } \ No newline at end of file diff --git a/Graph.exe b/Graphs/Graph.exe similarity index 100% rename from Graph.exe rename to Graphs/Graph.exe diff --git a/PathinDAG.cpp b/Graphs/PathinDAG.cpp similarity index 95% rename from PathinDAG.cpp rename to Graphs/PathinDAG.cpp index dbbbc10..55249b3 100644 --- a/PathinDAG.cpp +++ b/Graphs/PathinDAG.cpp @@ -1,96 +1,96 @@ -#include -#include -using namespace std; -class graph -{ -public: - unordered_map>> adj; - void addEdge(int u, int v, int weight) - { - pair p = make_pair(v, weight); - adj[u].push_back(p); - } - void printAdj() - { - for (auto i : adj) - { - cout << i.first << "->"; - for (auto j : i.second) - { - cout << "(" << j.first << "," << j.second << "), "; - } - cout << endl; - } - } - void dfs(int node, unordered_map &visited, stack &topo) - { - visited[node] = true; - for (auto neighbour : adj[node]) - { - if (!visited[neighbour.first]) - { - dfs(neighbour.first, visited, topo); - } - } - topo.push(node); - } - void getShortestPath(int src, vector &dist, stack &topo) - { - dist[src] = 0; - while (!topo.empty()) - { - int top = topo.top(); - topo.pop(); - if (dist[top] != INT_MAX) - { - for (auto i : adj[top]) - { - if (dist[top] + i.second < dist[i].first) - { - dist[i].first = dist[top] + i.second; - } - } - } - } - } -}; -int main() -{ - graph g; - g.addEdge(0, 1, 5); - g.addEdge(0, 2, 3); - g.addEdge(1, 2, 2); - g.addEdge(1, 3, 6); - g.addEdge(2, 3, 7); - g.addEdge(2, 4, 4); - g.addEdge(2, 5, 2); - g.addEdge(3, 4, -1); - g.addEdge(4, 5, -2); - g.printAdj(); - int n = 6; // n-->totalNode - // topological sort - unordered_map visited; - stack s; - for (int i = 0; i < n; i++) - { - if (!visited[i]) - { - g.dfs(i, visited, s); - } - } - int src = 1; - vector dist(n); - for (int i = 0; i < n; i++) - { - dist[i] = INT_MAX; - } - g.getShortestPath(src, dist, s); - cout << "ans is: " << endl; - for (int i = 0; i < dist.size(); i++) - { - cout << dist[i] << " "; - } - - cout << endl; - return 0; +#include +#include +using namespace std; +class graph +{ +public: + unordered_map>> adj; + void addEdge(int u, int v, int weight) + { + pair p = make_pair(v, weight); + adj[u].push_back(p); + } + void printAdj() + { + for (auto i : adj) + { + cout << i.first << "->"; + for (auto j : i.second) + { + cout << "(" << j.first << "," << j.second << "), "; + } + cout << endl; + } + } + void dfs(int node, unordered_map &visited, stack &topo) + { + visited[node] = true; + for (auto neighbour : adj[node]) + { + if (!visited[neighbour.first]) + { + dfs(neighbour.first, visited, topo); + } + } + topo.push(node); + } + void getShortestPath(int src, vector &dist, stack &topo) + { + dist[src] = 0; + while (!topo.empty()) + { + int top = topo.top(); + topo.pop(); + if (dist[top] != INT_MAX) + { + for (auto i : adj[top]) + { + if (dist[top] + i.second < dist[i].first) + { + dist[i].first = dist[top] + i.second; + } + } + } + } + } +}; +int main() +{ + graph g; + g.addEdge(0, 1, 5); + g.addEdge(0, 2, 3); + g.addEdge(1, 2, 2); + g.addEdge(1, 3, 6); + g.addEdge(2, 3, 7); + g.addEdge(2, 4, 4); + g.addEdge(2, 5, 2); + g.addEdge(3, 4, -1); + g.addEdge(4, 5, -2); + g.printAdj(); + int n = 6; // n-->totalNode + // topological sort + unordered_map visited; + stack s; + for (int i = 0; i < n; i++) + { + if (!visited[i]) + { + g.dfs(i, visited, s); + } + } + int src = 1; + vector dist(n); + for (int i = 0; i < n; i++) + { + dist[i] = INT_MAX; + } + g.getShortestPath(src, dist, s); + cout << "ans is: " << endl; + for (int i = 0; i < dist.size(); i++) + { + cout << dist[i] << " "; + } + + cout << endl; + return 0; } \ No newline at end of file diff --git a/PathinDAG.exe b/Graphs/PathinDAG.exe similarity index 100% rename from PathinDAG.exe rename to Graphs/PathinDAG.exe diff --git a/kosaraju.cpp b/Graphs/kosaraju.cpp similarity index 95% rename from kosaraju.cpp rename to Graphs/kosaraju.cpp index 42b1869..10f973d 100644 --- a/kosaraju.cpp +++ b/Graphs/kosaraju.cpp @@ -1,57 +1,57 @@ -#include -void dfs(int node,unordered_map &vis,stack &s, unordered_map> &adj){ - vis[node]=true; - for(auto nbr: adj[node]){ - if(!vis[nbr]){ - dfs(nbr,vis,s,adj); -} -} -// topo logic - s.push(node); -} -void revDfs(int node,unordered_map &vis,unordered_map> &adj){ -vis[node]=true; - for(auto nbr:adj[node]){ - if(!vis[nbr]){ -revDfs(nbr,vis,adj); - } -} -} -int stronglyConnectedComponents(int v, vector> &edges) -{ - // Write your code here. -// create an adj list - unordered_map> adj; - for(int i=0;i s; - unordered_map vis; - for(int i=0;i> transpose; - for(int i=0;i +void dfs(int node,unordered_map &vis,stack &s, unordered_map> &adj){ + vis[node]=true; + for(auto nbr: adj[node]){ + if(!vis[nbr]){ + dfs(nbr,vis,s,adj); +} +} +// topo logic + s.push(node); +} +void revDfs(int node,unordered_map &vis,unordered_map> &adj){ +vis[node]=true; + for(auto nbr:adj[node]){ + if(!vis[nbr]){ +revDfs(nbr,vis,adj); + } +} +} +int stronglyConnectedComponents(int v, vector> &edges) +{ + // Write your code here. +// create an adj list + unordered_map> adj; + for(int i=0;i s; + unordered_map vis; + for(int i=0;i> transpose; + for(int i=0;i -using namespace std; -int dp[1000][1000]; -int knapsack(int *wt,int *val,int n,int W){ - for (int i=0;i<=n;i++){ - for (int j=0;j<=W;j++){ - if (i==0 || j==0){ - dp[i][j]=0; - } - else if (wt[i-1]<=j){ - dp[i][j]=max(val[i-1]+dp[i-1][j-wt[i-1]],dp[i-1][j]); - } - - else{ - dp[i][j]=dp[i-1][j]; - } - } - } - return dp[n][W]; - } - int main() - { - - int val[]={60,100,120}; - int wt[]={10,20,30}; - int W=50; - cout< +using namespace std; +int dp[1000][1000]; +int knapsack(int *wt,int *val,int n,int W){ + for (int i=0;i<=n;i++){ + for (int j=0;j<=W;j++){ + if (i==0 || j==0){ + dp[i][j]=0; + } + else if (wt[i-1]<=j){ + dp[i][j]=max(val[i-1]+dp[i-1][j-wt[i-1]],dp[i-1][j]); + } + + else{ + dp[i][j]=dp[i-1][j]; + } + } + } + return dp[n][W]; + } + int main() + { + + int val[]={60,100,120}; + int wt[]={10,20,30}; + int W=50; + cout<m; - - mapresult; - vectorans; - - for(int i=0;i -using namespace std; -class Node -{ -public: - int data; - Node *next; - // Constructor - Node(int d) - { - this->data = d; - this->next = NULL; - } - ~Node() - { - int value = this->data; - if (this->next != NULL) - { - delete next; - next = NULL; - } - cout << "Memory free for node with data " << value << endl; - } -}; -void InsertNode(Node *&tail, int element, int d) -{ - // assuming that the element is present in the list - // Empty list - if (tail == NULL) - { - Node *newNode = new Node(d); - tail = newNode; - newNode->next = newNode; - } - else - { - // non-empty list - // assuming that the element is present in the list - Node *curr = tail; - while (curr->data != element) - { - curr = curr->next; - } - // element found->curr is representing element wala node - Node *temp = new Node(d); - temp->next = curr->next; - curr->next = temp; - } -} -void print(Node *tail) -{ - Node *temp = tail; - if (tail == NULL) - { - cout << "List is empty " << endl; - return; - } - - do - { - cout << tail->data << " "; - tail = tail->next; - } while (tail != temp); - cout << endl; -} -void deleteNode(Node *&tail, int value) -{ - // empty list - if (tail == NULL) - { - cout << "List is empty" << endl; - return; - } - else - { - // non-empty list - // assuming that the value is present in the list - Node *prev = tail; - Node *curr = prev->next; - while (curr->data != value) - { - prev = curr; - curr = curr->next; - } - prev->next = curr->next; - // for one node linked list - if (curr == prev) - { - tail = NULL; - } - // >=2 node linked list - if (tail == curr) - { - tail = prev; - } - - curr->next = NULL; - delete curr; - } -} -bool circularList(Node *head) -{ - if (head == NULL) - { - return true; - } - Node *temp = head->next; - while (temp != NULL && temp != head) - { - temp = temp->next; - } - if (temp == head) - { - return true; - } - return false; -} -int main() -{ - Node *tail = NULL; - // Insertion in empty list - InsertNode(tail, 5, 3); - print(tail); - /* InsertNode(tail, 3, 5); - print(tail); - InsertNode(tail, 5, 7); - print(tail); - InsertNode(tail, 7, 9); - print(tail); - InsertNode(tail, 5, 6); - print(tail); - InsertNode(tail, 3, 4); - print(tail); - - */ - deleteNode(tail, 3); - print(tail); - if (circularList(tail)) - { - cout << "Linked list is circular " << endl; - } - else - { - cout << "Linked list is not circular " << endl; - } - - return 0; -} -int len = 0; -while (head != NULL) -{ - len++; - head = head->next; -} -return len; -} -int getMiddle(Node *head) -{ - // Your code here - int len = getLength(head); - int ans = (len / 2); - Node *temp = head; - int cnt = 0; - while (cnt < ans) - { - temp = temp->next; - cnt++; - } - return temp->data; - - - - - - // Complete this method - if (head == NULL) - { - return NULL; - } - // Step-1: Reverse first k nodes - node *next = NULL; - node *curr = head; - node *prev = NULL; - int cnt = 0; - while (curr != NULL && cnt < k) - { - next = curr->next; - curr->next = prev; - prev = curr; - curr = next; - cnt++; - } - // Step-2: Recursion dekhlega - if (next != NULL) - { - head->next = reverse(next, k); - } - // Step-3: Return head of reversed LL +#include +using namespace std; +class Node +{ +public: + int data; + Node *next; + // Constructor + Node(int d) + { + this->data = d; + this->next = NULL; + } + ~Node() + { + int value = this->data; + if (this->next != NULL) + { + delete next; + next = NULL; + } + cout << "Memory free for node with data " << value << endl; + } +}; +void InsertNode(Node *&tail, int element, int d) +{ + // assuming that the element is present in the list + // Empty list + if (tail == NULL) + { + Node *newNode = new Node(d); + tail = newNode; + newNode->next = newNode; + } + else + { + // non-empty list + // assuming that the element is present in the list + Node *curr = tail; + while (curr->data != element) + { + curr = curr->next; + } + // element found->curr is representing element wala node + Node *temp = new Node(d); + temp->next = curr->next; + curr->next = temp; + } +} +void print(Node *tail) +{ + Node *temp = tail; + if (tail == NULL) + { + cout << "List is empty " << endl; + return; + } + + do + { + cout << tail->data << " "; + tail = tail->next; + } while (tail != temp); + cout << endl; +} +void deleteNode(Node *&tail, int value) +{ + // empty list + if (tail == NULL) + { + cout << "List is empty" << endl; + return; + } + else + { + // non-empty list + // assuming that the value is present in the list + Node *prev = tail; + Node *curr = prev->next; + while (curr->data != value) + { + prev = curr; + curr = curr->next; + } + prev->next = curr->next; + // for one node linked list + if (curr == prev) + { + tail = NULL; + } + // >=2 node linked list + if (tail == curr) + { + tail = prev; + } + + curr->next = NULL; + delete curr; + } +} +bool circularList(Node *head) +{ + if (head == NULL) + { + return true; + } + Node *temp = head->next; + while (temp != NULL && temp != head) + { + temp = temp->next; + } + if (temp == head) + { + return true; + } + return false; +} +int main() +{ + Node *tail = NULL; + // Insertion in empty list + InsertNode(tail, 5, 3); + print(tail); + /* InsertNode(tail, 3, 5); + print(tail); + InsertNode(tail, 5, 7); + print(tail); + InsertNode(tail, 7, 9); + print(tail); + InsertNode(tail, 5, 6); + print(tail); + InsertNode(tail, 3, 4); + print(tail); + + */ + deleteNode(tail, 3); + print(tail); + if (circularList(tail)) + { + cout << "Linked list is circular " << endl; + } + else + { + cout << "Linked list is not circular " << endl; + } + + return 0; +} +int len = 0; +while (head != NULL) +{ + len++; + head = head->next; +} +return len; +} +int getMiddle(Node *head) +{ + // Your code here + int len = getLength(head); + int ans = (len / 2); + Node *temp = head; + int cnt = 0; + while (cnt < ans) + { + temp = temp->next; + cnt++; + } + return temp->data; + + + + + + // Complete this method + if (head == NULL) + { + return NULL; + } + // Step-1: Reverse first k nodes + node *next = NULL; + node *curr = head; + node *prev = NULL; + int cnt = 0; + while (curr != NULL && cnt < k) + { + next = curr->next; + curr->next = prev; + prev = curr; + curr = next; + cnt++; + } + // Step-2: Recursion dekhlega + if (next != NULL) + { + head->next = reverse(next, k); + } + // Step-3: Return head of reversed LL return prev; \ No newline at end of file diff --git a/CircularLinkedList.exe b/Linked Lists/CircularLinkedList.exe similarity index 100% rename from CircularLinkedList.exe rename to Linked Lists/CircularLinkedList.exe diff --git a/DeleteMiddleNodeofLL.cpp b/Linked Lists/DeleteMiddleNodeofLL.cpp similarity index 95% rename from DeleteMiddleNodeofLL.cpp rename to Linked Lists/DeleteMiddleNodeofLL.cpp index b423dc3..d37121a 100644 --- a/DeleteMiddleNodeofLL.cpp +++ b/Linked Lists/DeleteMiddleNodeofLL.cpp @@ -1,25 +1,25 @@ -class Solution { -public: - ListNode* deleteMiddle(ListNode* head) { - if(head==NULL){ - return NULL; - } - if(head->next==NULL){ - head=NULL; - return NULL; - } - ListNode*slow=head; - ListNode*fast=head; - while(fast!=NULL&&fast->next!=NULL){ - fast=fast->next->next; - slow=slow->next; - } - if(slow->next==NULL){ - head->next=NULL; - return head; - } - slow->val=slow->next->val; - slow->next=slow->next->next; - return head; - } +class Solution { +public: + ListNode* deleteMiddle(ListNode* head) { + if(head==NULL){ + return NULL; + } + if(head->next==NULL){ + head=NULL; + return NULL; + } + ListNode*slow=head; + ListNode*fast=head; + while(fast!=NULL&&fast->next!=NULL){ + fast=fast->next->next; + slow=slow->next; + } + if(slow->next==NULL){ + head->next=NULL; + return head; + } + slow->val=slow->next->val; + slow->next=slow->next->next; + return head; + } }; \ No newline at end of file diff --git a/DoublyLinkedList.cpp b/Linked Lists/DoublyLinkedList.cpp similarity index 95% rename from DoublyLinkedList.cpp rename to Linked Lists/DoublyLinkedList.cpp index ddb607e..f814937 100644 --- a/DoublyLinkedList.cpp +++ b/Linked Lists/DoublyLinkedList.cpp @@ -1,177 +1,177 @@ -#include -using namespace std; -class Node -{ -public: - int data; - Node *next; - Node *prev; - Node(int d) - { - this->data = d; - this->prev = NULL; - this->next = NULL; - } - ~Node() - { - int value = this->data; - if (next != NULL) - { - delete next; - next = NULL; - } - cout << "Memory free for node with data " << value << endl; - } -}; -// Traversing a linked list -void print(Node *head) -{ - Node *temp = head; - while (temp != NULL) - { - cout << temp->data << " "; - temp = temp->next; - } - cout << endl; -} -// gives length of linked list -int getLength(Node *head) -{ - int len = 0; - Node *temp = head; - while (temp != NULL) - { - len++; - cout << temp->data << " "; - temp = temp->next; - } - return len; -} -void insertAtHead(Node *&tail, Node *&head, int d) -{ - if (head == NULL) - { - Node *temp = new Node(d); - head = temp; - tail = temp; - } - else - { - Node *temp = new Node(d); - temp->next = head; - head->prev = temp; - head = temp; - } -} -void insertAtTail(Node *&tail, Node *&head, int d) -{ - if (tail == NULL) - - { - Node *temp = new Node(d); - tail = temp; - head = temp; - } - else - { - Node *temp = new Node(d); - tail->next = temp; - temp->prev = tail; - tail = temp; - } -} -void insertAtPosition(Node *&tail, Node *&head, int position, int d) -{ - // insert at start - if (position == 1) - { - insertAtHead(tail, head, d); - return; - } - Node *temp = head; - int cnt = 1; - while (cnt < position - 1) - { - temp = temp->next; - cnt++; - } - // Inserting at last position - if (temp->next == NULL) - { - insertAtTail(tail, head, d); - return; - } - - // Creating a node for d - Node *nodeToInsert = new Node(d); - nodeToInsert->next = temp->next; - temp->next->prev = nodeToInsert; - temp->next = nodeToInsert; - nodeToInsert->prev = temp; -} -void DeleteNode(int position, Node *&head) -{ - // Deleting first node: - if (position == 1) - { - Node *temp = head; - temp->next->prev = NULL; - - head = temp->next; - temp->next = NULL; - // memory free start node - delete temp; - } - else - { - // deleting any middle node or last node: - Node *curr = head; - Node *prev = NULL; - int cnt = 1; - while (cnt < position) - { - prev = curr; - curr = curr->next; - curr->next = NULL; - cnt++; - } - curr->prev = NULL; - prev->next = curr->next; - curr->next = NULL; - // memory free start node - delete curr; - } -} - -int main() -{ - Node *node1 = new Node(10); - Node *head = node1; - Node *tail = node1; - print(head); - cout << getLength(head) << endl; - insertAtHead(tail, head, 11); - print(head); - cout << "head : " << head->data << endl; - cout << "tail : " << tail->data << endl; - insertAtHead(tail, head, 13); - print(head); - cout << "head : " << head->data << endl; - cout << "tail : " << tail->data << endl; - insertAtTail(tail, head, 15); - print(head); - insertAtPosition(tail, head, 5, 100); - print(head); - cout << "head : " << head->data << endl; - cout << "tail : " << tail->data << endl; - insertAtPosition(tail, head, 3, 103); - print(head); - cout << "head : " << head->data << endl; - cout << "tail : " << tail->data << endl; - DeleteNode(3, head); - print(head); - cout << "head : " << head->data << endl; - cout << "tail : " << tail->data << endl; - - return 0; +#include +using namespace std; +class Node +{ +public: + int data; + Node *next; + Node *prev; + Node(int d) + { + this->data = d; + this->prev = NULL; + this->next = NULL; + } + ~Node() + { + int value = this->data; + if (next != NULL) + { + delete next; + next = NULL; + } + cout << "Memory free for node with data " << value << endl; + } +}; +// Traversing a linked list +void print(Node *head) +{ + Node *temp = head; + while (temp != NULL) + { + cout << temp->data << " "; + temp = temp->next; + } + cout << endl; +} +// gives length of linked list +int getLength(Node *head) +{ + int len = 0; + Node *temp = head; + while (temp != NULL) + { + len++; + cout << temp->data << " "; + temp = temp->next; + } + return len; +} +void insertAtHead(Node *&tail, Node *&head, int d) +{ + if (head == NULL) + { + Node *temp = new Node(d); + head = temp; + tail = temp; + } + else + { + Node *temp = new Node(d); + temp->next = head; + head->prev = temp; + head = temp; + } +} +void insertAtTail(Node *&tail, Node *&head, int d) +{ + if (tail == NULL) + + { + Node *temp = new Node(d); + tail = temp; + head = temp; + } + else + { + Node *temp = new Node(d); + tail->next = temp; + temp->prev = tail; + tail = temp; + } +} +void insertAtPosition(Node *&tail, Node *&head, int position, int d) +{ + // insert at start + if (position == 1) + { + insertAtHead(tail, head, d); + return; + } + Node *temp = head; + int cnt = 1; + while (cnt < position - 1) + { + temp = temp->next; + cnt++; + } + // Inserting at last position + if (temp->next == NULL) + { + insertAtTail(tail, head, d); + return; + } + + // Creating a node for d + Node *nodeToInsert = new Node(d); + nodeToInsert->next = temp->next; + temp->next->prev = nodeToInsert; + temp->next = nodeToInsert; + nodeToInsert->prev = temp; +} +void DeleteNode(int position, Node *&head) +{ + // Deleting first node: + if (position == 1) + { + Node *temp = head; + temp->next->prev = NULL; + + head = temp->next; + temp->next = NULL; + // memory free start node + delete temp; + } + else + { + // deleting any middle node or last node: + Node *curr = head; + Node *prev = NULL; + int cnt = 1; + while (cnt < position) + { + prev = curr; + curr = curr->next; + curr->next = NULL; + cnt++; + } + curr->prev = NULL; + prev->next = curr->next; + curr->next = NULL; + // memory free start node + delete curr; + } +} + +int main() +{ + Node *node1 = new Node(10); + Node *head = node1; + Node *tail = node1; + print(head); + cout << getLength(head) << endl; + insertAtHead(tail, head, 11); + print(head); + cout << "head : " << head->data << endl; + cout << "tail : " << tail->data << endl; + insertAtHead(tail, head, 13); + print(head); + cout << "head : " << head->data << endl; + cout << "tail : " << tail->data << endl; + insertAtTail(tail, head, 15); + print(head); + insertAtPosition(tail, head, 5, 100); + print(head); + cout << "head : " << head->data << endl; + cout << "tail : " << tail->data << endl; + insertAtPosition(tail, head, 3, 103); + print(head); + cout << "head : " << head->data << endl; + cout << "tail : " << tail->data << endl; + DeleteNode(3, head); + print(head); + cout << "head : " << head->data << endl; + cout << "tail : " << tail->data << endl; + + return 0; } \ No newline at end of file diff --git a/DoublyLinkedList.exe b/Linked Lists/DoublyLinkedList.exe similarity index 100% rename from DoublyLinkedList.exe rename to Linked Lists/DoublyLinkedList.exe diff --git a/FlattenLL.cpp b/Linked Lists/FlattenLL.cpp similarity index 95% rename from FlattenLL.cpp rename to Linked Lists/FlattenLL.cpp index f5fb9df..e03f2da 100644 --- a/FlattenLL.cpp +++ b/Linked Lists/FlattenLL.cpp @@ -1,28 +1,28 @@ -class Solution { -public: -Node* mergeLists(Node* a, Node* b) { - - // base cases - if (a == NULL) return b; - if (b == NULL) return a; - // recursive step - Node* result; - if (a->data < b->data) { - result = a; - result->bottom = mergeLists(a->bottom, b); - } else { - result = b; - result->bottom = mergeLists(a, b->bottom); - } - return result; -} - Node *flatten(Node *root) - { - // base case - if (root == NULL || root->next == NULL) { - return root; - } - // recursive step - return mergeLists(root, flatten(root->next)); - } +class Solution { +public: +Node* mergeLists(Node* a, Node* b) { + + // base cases + if (a == NULL) return b; + if (b == NULL) return a; + // recursive step + Node* result; + if (a->data < b->data) { + result = a; + result->bottom = mergeLists(a->bottom, b); + } else { + result = b; + result->bottom = mergeLists(a, b->bottom); + } + return result; +} + Node *flatten(Node *root) + { + // base case + if (root == NULL || root->next == NULL) { + return root; + } + // recursive step + return mergeLists(root, flatten(root->next)); + } }; \ No newline at end of file diff --git a/Insertion-deletion.cpp b/Linked Lists/Insertion-deletion.cpp similarity index 94% rename from Insertion-deletion.cpp rename to Linked Lists/Insertion-deletion.cpp index a756359..e40535a 100644 --- a/Insertion-deletion.cpp +++ b/Linked Lists/Insertion-deletion.cpp @@ -1,132 +1,132 @@ -#include -using namespace std; -class node -{ -public: - int data; - node *next; - node *prev; - node(int d) - { - this->data = d; - this->next = NULL; - this->prev = NULL; - } - ~node() - { - int value = this->data; - if (next != NULL) - { - delete next; - next = NULL; - } - cout << "Memory free for node with data " << value << endl; - } -}; -void printDoublyLL(node *head) -{ - node *temp = head; - while (temp != NULL) - { - cout << temp->data << " "; - temp = temp->next; - } - cout << endl; -} -void insertionAtFront(node *&head, int d) -{ - if (head == NULL) - { - node *temp = new node(d); - head = temp; - temp->next = NULL; - } - else - { - node *temp = new node(d); - temp->next = head; - head->prev = temp; - head = temp; - } -} -void insertionAtEnd(node *&head, int d) -{ - node *temp = new node(d); - if (head == NULL) - { - temp->prev = NULL; - head = temp; - } - temp->next = NULL; - while (head->next != NULL) - { - head = head->next; - } - head->next = temp; - temp->prev = head; - head = temp; -} -void insertionAtPosition(node *&head, int d, int pos) -{ - if (pos == 1) - { - insertionAtFront(head, d); - } - node *temp = head; - int cnt = 1; - while (cnt < pos - 1) - { - temp = temp->next; - cnt++; - } - if (temp->next = NULL) - { - insertionAtEnd(head, d); - } - node *nodeToInsert = new node(d); - nodeToInsert->next = temp->next; - temp->next->prev = nodeToInsert; - temp->next = nodeToInsert; - nodeToInsert->prev = temp; -} -void deleteNode(node*&head,int pos){ -if(pos==1){ - node*temp=head; - temp->next->prev=NULL; - head=temp->next; - temp->next=NULL; - delete temp; -} -node*curr=head; -node*prev=NULL; -int cnt=1; -while (cntnext; - curr->next = NULL; - cnt++; -} -curr->prev = NULL; - prev->next = curr->next; - curr->next = NULL; - // memory free start node - delete curr; - -} -int main() -{ -node*node1=new node(10); -node*head=node1; - insertionAtFront(head,13); - insertionAtFront(head,14); - insertionAtEnd(head,15); - printDoublyLL(head); - insertionAtPosition(head,19,1); - printDoublyLL(head); - deleteNode(head,2); - printDoublyLL(head); - - - return 0; +#include +using namespace std; +class node +{ +public: + int data; + node *next; + node *prev; + node(int d) + { + this->data = d; + this->next = NULL; + this->prev = NULL; + } + ~node() + { + int value = this->data; + if (next != NULL) + { + delete next; + next = NULL; + } + cout << "Memory free for node with data " << value << endl; + } +}; +void printDoublyLL(node *head) +{ + node *temp = head; + while (temp != NULL) + { + cout << temp->data << " "; + temp = temp->next; + } + cout << endl; +} +void insertionAtFront(node *&head, int d) +{ + if (head == NULL) + { + node *temp = new node(d); + head = temp; + temp->next = NULL; + } + else + { + node *temp = new node(d); + temp->next = head; + head->prev = temp; + head = temp; + } +} +void insertionAtEnd(node *&head, int d) +{ + node *temp = new node(d); + if (head == NULL) + { + temp->prev = NULL; + head = temp; + } + temp->next = NULL; + while (head->next != NULL) + { + head = head->next; + } + head->next = temp; + temp->prev = head; + head = temp; +} +void insertionAtPosition(node *&head, int d, int pos) +{ + if (pos == 1) + { + insertionAtFront(head, d); + } + node *temp = head; + int cnt = 1; + while (cnt < pos - 1) + { + temp = temp->next; + cnt++; + } + if (temp->next = NULL) + { + insertionAtEnd(head, d); + } + node *nodeToInsert = new node(d); + nodeToInsert->next = temp->next; + temp->next->prev = nodeToInsert; + temp->next = nodeToInsert; + nodeToInsert->prev = temp; +} +void deleteNode(node*&head,int pos){ +if(pos==1){ + node*temp=head; + temp->next->prev=NULL; + head=temp->next; + temp->next=NULL; + delete temp; +} +node*curr=head; +node*prev=NULL; +int cnt=1; +while (cntnext; + curr->next = NULL; + cnt++; +} +curr->prev = NULL; + prev->next = curr->next; + curr->next = NULL; + // memory free start node + delete curr; + +} +int main() +{ +node*node1=new node(10); +node*head=node1; + insertionAtFront(head,13); + insertionAtFront(head,14); + insertionAtEnd(head,15); + printDoublyLL(head); + insertionAtPosition(head,19,1); + printDoublyLL(head); + deleteNode(head,2); + printDoublyLL(head); + + + return 0; } \ No newline at end of file diff --git a/IntersectionYshapedLL.cpp b/Linked Lists/IntersectionYshapedLL.cpp similarity index 96% rename from IntersectionYshapedLL.cpp rename to Linked Lists/IntersectionYshapedLL.cpp index 5c036d0..51ecd82 100644 --- a/IntersectionYshapedLL.cpp +++ b/Linked Lists/IntersectionYshapedLL.cpp @@ -1,26 +1,26 @@ -class Solution{ - public: - Node* findIntersection(Node* head1, Node* head2) - { - // code here - // return the head of intersection list - if(head1==NULL || head2==NULL){ - return NULL; - } - Node*temp=head2; - set s; - while(temp!=NULL){ - s.insert(temp->data); - temp=temp->next; - } - Node*intersection=new Node(0),*tracker=intersection; - while(head1!=NULL){ - if(s.find(head1->data)!=s.end()){ - tracker->next=new Node(head1->data); - tracker=tracker->next; - } - head1=head1->next; - } - return intersection->next; - } +class Solution{ + public: + Node* findIntersection(Node* head1, Node* head2) + { + // code here + // return the head of intersection list + if(head1==NULL || head2==NULL){ + return NULL; + } + Node*temp=head2; + set s; + while(temp!=NULL){ + s.insert(temp->data); + temp=temp->next; + } + Node*intersection=new Node(0),*tracker=intersection; + while(head1!=NULL){ + if(s.find(head1->data)!=s.end()){ + tracker->next=new Node(head1->data); + tracker=tracker->next; + } + head1=head1->next; + } + return intersection->next; + } }; \ No newline at end of file diff --git a/LinkedListPractice.exe b/Linked Lists/LinkedListPractice.exe similarity index 100% rename from LinkedListPractice.exe rename to Linked Lists/LinkedListPractice.exe diff --git a/LinkedListReversal.cpp b/Linked Lists/LinkedListReversal.cpp similarity index 94% rename from LinkedListReversal.cpp rename to Linked Lists/LinkedListReversal.cpp index 2ff7bbd..d44abc6 100644 --- a/LinkedListReversal.cpp +++ b/Linked Lists/LinkedListReversal.cpp @@ -1,23 +1,23 @@ -struct Node -{ - int data; - struct Node *next; -}; -class Solution -{ - public: -struct Node* reverseList(struct Node *head) - { - - struct Node*curr=head; - struct Node*prev=NULL; - struct Node*forward=NULL; - while(curr!=NULL){ - forward=curr->next; - curr->next=prev; - prev=curr; - curr=forward; - } - return prev; - } +struct Node +{ + int data; + struct Node *next; +}; +class Solution +{ + public: +struct Node* reverseList(struct Node *head) + { + + struct Node*curr=head; + struct Node*prev=NULL; + struct Node*forward=NULL; + while(curr!=NULL){ + forward=curr->next; + curr->next=prev; + prev=curr; + curr=forward; + } + return prev; + } }; \ No newline at end of file diff --git a/Linkedlist.cpp b/Linked Lists/Linkedlist.cpp similarity index 95% rename from Linkedlist.cpp rename to Linked Lists/Linkedlist.cpp index 56a5510..3c30a3c 100644 --- a/Linkedlist.cpp +++ b/Linked Lists/Linkedlist.cpp @@ -1,521 +1,521 @@ -#include -#include -using namespace std; -class Node -{ -public: - int data; - Node *next; - // Constructor - Node(int data) - { - this->data = data; - this->next = NULL; - } - // Destructor - ~Node() - { - int value = this->data; - // memory free - - if (this->next != NULL) - { - delete next; - this->next = NULL; - } - cout << "Memory is free for mode with data " << value << endl; - } -}; -void InsertAtHead(Node *&head, int d) -{ - // New node create - Node *temp = new Node(d); - temp->next = head; - head = temp; -} -void InsertAtTail(Node *&tail, int d) -{ - Node *temp = new Node(d); - tail->next = temp; - tail = temp; -} -void InsertAtPosition(Node *&head, int position, int d) -{ - // Insert at start - if (position == 1) - { - InsertAtHead(head, d); - return; - } - - Node *temp = head; - int cnt = 1; - while (cnt < position - 1) - { - temp = temp->next; - cnt++; - } - // Creating a node for d - Node *nodeToInsert = new Node(d); - nodeToInsert->next = temp->next; - temp->next = nodeToInsert; -} -void DeleteNode(int position, Node *&head) -{ - // Deleting first node: - if (position == 1) - { - Node *temp = head; - head = head->next; - // memory free start node - temp->next = NULL; - delete temp; - } - else - { - // deleting any middle node or last node: - Node *curr = head; - Node *prev = NULL; - int cnt = 1; - while (cnt < position) - { - prev = curr; - curr = curr->next; - curr->next = NULL; - cnt++; - } - prev->next = curr->next; - delete curr; - } -} -void print(Node *&head) -{ - Node *temp = head; - while (temp != NULL) - { - cout << temp->data << " "; - temp = temp->next; - } - cout << endl; -} -Node *floydDetectLoop(Node *head) -{ - if (head == NULL) - { - return NULL; - } - Node *slow = head; - Node *fast = head; - while (slow!=NULL&&fast!=NULL) - { - fast=fast->next; - if(fast!=NULL){ - fast=fast->next; - - } - slow=slow->next; - if (slow==fast) - { - return true; - } - return false; - - } - - -} -Node *startingNodeLoop(Node *head) -{ - if (head == NULL) - { - return NULL; - } - Node *intersection = detectLoop(head); - Node *slow = head; - while (slow != intersection) - { - slow = slow->next; - intersection = intersection->next; - } - return slow; -} - void removeLoop(Node* head) - { - // code here - // just remove the loop without losing any nodes - if(head==NULL){ - return ; - } - Node*startingNode=getStartingNodeLoop(head); - Node*temp=startingNode; - while(temp->next!=startingNode){ - temp=temp->next; - } - temp->next=NULL; - - } -int main() -{ - // Create a new node - Node *node1 = new Node(10); - // cout << node1->data << endl; - // cout << node1->next << endl; - // head pointer to node1 - Node *head = node1; - Node *tail = node1; - // print(head); - InsertAtHead(head, 12); - // print(head); - InsertAtHead(head, 15); - - InsertAtTail(tail, 10); - // print(head); - InsertAtTail(tail, 12); - // print(head); - tail->next = head->next; - - cout << "head : " << head->data << endl; - cout << "tail : " << tail->data << endl; - if (detectLoop(head)) - { - cout << "Loop is present " << endl; - } - else - { - cout << "Loop is absent " << endl; - } - - // InsertAtTail(tail, 15); - // print(head); - // InsertAtPosition(head, 4, 22); - // print(head); - // DeleteNode(3, head); - // print(head); - return 0; -} - if(head==NULL){ - return false; - } - Node*slow=head; - Node*fast=head; - while(fast!=NULL&&slow!=NULL){ - fast=fast->next; - if(fast!=NULL){ - fast=fast->next; - } - slow=slow->next; - if(slow==fast){ - return true; - } - } - return false; - } - if (headA == NULL && headB == NULL) { - return 1; -} else if (headA == NULL || headB == NULL) { - return 0; -} - -if (headA->data == headB->data) { - return CompareLists(headA->next, headB->next); -} else { - return 0; -} - - -// Add 2 numbers in form of LL - Node*reverse(Node*head){ - Node*curr=head; - Node*prev=NULL; - Node*next=NULL; - while(curr!=NULL){ - next=curr->next; - curr->next=prev; - prev=curr; - curr=next; - } - return prev; - } - void insertAtTail(struct Node*&head, struct Node*&tail,int val){ - Node*temp=new Node(val); - // Empty list - if(head==NULL){ - head=temp; - tail=temp; - return; - } - else{ - tail->next=temp; - tail=temp; - } - - - } - struct Node* add(struct Node* first, struct Node* second){ - int carry=0; - - Node*ansHead=NULL; - Node*ansTail=NULL; - while(first!=NULL ||second!=NULL||carry!=0){ - int val1=0; - if(first!=NULL){ - val1=first->data; - } - int val2=0; - if(second!=NULL){ - val2=second->data; - } - - int sum=carry+val1+val2; - int digit=sum%10; - // Create node and add in answer LL - insertAtTail(ansHead,ansTail,digit); - carry=sum/10; - if(first!=NULL) - first=first->next; - if(second!=NULL) - second=second->next; - } - - return ansHead; - } - public: - //Function to add two numbers represented by linked list. - struct Node* addTwoLists(struct Node* first, struct Node* second) - { - // code here - // Step-1:reverse input linked list: - first=reverse(first); - second=reverse(second); - // Step-2:Add 2 LL - Node*ans=add(first,second); - // Step-3:reverse ans wali LL - ans=reverse(ans); - - - return ans; - } - void insertAtTail(Node*&tail,Node*&curr){ - tail->next=curr; - tail=curr; - } - //Function to sort a linked list of 0s, 1s and 2s. - Node* segregate(Node *head) { - - // Add code here - Node*zeroHead=new Node(-1); - Node*zeroTail=zeroHead; - Node*oneHead=new Node(-1); - Node*oneTail=oneHead; - Node*twoHead=new Node(-1); - Node*twoTail=twoHead; - Node*curr=head; - // Create a separate list for 0s 1s and 2s - while(curr!=NULL){ - int value=curr->data; - if(value==0){ - insertAtTail(zeroTail,curr); - - } - else if(value==1){ - insertAtTail(oneTail,curr); - } - else if(value==2){ - insertAtTail(twoTail,curr); - - } - curr=curr->next; - } - // Merge 3 sublist - if(oneHead->next!=NULL){ // 1's list is non-empty - zeroTail->next=oneHead->next; - } - else{ - // 1's list is empty - zeroTail->next=twoHead->next; - } - oneTail->next=twoHead->next; - twoTail->next=NULL; - // Setup head - head=zeroHead->next; - // Delete dummy nodes - delete zeroHead; - delete oneHead; - delete twoHead; - return head; - } - - - - - - // Merge sort in two sorted LL - Node* solve(Node* first, Node* second){ - if(first->next==NULL){ - first->next=second; - return first; -} - Node*curr1=first; - Node*next1=curr1->next; - Node*curr2=second; - Node*next2=curr2->next; - while(next1!=NULL &&curr2!=NULL){ - if((curr2->data>=curr1->data)&&(curr2->data<=next1->data)){ -// add node in between first LL - curr1->next=curr2; - next2=curr2->next; - curr2->next=next1; -// Update pointers - curr1=curr2; - curr2=next2; -} - else{ -// curr1 and next1 ko aage bhadana h - curr1=next1; - next1=next1->next; - if(next1==NULL){ - curr1->next=curr2; - return first; -} -} - - return first; -} -Node* sortTwoLists(Node* first, Node* second){ - -// Write your code here. - if(first==NULL){ -return second; - } - if(second==NULL){ -return first; - } - if(first->data<=second->data){ - return solve(first,second); - } - else{ - return solve(second,first); - } -} - - - - - - - -// Merge sort in LL - private: - Node*merge( Node*left,Node*right){ - if(left==NULL){ -return right; - } - if(right==NULL){ - return left; - } - Node*ans=new Node(-1); - Node*temp=ans; -// merge two sorted LL - while(left!=NULL&&right!=NULL){ - if(left->data < right->data) { - temp->next=left; - temp=left; - left=left->next; -} - else{ - temp->next=right; - temp=right; - right=right->next; -} - } - while(left!=NULL){ - temp->next=left; - temp=left; - left=left->next; - } - while(right!=NULL){ - temp->next=right; - temp=right; - right=right->next; - } - ans=ans->next; - return ans; - } -Node*findMid(Node*head){ - Node*slow=head; - Node*fast=head->next; - while(fast!=NULL && fast->next!=NULL){ - fast=fast->next->next; - slow=slow->next;3 -} - return slow; -} - public: - //Function to sort the given linked list using Merge Sort. - Node* mergeSort(Node* head) { - // your code here - if(head==NULL || head->next==NULL){ - return head; - } -// break LL into two halves,after finding mid - Node*mid=findMid(head); - Node*left=head; - Node*right=mid->next; - mid->next=NULL; -// recursove calls to solve both halves - left=mergeSort(left); - right=mergeSort(right); -// merge both left and right halves - Node*result=merge(left,right); - return result; - - } - - - // Delete middle Node - Node* deleteMid(Node* head) -{ - // Your Code Here - Node*slow=head; - Node*fast=head; - while(fast!=NULL&&fast->next!=NULL){ - fast=fast->next->next; - slow=slow->next; - } - if(slow->next==NULL){ - head->next=NULL; - return head; - } - slow->data=slow->next->data; - slow->next=slow->next->next; - return head; -} -} - - -// duplicates from unsorted LL - Node * removeDuplicates( Node *head) - { - // your code goes here - if(head==NULL){ - return NULL; - } - map visited; - Node*curr=head; - visited[curr->data]=1; - Node*prev=head; - curr=curr->next; - while(curr!=NULL){ - if(visited[curr->data]){ - prev->next=curr->next; - delete curr; - } - else{ - visited[curr->data]=1; - prev=prev->next; - } - curr=curr->next; - - } - return head; +#include +#include +using namespace std; +class Node +{ +public: + int data; + Node *next; + // Constructor + Node(int data) + { + this->data = data; + this->next = NULL; + } + // Destructor + ~Node() + { + int value = this->data; + // memory free + + if (this->next != NULL) + { + delete next; + this->next = NULL; + } + cout << "Memory is free for mode with data " << value << endl; + } +}; +void InsertAtHead(Node *&head, int d) +{ + // New node create + Node *temp = new Node(d); + temp->next = head; + head = temp; +} +void InsertAtTail(Node *&tail, int d) +{ + Node *temp = new Node(d); + tail->next = temp; + tail = temp; +} +void InsertAtPosition(Node *&head, int position, int d) +{ + // Insert at start + if (position == 1) + { + InsertAtHead(head, d); + return; + } + + Node *temp = head; + int cnt = 1; + while (cnt < position - 1) + { + temp = temp->next; + cnt++; + } + // Creating a node for d + Node *nodeToInsert = new Node(d); + nodeToInsert->next = temp->next; + temp->next = nodeToInsert; +} +void DeleteNode(int position, Node *&head) +{ + // Deleting first node: + if (position == 1) + { + Node *temp = head; + head = head->next; + // memory free start node + temp->next = NULL; + delete temp; + } + else + { + // deleting any middle node or last node: + Node *curr = head; + Node *prev = NULL; + int cnt = 1; + while (cnt < position) + { + prev = curr; + curr = curr->next; + curr->next = NULL; + cnt++; + } + prev->next = curr->next; + delete curr; + } +} +void print(Node *&head) +{ + Node *temp = head; + while (temp != NULL) + { + cout << temp->data << " "; + temp = temp->next; + } + cout << endl; +} +Node *floydDetectLoop(Node *head) +{ + if (head == NULL) + { + return NULL; + } + Node *slow = head; + Node *fast = head; + while (slow!=NULL&&fast!=NULL) + { + fast=fast->next; + if(fast!=NULL){ + fast=fast->next; + + } + slow=slow->next; + if (slow==fast) + { + return true; + } + return false; + + } + + +} +Node *startingNodeLoop(Node *head) +{ + if (head == NULL) + { + return NULL; + } + Node *intersection = detectLoop(head); + Node *slow = head; + while (slow != intersection) + { + slow = slow->next; + intersection = intersection->next; + } + return slow; +} + void removeLoop(Node* head) + { + // code here + // just remove the loop without losing any nodes + if(head==NULL){ + return ; + } + Node*startingNode=getStartingNodeLoop(head); + Node*temp=startingNode; + while(temp->next!=startingNode){ + temp=temp->next; + } + temp->next=NULL; + + } +int main() +{ + // Create a new node + Node *node1 = new Node(10); + // cout << node1->data << endl; + // cout << node1->next << endl; + // head pointer to node1 + Node *head = node1; + Node *tail = node1; + // print(head); + InsertAtHead(head, 12); + // print(head); + InsertAtHead(head, 15); + + InsertAtTail(tail, 10); + // print(head); + InsertAtTail(tail, 12); + // print(head); + tail->next = head->next; + + cout << "head : " << head->data << endl; + cout << "tail : " << tail->data << endl; + if (detectLoop(head)) + { + cout << "Loop is present " << endl; + } + else + { + cout << "Loop is absent " << endl; + } + + // InsertAtTail(tail, 15); + // print(head); + // InsertAtPosition(head, 4, 22); + // print(head); + // DeleteNode(3, head); + // print(head); + return 0; +} + if(head==NULL){ + return false; + } + Node*slow=head; + Node*fast=head; + while(fast!=NULL&&slow!=NULL){ + fast=fast->next; + if(fast!=NULL){ + fast=fast->next; + } + slow=slow->next; + if(slow==fast){ + return true; + } + } + return false; + } + if (headA == NULL && headB == NULL) { + return 1; +} else if (headA == NULL || headB == NULL) { + return 0; +} + +if (headA->data == headB->data) { + return CompareLists(headA->next, headB->next); +} else { + return 0; +} + + +// Add 2 numbers in form of LL + Node*reverse(Node*head){ + Node*curr=head; + Node*prev=NULL; + Node*next=NULL; + while(curr!=NULL){ + next=curr->next; + curr->next=prev; + prev=curr; + curr=next; + } + return prev; + } + void insertAtTail(struct Node*&head, struct Node*&tail,int val){ + Node*temp=new Node(val); + // Empty list + if(head==NULL){ + head=temp; + tail=temp; + return; + } + else{ + tail->next=temp; + tail=temp; + } + + + } + struct Node* add(struct Node* first, struct Node* second){ + int carry=0; + + Node*ansHead=NULL; + Node*ansTail=NULL; + while(first!=NULL ||second!=NULL||carry!=0){ + int val1=0; + if(first!=NULL){ + val1=first->data; + } + int val2=0; + if(second!=NULL){ + val2=second->data; + } + + int sum=carry+val1+val2; + int digit=sum%10; + // Create node and add in answer LL + insertAtTail(ansHead,ansTail,digit); + carry=sum/10; + if(first!=NULL) + first=first->next; + if(second!=NULL) + second=second->next; + } + + return ansHead; + } + public: + //Function to add two numbers represented by linked list. + struct Node* addTwoLists(struct Node* first, struct Node* second) + { + // code here + // Step-1:reverse input linked list: + first=reverse(first); + second=reverse(second); + // Step-2:Add 2 LL + Node*ans=add(first,second); + // Step-3:reverse ans wali LL + ans=reverse(ans); + + + return ans; + } + void insertAtTail(Node*&tail,Node*&curr){ + tail->next=curr; + tail=curr; + } + //Function to sort a linked list of 0s, 1s and 2s. + Node* segregate(Node *head) { + + // Add code here + Node*zeroHead=new Node(-1); + Node*zeroTail=zeroHead; + Node*oneHead=new Node(-1); + Node*oneTail=oneHead; + Node*twoHead=new Node(-1); + Node*twoTail=twoHead; + Node*curr=head; + // Create a separate list for 0s 1s and 2s + while(curr!=NULL){ + int value=curr->data; + if(value==0){ + insertAtTail(zeroTail,curr); + + } + else if(value==1){ + insertAtTail(oneTail,curr); + } + else if(value==2){ + insertAtTail(twoTail,curr); + + } + curr=curr->next; + } + // Merge 3 sublist + if(oneHead->next!=NULL){ // 1's list is non-empty + zeroTail->next=oneHead->next; + } + else{ + // 1's list is empty + zeroTail->next=twoHead->next; + } + oneTail->next=twoHead->next; + twoTail->next=NULL; + // Setup head + head=zeroHead->next; + // Delete dummy nodes + delete zeroHead; + delete oneHead; + delete twoHead; + return head; + } + + + + + + // Merge sort in two sorted LL + Node* solve(Node* first, Node* second){ + if(first->next==NULL){ + first->next=second; + return first; +} + Node*curr1=first; + Node*next1=curr1->next; + Node*curr2=second; + Node*next2=curr2->next; + while(next1!=NULL &&curr2!=NULL){ + if((curr2->data>=curr1->data)&&(curr2->data<=next1->data)){ +// add node in between first LL + curr1->next=curr2; + next2=curr2->next; + curr2->next=next1; +// Update pointers + curr1=curr2; + curr2=next2; +} + else{ +// curr1 and next1 ko aage bhadana h + curr1=next1; + next1=next1->next; + if(next1==NULL){ + curr1->next=curr2; + return first; +} +} + + return first; +} +Node* sortTwoLists(Node* first, Node* second){ + +// Write your code here. + if(first==NULL){ +return second; + } + if(second==NULL){ +return first; + } + if(first->data<=second->data){ + return solve(first,second); + } + else{ + return solve(second,first); + } +} + + + + + + + +// Merge sort in LL + private: + Node*merge( Node*left,Node*right){ + if(left==NULL){ +return right; + } + if(right==NULL){ + return left; + } + Node*ans=new Node(-1); + Node*temp=ans; +// merge two sorted LL + while(left!=NULL&&right!=NULL){ + if(left->data < right->data) { + temp->next=left; + temp=left; + left=left->next; +} + else{ + temp->next=right; + temp=right; + right=right->next; +} + } + while(left!=NULL){ + temp->next=left; + temp=left; + left=left->next; + } + while(right!=NULL){ + temp->next=right; + temp=right; + right=right->next; + } + ans=ans->next; + return ans; + } +Node*findMid(Node*head){ + Node*slow=head; + Node*fast=head->next; + while(fast!=NULL && fast->next!=NULL){ + fast=fast->next->next; + slow=slow->next;3 +} + return slow; +} + public: + //Function to sort the given linked list using Merge Sort. + Node* mergeSort(Node* head) { + // your code here + if(head==NULL || head->next==NULL){ + return head; + } +// break LL into two halves,after finding mid + Node*mid=findMid(head); + Node*left=head; + Node*right=mid->next; + mid->next=NULL; +// recursove calls to solve both halves + left=mergeSort(left); + right=mergeSort(right); +// merge both left and right halves + Node*result=merge(left,right); + return result; + + } + + + // Delete middle Node + Node* deleteMid(Node* head) +{ + // Your Code Here + Node*slow=head; + Node*fast=head; + while(fast!=NULL&&fast->next!=NULL){ + fast=fast->next->next; + slow=slow->next; + } + if(slow->next==NULL){ + head->next=NULL; + return head; + } + slow->data=slow->next->data; + slow->next=slow->next->next; + return head; +} +} + + +// duplicates from unsorted LL + Node * removeDuplicates( Node *head) + { + // your code goes here + if(head==NULL){ + return NULL; + } + map visited; + Node*curr=head; + visited[curr->data]=1; + Node*prev=head; + curr=curr->next; + while(curr!=NULL){ + if(visited[curr->data]){ + prev->next=curr->next; + delete curr; + } + else{ + visited[curr->data]=1; + prev=prev->next; + } + curr=curr->next; + + } + return head; } \ No newline at end of file diff --git a/Linkedlist.exe b/Linked Lists/Linkedlist.exe similarity index 100% rename from Linkedlist.exe rename to Linked Lists/Linkedlist.exe diff --git a/OccurenceOfKeyinDLL.cpp b/Linked Lists/OccurenceOfKeyinDLL.cpp similarity index 96% rename from OccurenceOfKeyinDLL.cpp rename to Linked Lists/OccurenceOfKeyinDLL.cpp index cac7a19..6070be5 100644 --- a/OccurenceOfKeyinDLL.cpp +++ b/Linked Lists/OccurenceOfKeyinDLL.cpp @@ -1,51 +1,51 @@ -class Solution { - public: - void deleteAllOccurOfX(struct Node** head_ref, int x) { - // Write your code here - /* - Node*temp=*head_ref; - while(temp!=NULL){ - // occurence is at 1st node - if(temp->data==x){ - if(temp->prev==NULL){ - *head_ref=temp->next; - temp->prev=NULL; - } - - // occurence is at last node - else if(temp->next==NULL){ - temp->prev->next=NULL; - } - else{ - temp->prev->next=temp->next; - temp->next->prev=temp->prev; - } - } - temp=temp->next; - } - */ - Node*temp=*head_ref; - while(temp!=NULL){ - // occurence is at 1st node - if(temp->data==x){ - if(temp->prev==NULL){ - *head_ref=temp->next; - temp->prev=NULL; - } - - // occurence is at last node - else if(temp->next==NULL){ - temp->prev->next=NULL; - } - // occurence is in middle - else{ - temp->prev->next=temp->next; - temp->next->prev=temp->prev; - } - } - temp=temp->next; - } - - - } +class Solution { + public: + void deleteAllOccurOfX(struct Node** head_ref, int x) { + // Write your code here + /* + Node*temp=*head_ref; + while(temp!=NULL){ + // occurence is at 1st node + if(temp->data==x){ + if(temp->prev==NULL){ + *head_ref=temp->next; + temp->prev=NULL; + } + + // occurence is at last node + else if(temp->next==NULL){ + temp->prev->next=NULL; + } + else{ + temp->prev->next=temp->next; + temp->next->prev=temp->prev; + } + } + temp=temp->next; + } + */ + Node*temp=*head_ref; + while(temp!=NULL){ + // occurence is at 1st node + if(temp->data==x){ + if(temp->prev==NULL){ + *head_ref=temp->next; + temp->prev=NULL; + } + + // occurence is at last node + else if(temp->next==NULL){ + temp->prev->next=NULL; + } + // occurence is in middle + else{ + temp->prev->next=temp->next; + temp->next->prev=temp->prev; + } + } + temp=temp->next; + } + + + } }; \ No newline at end of file diff --git a/PalindromicLL.cpp b/Linked Lists/PalindromicLL.cpp similarity index 96% rename from PalindromicLL.cpp rename to Linked Lists/PalindromicLL.cpp index 36359fd..2007431 100644 --- a/PalindromicLL.cpp +++ b/Linked Lists/PalindromicLL.cpp @@ -1,45 +1,45 @@ -class Solution { -public: - ListNode*getMid( ListNode*head){ - ListNode*slow=head; - ListNode*fast=head->next; - while(fast!=NULL && fast->next!=NULL){ - fast=fast->next->next; - slow=slow->next; - - } - return slow; - } - ListNode*reverse(ListNode*head){ - ListNode*prev=NULL; - ListNode*curr=head; - ListNode*forward=NULL; - while(curr!=NULL){ - forward=curr->next; - curr->next=prev; - prev=curr; - curr=forward; - } - return prev; - } - bool isPalindrome(ListNode* head) { - if(head->next==NULL){ - return true; - } - ListNode*middle=getMid(head); - ListNode*temp=middle->next; - middle->next=reverse(temp); - ListNode*head1=head; - ListNode*head2=middle->next; - while(head2!=NULL){ - if(head1->val!=head2->val){ - return false; - } - head1=head1->next; - head2=head2->next; - } - temp=middle->next; - middle->next=reverse(temp); - return true; - } +class Solution { +public: + ListNode*getMid( ListNode*head){ + ListNode*slow=head; + ListNode*fast=head->next; + while(fast!=NULL && fast->next!=NULL){ + fast=fast->next->next; + slow=slow->next; + + } + return slow; + } + ListNode*reverse(ListNode*head){ + ListNode*prev=NULL; + ListNode*curr=head; + ListNode*forward=NULL; + while(curr!=NULL){ + forward=curr->next; + curr->next=prev; + prev=curr; + curr=forward; + } + return prev; + } + bool isPalindrome(ListNode* head) { + if(head->next==NULL){ + return true; + } + ListNode*middle=getMid(head); + ListNode*temp=middle->next; + middle->next=reverse(temp); + ListNode*head1=head; + ListNode*head2=middle->next; + while(head2!=NULL){ + if(head1->val!=head2->val){ + return false; + } + head1=head1->next; + head2=head2->next; + } + temp=middle->next; + middle->next=reverse(temp); + return true; + } }; \ No newline at end of file diff --git a/ReverseDLL.cpp b/Linked Lists/ReverseDLL.cpp similarity index 95% rename from ReverseDLL.cpp rename to Linked Lists/ReverseDLL.cpp index 3695999..a17cf92 100644 --- a/ReverseDLL.cpp +++ b/Linked Lists/ReverseDLL.cpp @@ -1,35 +1,35 @@ -Node* reverseDLL(Node * head) -{ - //Your code here - // Node*temp=head; - // while(temp!=NULL){ - // swap(temp->next,temp->prev); - // head=temp; - // temp=temp->prev; - // } - // return head; - /* - Node*temp=head; - while(temp!=NULL){ - swap(temp->next,temp->prev); - head=temp; - temp=temp->prev; - } - return head; - - Node*temp=head; - while(temp!=NULL){ - swap(temp->next,temp->prev); - head=temp; - temp=temp->prev; - } - return head; - */ - Node*temp=head; - while(temp!=NULL){ - swap(temp->next,temp->prev); - head=temp; - temp=temp->prev; - } - return head; +Node* reverseDLL(Node * head) +{ + //Your code here + // Node*temp=head; + // while(temp!=NULL){ + // swap(temp->next,temp->prev); + // head=temp; + // temp=temp->prev; + // } + // return head; + /* + Node*temp=head; + while(temp!=NULL){ + swap(temp->next,temp->prev); + head=temp; + temp=temp->prev; + } + return head; + + Node*temp=head; + while(temp!=NULL){ + swap(temp->next,temp->prev); + head=temp; + temp=temp->prev; + } + return head; + */ + Node*temp=head; + while(temp!=NULL){ + swap(temp->next,temp->prev); + head=temp; + temp=temp->prev; + } + return head; } \ No newline at end of file diff --git a/RotateLL.cpp b/Linked Lists/RotateLL.cpp similarity index 95% rename from RotateLL.cpp rename to Linked Lists/RotateLL.cpp index 3e4ff08..5a2c041 100644 --- a/RotateLL.cpp +++ b/Linked Lists/RotateLL.cpp @@ -1,31 +1,31 @@ -class Solution -{ - public: - Node* getlastNode(Node*head){ - Node*temp=head; - while(temp->next!=NULL){ - temp=temp->next; - - } - return temp; - } - //Function to rotate a linked list. - Node* rotate(Node* head, int k) - { - // Your code here - if(head==NULL ||head->next==NULL){ - return head; - } - Node*temp=head; - Node*lastNode=getlastNode(temp); - while(k){ - Node*forward=head->next; - lastNode->next=head; - lastNode=head; - head=head->next; - lastNode->next=NULL; - --k; - } - return head; - } +class Solution +{ + public: + Node* getlastNode(Node*head){ + Node*temp=head; + while(temp->next!=NULL){ + temp=temp->next; + + } + return temp; + } + //Function to rotate a linked list. + Node* rotate(Node* head, int k) + { + // Your code here + if(head==NULL ||head->next==NULL){ + return head; + } + Node*temp=head; + Node*lastNode=getlastNode(temp); + while(k){ + Node*forward=head->next; + lastNode->next=head; + lastNode=head; + head=head->next; + lastNode->next=NULL; + --k; + } + return head; + } }; \ No newline at end of file diff --git a/Codechef.cpp b/Misc/Codechef.cpp similarity index 94% rename from Codechef.cpp rename to Misc/Codechef.cpp index cda7c87..96a2b20 100644 --- a/Codechef.cpp +++ b/Misc/Codechef.cpp @@ -1,29 +1,29 @@ -#include -#include -using namespace std; -int main() -{ - // your code goes here - int T; - char S[1000]; - cout << "Enter the no. of test cases" << endl; - cin >> T; - cout<<"Enter the string S"< 2) - { - cout << "HAppy" << endl; - } - else - { - cout << "Sad" << endl; - } - } - return 0; -} +#include +#include +using namespace std; +int main() +{ + // your code goes here + int T; + char S[1000]; + cout << "Enter the no. of test cases" << endl; + cin >> T; + cout<<"Enter the string S"< 2) + { + cout << "HAppy" << endl; + } + else + { + cout << "Sad" << endl; + } + } + return 0; +} diff --git a/Codechef.exe b/Misc/Codechef.exe similarity index 100% rename from Codechef.exe rename to Misc/Codechef.exe diff --git a/Heap.cpp b/Misc/Heap.cpp similarity index 95% rename from Heap.cpp rename to Misc/Heap.cpp index 4354ea5..ef9803b 100644 --- a/Heap.cpp +++ b/Misc/Heap.cpp @@ -1,158 +1,158 @@ -#include -#include -using namespace std; -class heap -{ -public: - int arr[100]; - int size = 0; - heap() - { - arr[0] = -1; - size = 0; - } - void insert(int val) - { - size = size + 1; - int index = size; - arr[index] = val; - while (index > 1) - { - int parent = index / 2; - if (arr[parent] < arr[index]) - { - swap(arr[parent], arr[index]); - index = parent; - } - else - { - return; - } - } - } - void DeleteFromHeap() - { - if (size == 0) - { - cout << "Nothing to delete " << endl; - return; - } - arr[1] = arr[size]; - size--; - // take root node to its correct position - int i = 1; - while (i < size) - { - int leftIndex = 2 * i; - int rightIndex = 2 * i + 1; - if (leftIndex < size && arr[i] < arr[leftIndex]) - { - swap(arr[i], arr[leftIndex]); - i = leftIndex; - } - else if (rightIndex < size && arr[i] < arr[rightIndex]) - { - swap(arr[i], arr[rightIndex]); - i = rightIndex; - } - else - { - return; - } - } - } - void print() - { - for (int i = 1; i <= size; i++) - { - cout << arr[i] << " "; - } - cout << endl; - } -}; -void heapify(int arr[], int n, int i) -{ - int largest = i; - int left = 2 * i; - int right = 2 * i + 1; - if (left <= n && arr[largest] < arr[left]) - { - largest = left; - } - - if (right <= n && arr[largest] < arr[right]) - { - largest = right; - } - if (largest != i) - { - swap(arr[largest], arr[i]); - heapify(arr, n, largest); - } -} -void heapSort(int arr[], int n) -{ - int size = n; - while (size > 1) - { - // step-1:swap - swap(arr[size], arr[1]); - // step-2: - size--; - - heapify(arr, size, 1); - } -} -int main() -{ - heap h; - h.insert(50); - h.insert(55); - h.insert(53); - h.insert(52); - h.insert(54); - h.print(); - h.DeleteFromHeap(); - h.print(); - int arr[6] = {-1, 54, 53, 55, 52, 50}; - int n = 5; - for (int i = 5 / 2; i > 0; i--) - { - heapify(arr, n, i); - } - cout << "printing array " << endl; - for (int i = 1; i <= n; i++) - { - cout << arr[i] << " "; - } - cout << endl; - heapSort(arr, n); - cout << "printing sorted array " << endl; - for (int i = 1; i <= n; i++) - { - cout << arr[i] << " "; - } - cout << endl; - - cout << "Using priority queue " << endl; - // max heap - priority_queue pq; - pq.push(4); - pq.push(2); - pq.push(5); - pq.push(3); - cout << pq.top() << endl; - pq.pop(); - cout << pq.top() << endl; - // min heap - priority_queue,greater >minHeap; - minHeap.push(4); - minHeap.push(2); - minHeap.push(5); - minHeap.push(3); - cout << pq.top() << endl; - minHeap.pop(); - cout << pq.top() << endl; - - return 0; +#include +#include +using namespace std; +class heap +{ +public: + int arr[100]; + int size = 0; + heap() + { + arr[0] = -1; + size = 0; + } + void insert(int val) + { + size = size + 1; + int index = size; + arr[index] = val; + while (index > 1) + { + int parent = index / 2; + if (arr[parent] < arr[index]) + { + swap(arr[parent], arr[index]); + index = parent; + } + else + { + return; + } + } + } + void DeleteFromHeap() + { + if (size == 0) + { + cout << "Nothing to delete " << endl; + return; + } + arr[1] = arr[size]; + size--; + // take root node to its correct position + int i = 1; + while (i < size) + { + int leftIndex = 2 * i; + int rightIndex = 2 * i + 1; + if (leftIndex < size && arr[i] < arr[leftIndex]) + { + swap(arr[i], arr[leftIndex]); + i = leftIndex; + } + else if (rightIndex < size && arr[i] < arr[rightIndex]) + { + swap(arr[i], arr[rightIndex]); + i = rightIndex; + } + else + { + return; + } + } + } + void print() + { + for (int i = 1; i <= size; i++) + { + cout << arr[i] << " "; + } + cout << endl; + } +}; +void heapify(int arr[], int n, int i) +{ + int largest = i; + int left = 2 * i; + int right = 2 * i + 1; + if (left <= n && arr[largest] < arr[left]) + { + largest = left; + } + + if (right <= n && arr[largest] < arr[right]) + { + largest = right; + } + if (largest != i) + { + swap(arr[largest], arr[i]); + heapify(arr, n, largest); + } +} +void heapSort(int arr[], int n) +{ + int size = n; + while (size > 1) + { + // step-1:swap + swap(arr[size], arr[1]); + // step-2: + size--; + + heapify(arr, size, 1); + } +} +int main() +{ + heap h; + h.insert(50); + h.insert(55); + h.insert(53); + h.insert(52); + h.insert(54); + h.print(); + h.DeleteFromHeap(); + h.print(); + int arr[6] = {-1, 54, 53, 55, 52, 50}; + int n = 5; + for (int i = 5 / 2; i > 0; i--) + { + heapify(arr, n, i); + } + cout << "printing array " << endl; + for (int i = 1; i <= n; i++) + { + cout << arr[i] << " "; + } + cout << endl; + heapSort(arr, n); + cout << "printing sorted array " << endl; + for (int i = 1; i <= n; i++) + { + cout << arr[i] << " "; + } + cout << endl; + + cout << "Using priority queue " << endl; + // max heap + priority_queue pq; + pq.push(4); + pq.push(2); + pq.push(5); + pq.push(3); + cout << pq.top() << endl; + pq.pop(); + cout << pq.top() << endl; + // min heap + priority_queue,greater >minHeap; + minHeap.push(4); + minHeap.push(2); + minHeap.push(5); + minHeap.push(3); + cout << pq.top() << endl; + minHeap.pop(); + cout << pq.top() << endl; + + return 0; } \ No newline at end of file diff --git a/Heap.exe b/Misc/Heap.exe similarity index 100% rename from Heap.exe rename to Misc/Heap.exe diff --git a/Intersection.cpp b/Misc/Intersection.cpp similarity index 95% rename from Intersection.cpp rename to Misc/Intersection.cpp index d862d19..b5b5d2a 100644 --- a/Intersection.cpp +++ b/Misc/Intersection.cpp @@ -1,21 +1,21 @@ -mapm; - - mapresult; - vectorans; - - for(int i=0;im; + + mapresult; + vectorans; + + for(int i=0;i -using namespace std; -int main() -{ - - int a, b; - cout << "Enter the two numbers " << endl; - cin >> a >> b; - a > b ? cout << " a is maximum" : cout << "b is maximum" << endl; - - - - return 0; +#include +using namespace std; +int main() +{ + + int a, b; + cout << "Enter the two numbers " << endl; + cin >> a >> b; + a > b ? cout << " a is maximum" : cout << "b is maximum" << endl; + + + + return 0; } \ No newline at end of file diff --git a/MaxOf2nums.exe b/Misc/MaxOf2nums.exe similarity index 100% rename from MaxOf2nums.exe rename to Misc/MaxOf2nums.exe diff --git a/SudokuSolver.cpp b/Misc/SudokuSolver.cpp similarity index 96% rename from SudokuSolver.cpp rename to Misc/SudokuSolver.cpp index 321c1fd..ed197f5 100644 --- a/SudokuSolver.cpp +++ b/Misc/SudokuSolver.cpp @@ -1,77 +1,77 @@ -class Solution -{ -public: - bool isSafe(int row, int col, int grid[N][N], int val) - { - - for (int i = 0; i < N; i++) - { - // row check - if (grid[row][i] == val) - { - return false; - } - // col check - if (grid[i][col] == val) - { - return false; - } - // 3x3 matrix check - if (grid[3 * (row / 3) + i / 3][(3 * (col / 3)) + i % 3] == val) - { - return false; - } - } - return true; - } - // Function to find a solved Sudoku. - bool SolveSudoku(int grid[N][N]) - { - // Your code here - - for (int row = 0; row < N; row++) - { - for (int col = 0; col < N; col++) - { - // cell empty - if (grid[row][col] == 0) - { - for (int val = 1; val <= 9; val++) - { - if (isSafe(row, col, grid, val)) - { - grid[row][col] = val; - // recursive call - bool aageSolutionPossible = SolveSudoku(grid); - if (aageSolutionPossible) - { - return true; - } - else - { - // backtrack - grid[row][col] = 0; - } - } - } - return false; - } - } - } - return true; - } - - // Function to print grids of the Sudoku. - void printGrid(int grid[N][N]) - { - // Your code here - SolveSudoku(grid); - for (int i = 0; i < N; i++) - { - for (int j = 0; j < N; j++) - { - cout << grid[i][j] << " "; - } - } - } -}; +class Solution +{ +public: + bool isSafe(int row, int col, int grid[N][N], int val) + { + + for (int i = 0; i < N; i++) + { + // row check + if (grid[row][i] == val) + { + return false; + } + // col check + if (grid[i][col] == val) + { + return false; + } + // 3x3 matrix check + if (grid[3 * (row / 3) + i / 3][(3 * (col / 3)) + i % 3] == val) + { + return false; + } + } + return true; + } + // Function to find a solved Sudoku. + bool SolveSudoku(int grid[N][N]) + { + // Your code here + + for (int row = 0; row < N; row++) + { + for (int col = 0; col < N; col++) + { + // cell empty + if (grid[row][col] == 0) + { + for (int val = 1; val <= 9; val++) + { + if (isSafe(row, col, grid, val)) + { + grid[row][col] = val; + // recursive call + bool aageSolutionPossible = SolveSudoku(grid); + if (aageSolutionPossible) + { + return true; + } + else + { + // backtrack + grid[row][col] = 0; + } + } + } + return false; + } + } + } + return true; + } + + // Function to print grids of the Sudoku. + void printGrid(int grid[N][N]) + { + // Your code here + SolveSudoku(grid); + for (int i = 0; i < N; i++) + { + for (int j = 0; j < N; j++) + { + cout << grid[i][j] << " "; + } + } + } +}; diff --git a/Tom&Jerry.cpp b/Misc/Tom&Jerry.cpp similarity index 92% rename from Tom&Jerry.cpp rename to Misc/Tom&Jerry.cpp index 97bebf6..4733b69 100644 --- a/Tom&Jerry.cpp +++ b/Misc/Tom&Jerry.cpp @@ -1,17 +1,17 @@ -class Solution -{ - int numsGame(int N) - { - // code here - if (N & 1 == 1) - { - - return 0; - } - else - { - - return 1; - } - } +class Solution +{ + int numsGame(int N) + { + // code here + if (N & 1 == 1) + { + + return 0; + } + else + { + + return 1; + } + } }; \ No newline at end of file diff --git a/Trie.cpp b/Misc/Trie.cpp similarity index 95% rename from Trie.cpp rename to Misc/Trie.cpp index 29dd602..bb7b74f 100644 --- a/Trie.cpp +++ b/Misc/Trie.cpp @@ -1,90 +1,90 @@ -#include -#include -using namespace std; -class TrieNode -{ -public: - char data; - TrieNode *children[26]; - bool isTerminal; - TrieNode(char ch) - { - data = ch; - for (int i = 0; i < 26; i++) - { - children[i] = NULL; - } - isTerminal = false; - } -}; -class Trie -{ -public: - TrieNode *root; - Trie() - { - root = new TrieNode('\0'); - } - void insertUtil(TrieNode *root, string word) - { - // base case - if (word.length() == 0) - { - root->isTerminal = true; - return; - } - // assumption-->word will be in caps - int index = word[0] - 'A'; - TrieNode *child; - if (root->children[index] != NULL) - { - // present - child = root->children[index]; - } - else - { - // absent - child = new TrieNode(word[0]); - root->children[index] = child; - } - insertUtil(child, word.substr(1)); - } - void insertWord(string word) - { - insertUtil(root, word); - } - bool searchUtil(TrieNode *root, string word) - { - // base case - if (word.length() == 0) - { - return root->isTerminal; - } - int index = word[0] - 'A'; - TrieNode *child; - // present - if (root->children[index] != NULL) - { - child = root->children[index]; - } - // absent - else - { - return false; - } - return searchUtil(child, word.substr(1)); - } - - bool searchWord(string word) - { - return searchUtil(root, word); - } -}; -int main() -{ - Trie *t = new Trie(); - - t->insertWord("ABCD"); - cout << "present or not " << t->searchWord("ABC") << endl; - return 0; +#include +#include +using namespace std; +class TrieNode +{ +public: + char data; + TrieNode *children[26]; + bool isTerminal; + TrieNode(char ch) + { + data = ch; + for (int i = 0; i < 26; i++) + { + children[i] = NULL; + } + isTerminal = false; + } +}; +class Trie +{ +public: + TrieNode *root; + Trie() + { + root = new TrieNode('\0'); + } + void insertUtil(TrieNode *root, string word) + { + // base case + if (word.length() == 0) + { + root->isTerminal = true; + return; + } + // assumption-->word will be in caps + int index = word[0] - 'A'; + TrieNode *child; + if (root->children[index] != NULL) + { + // present + child = root->children[index]; + } + else + { + // absent + child = new TrieNode(word[0]); + root->children[index] = child; + } + insertUtil(child, word.substr(1)); + } + void insertWord(string word) + { + insertUtil(root, word); + } + bool searchUtil(TrieNode *root, string word) + { + // base case + if (word.length() == 0) + { + return root->isTerminal; + } + int index = word[0] - 'A'; + TrieNode *child; + // present + if (root->children[index] != NULL) + { + child = root->children[index]; + } + // absent + else + { + return false; + } + return searchUtil(child, word.substr(1)); + } + + bool searchWord(string word) + { + return searchUtil(root, word); + } +}; +int main() +{ + Trie *t = new Trie(); + + t->insertWord("ABCD"); + cout << "present or not " << t->searchWord("ABC") << endl; + return 0; } \ No newline at end of file diff --git a/Trie.exe b/Misc/Trie.exe similarity index 100% rename from Trie.exe rename to Misc/Trie.exe diff --git a/QueueUsingArray.java b/Queue/QueueUsingArray.java similarity index 95% rename from QueueUsingArray.java rename to Queue/QueueUsingArray.java index b557056..5b81b18 100644 --- a/QueueUsingArray.java +++ b/Queue/QueueUsingArray.java @@ -1,58 +1,58 @@ -public class QueueUsingArray { - - private int[] array; - private int front; - private int rear; - - public QueueUsingArray(int size) { - array = new int[size]; - front = 0; - rear = -1; - } - - public void enqueue(int item) { - if (rear == array.length - 1) { - System.out.println("Queue is full."); - } else { - System.out.println("Element enqueued in the queue " + item); - rear++; - array[rear] = item; - } - } - - public int dequeue() { - if (front > rear) { - System.out.println("Queue is empty."); - return -1; - } else { - - int item = array[front]; - front++; - System.out.println("Element dequeued from the queue " + item); - return item; - } - } - - public int peek() { - if (front > rear) { - System.out.println("Queue is empty."); - return -1; - } else { - System.out.println("Peek element is " + array[front]); - return array[front]; - } - } - - public boolean isEmpty() { - return (front > rear); - } - - public static void main(String[] args) { - QueueUsingArray q = new QueueUsingArray(5); - q.enqueue(5); - q.enqueue(12); - q.enqueue(15); - q.dequeue(); - q.peek(); - } -} +public class QueueUsingArray { + + private int[] array; + private int front; + private int rear; + + public QueueUsingArray(int size) { + array = new int[size]; + front = 0; + rear = -1; + } + + public void enqueue(int item) { + if (rear == array.length - 1) { + System.out.println("Queue is full."); + } else { + System.out.println("Element enqueued in the queue " + item); + rear++; + array[rear] = item; + } + } + + public int dequeue() { + if (front > rear) { + System.out.println("Queue is empty."); + return -1; + } else { + + int item = array[front]; + front++; + System.out.println("Element dequeued from the queue " + item); + return item; + } + } + + public int peek() { + if (front > rear) { + System.out.println("Queue is empty."); + return -1; + } else { + System.out.println("Peek element is " + array[front]); + return array[front]; + } + } + + public boolean isEmpty() { + return (front > rear); + } + + public static void main(String[] args) { + QueueUsingArray q = new QueueUsingArray(5); + q.enqueue(5); + q.enqueue(12); + q.enqueue(15); + q.dequeue(); + q.peek(); + } +} diff --git a/QueueusingLL.cpp b/Queue/QueueusingLL.cpp similarity index 96% rename from QueueusingLL.cpp rename to Queue/QueueusingLL.cpp index 8ebacd8..7c5a4cf 100644 --- a/QueueusingLL.cpp +++ b/Queue/QueueusingLL.cpp @@ -1,75 +1,75 @@ -#include -#include -struct node { - int data; - struct node * next; -}; -struct node * front = NULL; -struct node * rear = NULL; -void push(int value) { - struct node * ptr; - ptr = (struct node * ) malloc(sizeof(struct node)); - ptr -> data = value; - ptr -> next = NULL; - if ((front == NULL) && (rear == NULL)) { - front = rear = ptr; - } else { - rear -> next = ptr; - rear = ptr; - } - printf("Node is Inserted\n"); -} -int pop() { - if (front == NULL) { - printf("\nUnderflow\n"); - return -1; - } else { - struct node * temp = front; - int temp_data = front -> data; - front = front -> next; - free(temp); - return temp_data; - } -} -void display() { - struct node * temp; - if ((front == NULL) && (rear == NULL)) { - printf("\nQueue is Empty\n"); - } else { - printf("The queue is \n"); - temp = front; - while (temp) { - printf("%d--->", temp -> data); - temp = temp -> next; - } - printf("NULL\n"); - } -} -int main() { - int choice, value; - printf("\nImplementation of Queue using Linked List\n"); - while (choice) { - printf("1.Push 2.Pop 3.Display 4.Exit\n"); - printf("Enter your choice : "); - scanf("%d", & choice); - switch (choice) { - case 1: - printf("\nEnter the value to insert: "); - scanf("%d", & value); - push(value); - break; - case 2: - printf("Popped element is :%d\n", pop()); - break; - case 3: - display(); - break; - case 4: - printf("Exit\n"); - break; - default: - printf("\nWrong Choice\n"); - } - } - return 0; -} +#include +#include +struct node { + int data; + struct node * next; +}; +struct node * front = NULL; +struct node * rear = NULL; +void push(int value) { + struct node * ptr; + ptr = (struct node * ) malloc(sizeof(struct node)); + ptr -> data = value; + ptr -> next = NULL; + if ((front == NULL) && (rear == NULL)) { + front = rear = ptr; + } else { + rear -> next = ptr; + rear = ptr; + } + printf("Node is Inserted\n"); +} +int pop() { + if (front == NULL) { + printf("\nUnderflow\n"); + return -1; + } else { + struct node * temp = front; + int temp_data = front -> data; + front = front -> next; + free(temp); + return temp_data; + } +} +void display() { + struct node * temp; + if ((front == NULL) && (rear == NULL)) { + printf("\nQueue is Empty\n"); + } else { + printf("The queue is \n"); + temp = front; + while (temp) { + printf("%d--->", temp -> data); + temp = temp -> next; + } + printf("NULL\n"); + } +} +int main() { + int choice, value; + printf("\nImplementation of Queue using Linked List\n"); + while (choice) { + printf("1.Push 2.Pop 3.Display 4.Exit\n"); + printf("Enter your choice : "); + scanf("%d", & choice); + switch (choice) { + case 1: + printf("\nEnter the value to insert: "); + scanf("%d", & value); + push(value); + break; + case 2: + printf("Popped element is :%d\n", pop()); + break; + case 3: + display(); + break; + case 4: + printf("Exit\n"); + break; + default: + printf("\nWrong Choice\n"); + } + } + return 0; +} diff --git a/Celebrity problem.cpp b/Stack/Celebrity problem.cpp similarity index 92% rename from Celebrity problem.cpp rename to Stack/Celebrity problem.cpp index 6ed5284..bcfa2a9 100644 --- a/Celebrity problem.cpp +++ b/Stack/Celebrity problem.cpp @@ -1,63 +1,66 @@ - bool knows(vector >& M,int a,int b,int n){ - if(M[a][b]==1){ - return true; - } - else{ - return false; - } - } - public: - //Function to find if there is a celebrity in the party or not. - int celebrity(vector >& M, int n) - { - // code here - stacks; - // Step-1: push all elements in stack - for(int i=0;i1){ - int a=s.top(); - s.pop(); - int b=s.top(); - s.pop(); - if(knows(M,a,b,n)){ - s.push(b); - } - else{ - s.push(a); - } - } - int candidate=s.top(); - // Step-3: single element in stack is "Potential Celebrity" - // so verify it. - bool rowCheck=false; - int ZeroCount=0; - for(int i=0;i +#include +#include + bool knows(vector>&M,int a,int b,int n){ + if(M[a][b]==1){ + return true; + } + else{ + return false; + } + } + public: + //Function to find if there is a celebrity in the party or not. + int celebrity(vector >& M, int n) + { + // code here + stacks; + // Step-1: push all elements in stack + for(int i=0;i1){ + int a=s.top(); + s.pop(); + int b=s.top(); + s.pop(); + if(knows(M,a,b,n)){ + s.push(b); + } + else{ + s.push(a); + } + } + int candidate=s.top(); + // Step-3: single element in stack is "Potential Celebrity" + // so verify it. + bool rowCheck=false; + int ZeroCount=0; + for(int i=0;i -#include -using namespace std; -int main() -{ - string str = "babbar"; - stack s; - for (int i = 0; i < str.length(); i++) - { - char ch = str[i]; - s.push(ch); - } - string ans = ""; - while (!s.empty()) - { - char ch = s.top(); - ans.push_back(ch); - s.pop(); - } - cout << "Answer is " << ans << endl; - - return 0; +#include +#include +using namespace std; +int main() +{ + string str = "babbar"; + stack s; + for (int i = 0; i < str.length(); i++) + { + char ch = str[i]; + s.push(ch); + } + string ans = ""; + while (!s.empty()) + { + char ch = s.top(); + ans.push_back(ch); + s.pop(); + } + cout << "Answer is " << ans << endl; + + return 0; } \ No newline at end of file diff --git a/StackQuestions.exe b/Stack/StackQuestions.exe similarity index 100% rename from StackQuestions.exe rename to Stack/StackQuestions.exe diff --git a/StackUsingArray.cpp b/Stack/StackUsingArray.cpp similarity index 93% rename from StackUsingArray.cpp rename to Stack/StackUsingArray.cpp index 4eafd53..5de92bb 100644 --- a/StackUsingArray.cpp +++ b/Stack/StackUsingArray.cpp @@ -1,73 +1,73 @@ -#include -using namespace std; -class Stack -{ - // Properties -public: - int *arr; - int top; - int size; - - // Behaviour - Stack(int size) - { - this->size = size; - arr = new int[size]; - top = -1; - } - void push(int element) - { - if (size - top > 1) - { - top++; - arr[top] = element; - } - else - { - cout << "Stack OverFlow " << endl; - } - } - void pop() - { - if (top >= 0) - { - top--; - } - else - { - cout << "Stack UnderFlow " << endl; - } - } - int peak() - { - if (top >= 0) - return arr[top]; - else - { - cout << "Stack is empty " << endl; - return -1; - } - } - bool isEmpty() - { - if (top == -1) - { - return true; - } - else - { - return false; - } - } -}; -int main() -{ - Stack st(5); - st.push(22); - st.push(43); - st.push(44); - st.push(22); - st.push(43); - st.pop(); - return 0; -} +#include +using namespace std; +class Stack +{ + // Properties +public: + int *arr; + int top; + int size; + + // Behaviour + Stack(int size) + { + this->size = size; + arr = new int[size]; + top = -1; + } + void push(int element) + { + if (size - top > 1) + { + top++; + arr[top] = element; + } + else + { + cout << "Stack OverFlow " << endl; + } + } + void pop() + { + if (top >= 0) + { + top--; + } + else + { + cout << "Stack UnderFlow " << endl; + } + } + int peak() + { + if (top >= 0) + return arr[top]; + else + { + cout << "Stack is empty " << endl; + return -1; + } + } + bool isEmpty() + { + if (top == -1) + { + return true; + } + else + { + return false; + } + } +}; +int main() +{ + Stack st(5); + st.push(22); + st.push(43); + st.push(44); + st.push(22); + st.push(43); + st.pop(); + return 0; +} diff --git a/stack.cpp b/Stack/stack.cpp similarity index 94% rename from stack.cpp rename to Stack/stack.cpp index 1a14d51..cb60ac4 100644 --- a/stack.cpp +++ b/Stack/stack.cpp @@ -1,206 +1,206 @@ -#include -#include - -using namespace std; - -/* -using namespace std; -class StackNode -{ - int data; - StackNode *next; - StackNode *head; - // Constructor - StackNode(int a) - { - this->data = a; - this->next = NULL; - } - void push(int x) - { - StackNode *temp = new StackNode(x); - temp->next = head; - head = temp; - } - int pop(int x) - { - if (head == NULL){ - return -1; - } - - int res = head->data; - StackNode *temp = head; - head = head->next; - delete (temp); - return res; - - } -}; -*/ -class ArrayStack -{ - int *arr; - int size; - int top; - ArrayStack(int size) - { - this->size = size; - arr = new int[size]; - top = -1; - } - void push(int element) - { - if (size - top > 1) - { - top++; - arr[top] = element; - } - else - { - cout << "Stack OverFlow" << endl; - } - } - void pop() - { - if (top >= 0) - { - top--; - } - else - { - cout << "Stack UnderFlow" << endl; - } - } - int peak() - { - if (top >= 0) - { - return arr[top]; - } - else - { - cout << "Stack is empty" << endl; - } - } - bool isEmpty() - { - if (top == -1) - { - return true; - } - else - { - return false; - } - } - }; - -/* -class Stack -{ - // Properties -public: - - int *arr; - int top; - int size; - - // Behaviour - Stack(int size) - { - this->size = size; - arr = new int[size]; - top = -1; - } - void push(int element) - { - if (size - top > 1) - { - top++; - arr[top] = element; - } - else - { - cout << "Stack OverFlow " << endl; - } - } - void pop() - { - if (top >= 0) - { - top--; - } - else - { - cout << "Stack UnderFlow " << endl; - } - } - int peak() - { - if (top >= 0) - return arr[top]; - else - { - cout << "Stack is empty " << endl; - return -1; - } - } - bool isEmpty() - { - if (top == -1) - { - return true; - } - else - { - return false; - } - } - */ - -int main() - -{ - ArrayStack st(5); - st.push(22); - st.push(43); - st.push(44); - st.push(22); - st.push(43); - st.push(44); - st.pop(44); - - cout << st.peak() << endl; - cout << st.peak() << endl; - st.pop(); - cout << st.peak() << endl; - st.pop(); - cout << st.peak() << endl; - if (st.isEmpty()) - { - cout << "Stack is empty" << endl; - } - else - { - cout << "Stack is not empty " << endl; - } - /* - stack s; // creation of stack - s.push(2); // insert operation - s.push(5); // insert operation - // s.pop(); // delete operation - s.pop(); // delete operation - cout << "Printing top element " << s.top() << endl; - if (s.empty()) - { - cout << "Stack is empty" << endl; - } - else - { - cout << "Stack is not empty " << endl; - } - cout << "Size of stack " << s.size() << endl; - */ - - return 0; +#include +#include + +using namespace std; + +/* +using namespace std; +class StackNode +{ + int data; + StackNode *next; + StackNode *head; + // Constructor + StackNode(int a) + { + this->data = a; + this->next = NULL; + } + void push(int x) + { + StackNode *temp = new StackNode(x); + temp->next = head; + head = temp; + } + int pop(int x) + { + if (head == NULL){ + return -1; + } + + int res = head->data; + StackNode *temp = head; + head = head->next; + delete (temp); + return res; + + } +}; +*/ +class ArrayStack +{ + int *arr; + int size; + int top; + ArrayStack(int size) + { + this->size = size; + arr = new int[size]; + top = -1; + } + void push(int element) + { + if (size - top > 1) + { + top++; + arr[top] = element; + } + else + { + cout << "Stack OverFlow" << endl; + } + } + void pop() + { + if (top >= 0) + { + top--; + } + else + { + cout << "Stack UnderFlow" << endl; + } + } + int peak() + { + if (top >= 0) + { + return arr[top]; + } + else + { + cout << "Stack is empty" << endl; + } + } + bool isEmpty() + { + if (top == -1) + { + return true; + } + else + { + return false; + } + } + }; + +/* +class Stack +{ + // Properties +public: + + int *arr; + int top; + int size; + + // Behaviour + Stack(int size) + { + this->size = size; + arr = new int[size]; + top = -1; + } + void push(int element) + { + if (size - top > 1) + { + top++; + arr[top] = element; + } + else + { + cout << "Stack OverFlow " << endl; + } + } + void pop() + { + if (top >= 0) + { + top--; + } + else + { + cout << "Stack UnderFlow " << endl; + } + } + int peak() + { + if (top >= 0) + return arr[top]; + else + { + cout << "Stack is empty " << endl; + return -1; + } + } + bool isEmpty() + { + if (top == -1) + { + return true; + } + else + { + return false; + } + } + */ + +int main() + +{ + ArrayStack st(5); + st.push(22); + st.push(43); + st.push(44); + st.push(22); + st.push(43); + st.push(44); + st.pop(44); + + cout << st.peak() << endl; + cout << st.peak() << endl; + st.pop(); + cout << st.peak() << endl; + st.pop(); + cout << st.peak() << endl; + if (st.isEmpty()) + { + cout << "Stack is empty" << endl; + } + else + { + cout << "Stack is not empty " << endl; + } + /* + stack s; // creation of stack + s.push(2); // insert operation + s.push(5); // insert operation + // s.pop(); // delete operation + s.pop(); // delete operation + cout << "Printing top element " << s.top() << endl; + if (s.empty()) + { + cout << "Stack is empty" << endl; + } + else + { + cout << "Stack is not empty " << endl; + } + cout << "Size of stack " << s.size() << endl; + */ + + return 0; } \ No newline at end of file diff --git a/stack.exe b/Stack/stack.exe similarity index 100% rename from stack.exe rename to Stack/stack.exe diff --git a/numbertoWords.c b/Strings/numbertoWords.c similarity index 94% rename from numbertoWords.c rename to Strings/numbertoWords.c index 3ee7da8..1a82b30 100644 --- a/numbertoWords.c +++ b/Strings/numbertoWords.c @@ -1,233 +1,233 @@ - -#include -#include -#include - - -char *ones[]={"", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"}; -char *ten_special[]={"","ten","eleven", "twelve", "thirteen","fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"}; -char *tens[]= {"","", "twenty", "thirty", "fourty", "fifty", "sixty", "seventy","eighty","ninety"}; -char *tens_power[] = {"","","","hundred", "thousand", "million","billion"}; - -void print(char *num) -{ - int n, n2, n3; - int len = strlen(num); - if (len == 1) - { - n = num[0] - 48; - printf("%s ", ones[n]); - - } - - - - - if (len == 2 && num[0]==49) - { - n = (num[0]-48) + (num[1] - 48); - printf("%s ", ten_special[n]); - } - - else if (len==2 && num[1] == 48) - { - n = (num[0]-48) + (num[1] - 48); - printf("%s ", tens[n]); - - } - else if (len==2) - { - n=num[0]-48; - n2=num[1] - 48; - printf("%s %s ", tens[n], ones[n2]); - - } - - - - - if (len==3 && num[1]==48 && num[2]==48) - { - n=num[0] - 48; - printf("%s %s ", ones[n],tens_power[len]); - - } - else if (len==3 && num[1]==48) - { - n=num[0] - 48; - printf("%s %s ", ones[n],tens_power[len]); - n2=num[2] - 48; - printf("%s ", ones[n2]); - } - else if (len==3 && num[2]==48) - { - n=num[0] - 48; - printf("%s %s ", ones[n],tens_power[len]); - n2=(num[1]-48) + (num[2] - 48); - printf("%s ", tens[n2]); - } - else if (len==3 && num[1]==49) - { - n=num[0] - 48; - printf("%s %s ", ones[n],tens_power[len]); - n2=(num[1]-48) + (num[2] - 48); - printf("%s ", ten_special[n2]); - } - else if (len==3) - { - n=num[0] - 48; - printf("%s %s ", ones[n],tens_power[len]); - n2=num[1]-48; - n3=num[2]-48; - printf("%s %s ", tens[n2], ones[n3]); - } -} - -int main() -{ - char num[20],temp[20]; - long long int number,temporary=0; - - printf("Enter a number: "); - scanf("%lld", &number); - - sprintf(num, "%lld", number); - - int length=strlen(num); - - if (length >12) - { - printf("\nError: Enter number less than a trillion!"); - exit(0); - } - - if (number==0) - { - printf("zero"); - exit(0); - } - - if (number >= 1000000000) - { - if (length == 12) - { - temporary=number/1000000000; - - sprintf(temp, "%lld", temporary); - print(temp); - - - } - - else if (length==11) - { - temporary=number/1000000000; - sprintf(temp, "%lld", temporary); - print(temp); - - } - - else - { - temporary=number/1000000000; - sprintf(temp, "%lld", temporary); - print(temp); - - } - printf("billion "); - } - - - length=9; - number=number % 1000000000; - temporary=0; - sprintf(num, "%lld", number); - - - if (number >= 1000000) - { - if (length==9) - { - temporary=number/1000000; - - sprintf(temp, "%lld", temporary); - print(temp); - } - - else if (length ==8) - { - temporary=number/1000000; - - sprintf(temp, "%lld", temporary); - print(temp); - } - - else - { - temporary=number/1000000; - - sprintf(temp, "%lld", temporary); - print(temp); - } - printf("million "); - } - - - - length=6; - number=number % 1000000; - temporary=0; - sprintf(num, "%lld", number); - - if (number >= 1000 ) - { - if (length==6) - { - temporary=number/1000; - - - sprintf(temp, "%lld", temporary); - print(temp); - } - - else if (length==5) - { - temporary=number/1000; - - - sprintf(temp, "%lld", temporary); - print(temp); - } - - else{ - temporary=number/1000; - - - sprintf(temp, "%lld", temporary); - print(temp); - } - printf("thousand "); - } - - length=3; - number=number % 1000; - temporary=0; - sprintf(num, "%lld", number); - - - - if (length==3 || length==2 || length ==1) - { - print(num); - } - - - - - else - printf("Enter postive value! "); - - printf("\n"); - - return 0; + +#include +#include +#include + + +char *ones[]={"", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"}; +char *ten_special[]={"","ten","eleven", "twelve", "thirteen","fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"}; +char *tens[]= {"","", "twenty", "thirty", "fourty", "fifty", "sixty", "seventy","eighty","ninety"}; +char *tens_power[] = {"","","","hundred", "thousand", "million","billion"}; + +void print(char *num) +{ + int n, n2, n3; + int len = strlen(num); + if (len == 1) + { + n = num[0] - 48; + printf("%s ", ones[n]); + + } + + + + + if (len == 2 && num[0]==49) + { + n = (num[0]-48) + (num[1] - 48); + printf("%s ", ten_special[n]); + } + + else if (len==2 && num[1] == 48) + { + n = (num[0]-48) + (num[1] - 48); + printf("%s ", tens[n]); + + } + else if (len==2) + { + n=num[0]-48; + n2=num[1] - 48; + printf("%s %s ", tens[n], ones[n2]); + + } + + + + + if (len==3 && num[1]==48 && num[2]==48) + { + n=num[0] - 48; + printf("%s %s ", ones[n],tens_power[len]); + + } + else if (len==3 && num[1]==48) + { + n=num[0] - 48; + printf("%s %s ", ones[n],tens_power[len]); + n2=num[2] - 48; + printf("%s ", ones[n2]); + } + else if (len==3 && num[2]==48) + { + n=num[0] - 48; + printf("%s %s ", ones[n],tens_power[len]); + n2=(num[1]-48) + (num[2] - 48); + printf("%s ", tens[n2]); + } + else if (len==3 && num[1]==49) + { + n=num[0] - 48; + printf("%s %s ", ones[n],tens_power[len]); + n2=(num[1]-48) + (num[2] - 48); + printf("%s ", ten_special[n2]); + } + else if (len==3) + { + n=num[0] - 48; + printf("%s %s ", ones[n],tens_power[len]); + n2=num[1]-48; + n3=num[2]-48; + printf("%s %s ", tens[n2], ones[n3]); + } +} + +int main() +{ + char num[20],temp[20]; + long long int number,temporary=0; + + printf("Enter a number: "); + scanf("%lld", &number); + + sprintf(num, "%lld", number); + + int length=strlen(num); + + if (length >12) + { + printf("\nError: Enter number less than a trillion!"); + exit(0); + } + + if (number==0) + { + printf("zero"); + exit(0); + } + + if (number >= 1000000000) + { + if (length == 12) + { + temporary=number/1000000000; + + sprintf(temp, "%lld", temporary); + print(temp); + + + } + + else if (length==11) + { + temporary=number/1000000000; + sprintf(temp, "%lld", temporary); + print(temp); + + } + + else + { + temporary=number/1000000000; + sprintf(temp, "%lld", temporary); + print(temp); + + } + printf("billion "); + } + + + length=9; + number=number % 1000000000; + temporary=0; + sprintf(num, "%lld", number); + + + if (number >= 1000000) + { + if (length==9) + { + temporary=number/1000000; + + sprintf(temp, "%lld", temporary); + print(temp); + } + + else if (length ==8) + { + temporary=number/1000000; + + sprintf(temp, "%lld", temporary); + print(temp); + } + + else + { + temporary=number/1000000; + + sprintf(temp, "%lld", temporary); + print(temp); + } + printf("million "); + } + + + + length=6; + number=number % 1000000; + temporary=0; + sprintf(num, "%lld", number); + + if (number >= 1000 ) + { + if (length==6) + { + temporary=number/1000; + + + sprintf(temp, "%lld", temporary); + print(temp); + } + + else if (length==5) + { + temporary=number/1000; + + + sprintf(temp, "%lld", temporary); + print(temp); + } + + else{ + temporary=number/1000; + + + sprintf(temp, "%lld", temporary); + print(temp); + } + printf("thousand "); + } + + length=3; + number=number % 1000; + temporary=0; + sprintf(num, "%lld", number); + + + + if (length==3 || length==2 || length ==1) + { + print(num); + } + + + + + else + printf("Enter postive value! "); + + printf("\n"); + + return 0; } \ No newline at end of file diff --git a/BST.cpp b/Trees/BST.cpp similarity index 95% rename from BST.cpp rename to Trees/BST.cpp index 41f9130..b41ca4c 100644 --- a/BST.cpp +++ b/Trees/BST.cpp @@ -1,175 +1,175 @@ -#include -#include -using namespace std; -class Node -{ -public: - int data; - Node *left; - Node *right; - Node(int d) - { - this->data = d; - this->left = NULL; - this->right = NULL; - } -}; -Node *insertIntoBST(Node *&root, int d) -{ - // base case - if (root == NULL) - { - root = new Node(d); - return root; - } - if (d > root->data) - { - // right part mei insert - root->right = insertIntoBST(root->right, d); - } - else - { - root->left = insertIntoBST(root->left, d); - } - return root; -} -void takeInput(Node *&root) -{ - int data; - cin >> data; - while (data != -1) - { - root = insertIntoBST(root, data); - cin >> data; - } -} -void LevelOrderTraversal(Node *root) -{ - queue q; - q.push(root); - q.push(NULL); - while (!q.empty()) - { - Node *temp = q.front(); - q.pop(); - if (temp == NULL) // ek level traverse hogya - { - cout << endl; - if (!q.empty()) - { - q.push(NULL); - } - } - else - { - cout << temp->data << " "; - if (temp->left) - { - q.push(temp->left); - } - if (temp->right) - { - q.push(temp->right); - } - } - } -} -void InOrder(Node *root) -{ - // base case - if (root == NULL) - { - return; - } - InOrder(root->left); - cout << root->data << " "; - InOrder(root->right); -} -void PreOrder(Node *root) -{ - // base case - if (root == NULL) - { - return; - } - cout << root->data << " "; - PreOrder(root->left); - PreOrder(root->right); -} -void PostOrder(Node *root) -{ - // base case - if (root == NULL) - { - return; - } - PostOrder(root->left); - PostOrder(root->right); - cout << root->data << " "; -} -Node -Node *DeleteFromBST(Node *root, int val) -{ - // base case - if (root == NULL) - { - return root; - } - if (root->data == val) - { - // 0 child - if(root->left==NULL && root->right==NULL){ - delete root; - return NULL; - } - - - // 1 child - // left child - if(root->left!=NULL && root->right==NULL){ - Node*temp=root->left; - delete root; - return temp; - } -// right child - if(root->left==NULL && root->right!=NULL){ - Node*temp=root->right; - delete root; - return temp; - } - // 2 child - if(root->left!=NULL && root->right!=NULL){ - int min=minval(root->right)->data; - root->data=min; - root->right=DeleteFromBST(root->right,min); - return root; - } - } - else if (root->data > val) - { - root->left = DeleteFromBST(root->left, val); - return root; - } - else - { - root->right = DeleteFromBST(root->right, val); - } -} -int main() -{ - // 10 8 21 7 27 5 4 3 -1 - Node *root = NULL; - cout << "Enter data to create BST" << endl; - takeInput(root); - cout << "Level order traversal of BST is :" << endl; - LevelOrderTraversal(root); - cout << "Printing inorder :" << endl; - InOrder(root); - cout << endl - << "Printing Preorder :" << endl; - PreOrder(root); - cout << endl - << "Printing Postorder :" << endl; - PostOrder(root); - return 0; +#include +#include +using namespace std; +class Node +{ +public: + int data; + Node *left; + Node *right; + Node(int d) + { + this->data = d; + this->left = NULL; + this->right = NULL; + } +}; +Node *insertIntoBST(Node *&root, int d) +{ + // base case + if (root == NULL) + { + root = new Node(d); + return root; + } + if (d > root->data) + { + // right part mei insert + root->right = insertIntoBST(root->right, d); + } + else + { + root->left = insertIntoBST(root->left, d); + } + return root; +} +void takeInput(Node *&root) +{ + int data; + cin >> data; + while (data != -1) + { + root = insertIntoBST(root, data); + cin >> data; + } +} +void LevelOrderTraversal(Node *root) +{ + queue q; + q.push(root); + q.push(NULL); + while (!q.empty()) + { + Node *temp = q.front(); + q.pop(); + if (temp == NULL) // ek level traverse hogya + { + cout << endl; + if (!q.empty()) + { + q.push(NULL); + } + } + else + { + cout << temp->data << " "; + if (temp->left) + { + q.push(temp->left); + } + if (temp->right) + { + q.push(temp->right); + } + } + } +} +void InOrder(Node *root) +{ + // base case + if (root == NULL) + { + return; + } + InOrder(root->left); + cout << root->data << " "; + InOrder(root->right); +} +void PreOrder(Node *root) +{ + // base case + if (root == NULL) + { + return; + } + cout << root->data << " "; + PreOrder(root->left); + PreOrder(root->right); +} +void PostOrder(Node *root) +{ + // base case + if (root == NULL) + { + return; + } + PostOrder(root->left); + PostOrder(root->right); + cout << root->data << " "; +} +Node +Node *DeleteFromBST(Node *root, int val) +{ + // base case + if (root == NULL) + { + return root; + } + if (root->data == val) + { + // 0 child + if(root->left==NULL && root->right==NULL){ + delete root; + return NULL; + } + + + // 1 child + // left child + if(root->left!=NULL && root->right==NULL){ + Node*temp=root->left; + delete root; + return temp; + } +// right child + if(root->left==NULL && root->right!=NULL){ + Node*temp=root->right; + delete root; + return temp; + } + // 2 child + if(root->left!=NULL && root->right!=NULL){ + int min=minval(root->right)->data; + root->data=min; + root->right=DeleteFromBST(root->right,min); + return root; + } + } + else if (root->data > val) + { + root->left = DeleteFromBST(root->left, val); + return root; + } + else + { + root->right = DeleteFromBST(root->right, val); + } +} +int main() +{ + // 10 8 21 7 27 5 4 3 -1 + Node *root = NULL; + cout << "Enter data to create BST" << endl; + takeInput(root); + cout << "Level order traversal of BST is :" << endl; + LevelOrderTraversal(root); + cout << "Printing inorder :" << endl; + InOrder(root); + cout << endl + << "Printing Preorder :" << endl; + PreOrder(root); + cout << endl + << "Printing Postorder :" << endl; + PostOrder(root); + return 0; } \ No newline at end of file diff --git a/BST.exe b/Trees/BST.exe similarity index 100% rename from BST.exe rename to Trees/BST.exe diff --git a/BinaryTree.cpp b/Trees/BinaryTree.cpp similarity index 95% rename from BinaryTree.cpp rename to Trees/BinaryTree.cpp index 19ef178..75134f6 100644 --- a/BinaryTree.cpp +++ b/Trees/BinaryTree.cpp @@ -1,189 +1,189 @@ -#include -#include -using namespace std; -class Node -{ -public: - int data; - Node *left; - Node *right; - Node(int d) - { - this->data = d; - this->left = NULL; - this->right = NULL; - } -}; -Node *buildTree(Node *root) -{ - cout << "Enter the data for node " << endl; - int data; - cin >> data; - root = new Node(data); - if (data == -1) - { - return NULL; - } - cout << "Enter data for inserting in left of " << data << endl; - root->left = buildTree(root->left); - cout << "Enter data for inserting in right of " << data << endl; - root->right = buildTree(root->right); - return root; -} -void levelOrderTraversal(Node *root) -{ - queue q; - q.push(root); - q.push(NULL); - while (!q.empty()) - { - Node *temp = q.front(); - - q.pop(); - if (temp == NULL) - { // purana level complete traverse ho chuka h - cout << endl; - if (!q.empty()) - { // queue still has some nodes - q.push(NULL); - } - } - else - { - cout << temp->data << " "; - if (temp->left) - { - q.push(temp->left); - } - if (temp->right) - { - q.push(temp->right); - } - } - } -} -/* -void InOrder(Node *root) -{ - // base case - if (root == NULL) - { - return; - } - InOrder(root->left); - cout << root->data << " "; - InOrder(root->right); -} -*/ -void InOrder(Node*root){ - if(root==NULL){ - return; - } - stack s; - Node*curr=root; - while(curr!=NULL || !s.empty()){ - while(curr!=NULL){ - s.push(curr); - curr=curr->left; - } - while (!s.empty()) - { - curr=s.top(); - s.pop(); - cout<data<<" "; - } - curr=curr->right; - - - } - -} -void PreOrder(Node *root) -{ - // base case - if (root == NULL) - { - return; - } - cout << root->data << " "; - PreOrder(root->left); - PreOrder(root->right); -} -void PostOrder(Node *root) -{ - // base case - if (root == NULL) - { - return; - } - PostOrder(root->left); - PostOrder(root->right); - cout << root->data << " "; -} -void buildFromLevelOrder(Node *&root) -{ - queue q; - cout << "Enter data for root " << endl; - int data; - cin >> data; - root = new Node(data); - q.push(root); - while (!q.empty()) - { - Node *temp = q.front(); - q.pop(); - cout << "Enter left node for : " << temp->data << endl; - int LeftData; - cin >> LeftData; - if (LeftData != -1) - { - temp->left = new Node(LeftData); - q.push(temp->left); - } - cout << "Enter Right node for : " << temp->data << endl; - int RightData; - cin >> RightData; - if (RightData != -1) - { - temp->right = new Node(RightData); - q.push(temp->right); - } - } -} -int main() -{ - Node *root = NULL; - // buildFromLevelOrder(root); - // levelOrderTraversal(root); - // 1 3 7 -1 -1 11 -1 -1 5 17 -1 -1 -1 - - // creating a tree - root = buildTree(root); - // 1 3 7 -1 -1 11 -1 -1 5 17 -1 -1 -1 - // level order - cout << "Printing the level order traversal output " << endl; - levelOrderTraversal(root); - - cout << "InOrder traversal is :" << endl; - InOrder(root); - /* - cout << endl; - cout << "PreOrder traversal is :" << endl; - PreOrder(root); - cout << endl; - cout << "PostOrder traversal is :" << endl; - PostOrder(root); - */ - - return 0; -} - - - - - - - - - - +#include +#include +using namespace std; +class Node +{ +public: + int data; + Node *left; + Node *right; + Node(int d) + { + this->data = d; + this->left = NULL; + this->right = NULL; + } +}; +Node *buildTree(Node *root) +{ + cout << "Enter the data for node " << endl; + int data; + cin >> data; + root = new Node(data); + if (data == -1) + { + return NULL; + } + cout << "Enter data for inserting in left of " << data << endl; + root->left = buildTree(root->left); + cout << "Enter data for inserting in right of " << data << endl; + root->right = buildTree(root->right); + return root; +} +void levelOrderTraversal(Node *root) +{ + queue q; + q.push(root); + q.push(NULL); + while (!q.empty()) + { + Node *temp = q.front(); + + q.pop(); + if (temp == NULL) + { // purana level complete traverse ho chuka h + cout << endl; + if (!q.empty()) + { // queue still has some nodes + q.push(NULL); + } + } + else + { + cout << temp->data << " "; + if (temp->left) + { + q.push(temp->left); + } + if (temp->right) + { + q.push(temp->right); + } + } + } +} +/* +void InOrder(Node *root) +{ + // base case + if (root == NULL) + { + return; + } + InOrder(root->left); + cout << root->data << " "; + InOrder(root->right); +} +*/ +void InOrder(Node*root){ + if(root==NULL){ + return; + } + stack s; + Node*curr=root; + while(curr!=NULL || !s.empty()){ + while(curr!=NULL){ + s.push(curr); + curr=curr->left; + } + while (!s.empty()) + { + curr=s.top(); + s.pop(); + cout<data<<" "; + } + curr=curr->right; + + + } + +} +void PreOrder(Node *root) +{ + // base case + if (root == NULL) + { + return; + } + cout << root->data << " "; + PreOrder(root->left); + PreOrder(root->right); +} +void PostOrder(Node *root) +{ + // base case + if (root == NULL) + { + return; + } + PostOrder(root->left); + PostOrder(root->right); + cout << root->data << " "; +} +void buildFromLevelOrder(Node *&root) +{ + queue q; + cout << "Enter data for root " << endl; + int data; + cin >> data; + root = new Node(data); + q.push(root); + while (!q.empty()) + { + Node *temp = q.front(); + q.pop(); + cout << "Enter left node for : " << temp->data << endl; + int LeftData; + cin >> LeftData; + if (LeftData != -1) + { + temp->left = new Node(LeftData); + q.push(temp->left); + } + cout << "Enter Right node for : " << temp->data << endl; + int RightData; + cin >> RightData; + if (RightData != -1) + { + temp->right = new Node(RightData); + q.push(temp->right); + } + } +} +int main() +{ + Node *root = NULL; + // buildFromLevelOrder(root); + // levelOrderTraversal(root); + // 1 3 7 -1 -1 11 -1 -1 5 17 -1 -1 -1 + + // creating a tree + root = buildTree(root); + // 1 3 7 -1 -1 11 -1 -1 5 17 -1 -1 -1 + // level order + cout << "Printing the level order traversal output " << endl; + levelOrderTraversal(root); + + cout << "InOrder traversal is :" << endl; + InOrder(root); + /* + cout << endl; + cout << "PreOrder traversal is :" << endl; + PreOrder(root); + cout << endl; + cout << "PostOrder traversal is :" << endl; + PostOrder(root); + */ + + return 0; +} + + + + + + + + + + diff --git a/BinaryTree.exe b/Trees/BinaryTree.exe similarity index 100% rename from BinaryTree.exe rename to Trees/BinaryTree.exe diff --git a/BinaryTrees.cpp b/Trees/BinaryTrees.cpp similarity index 95% rename from BinaryTrees.cpp rename to Trees/BinaryTrees.cpp index 30d6956..a403f07 100644 --- a/BinaryTrees.cpp +++ b/Trees/BinaryTrees.cpp @@ -1,185 +1,185 @@ -#include -#include -using namespace std; -class Node -{ -public: - int data; - Node *left; - Node *right; - Node(int d) - { - this->data = d; - this->left = NULL; - this->right = NULL; - } -}; -Node *buildTree(Node *root) -{ - cout << "Enter the data for node " << endl; - int data; - cin >> data; - root = new Node(data); - if (data == -1) - { - return NULL; - } - cout << "Enter data for inserting in left of " << data << endl; - root->left = buildTree(root->left); - cout << "Enter data for inserting in right of " << data << endl; - root->right = buildTree(root->right); - return root; -} -void levelOrderTraversal(Node *root) -{ - queue q; - q.push(root); - q.push(NULL); - while (!q.empty()) - { - Node *temp = q.front(); - - q.pop(); - if (temp == NULL) - { // purana level complete traverse ho chuka h - cout << endl; - if (!q.empty()) - { // queue still has some nodes - q.push(NULL); - } - } - else - { - cout << temp->data << " "; - if (temp->left) - { - q.push(temp->left); - } - if (temp->right) - { - q.push(temp->right); - } - } - } -} -void InOrder(Node*root){ - if(root==NULL){ - return; - } - stack s; - Node*curr=root; - while (curr!=NULL || !s.empty()) - { - s.push(curr->data); - curr=curr->left; - - } - curr->data=s.top(); - s.pop(); - cout<data; - curr=curr->right; - -} -/* -void InOrder(Node *root) -{ - // base case - if (root == NULL) - { - return; - } - InOrder(root->left); - cout << root->data << " "; - InOrder(root->right); -} -*/ -void PreOrder(Node *root) -{ - // base case - if (root == NULL) - { - return; - } - cout << root->data << " "; - PreOrder(root->left); - PreOrder(root->right); -} -void PostOrder(Node *root) -{ - // base case - if (root == NULL) - { - return; - } - PostOrder(root->left); - PostOrder(root->right); - cout << root->data << " "; -} -void buildFromLevelOrder(Node *&root) -{ - queue q; - cout << "Enter data for root " << endl; - int data; - cin >> data; - root = new Node(data); - q.push(root); - while (!q.empty()) - { - Node *temp = q.front(); - q.pop(); - cout << "Enter left node for : " << temp->data << endl; - int LeftData; - cin >> LeftData; - if (LeftData != -1) - { - temp->left = new Node(LeftData); - q.push(temp->left); - } - cout << "Enter Right node for : " << temp->data << endl; - int RightData; - cin >> RightData; - if (RightData != -1) - { - temp->right = new Node(RightData); - q.push(temp->right); - } - } -} -int main() -{ - - Node *root = NULL; - levelOrderTraversal(root); - InOrder(root); - // buildFromLevelOrder(root); - // 1 3 7 -1 -1 11 -1 -1 5 17 -1 -1 -1 - - // creating a tree - /* - root = buildTree(root); - // 1 3 7 -1 -1 11 -1 -1 5 17 -1 -1 -1 - // level order - cout << "Printing the level order traversal output " << endl; - levelOrderTraversal(root); - cout << "InOrder traversal is :" << endl; - cout << endl; - cout << "PreOrder traversal is :" << endl; - PreOrder(root); - cout << endl; - cout << "PostOrder traversal is :" << endl; - PostOrder(root); - */ - - - return 0; -} - - - - - - - - - - +#include +#include +using namespace std; +class Node +{ +public: + int data; + Node *left; + Node *right; + Node(int d) + { + this->data = d; + this->left = NULL; + this->right = NULL; + } +}; +Node *buildTree(Node *root) +{ + cout << "Enter the data for node " << endl; + int data; + cin >> data; + root = new Node(data); + if (data == -1) + { + return NULL; + } + cout << "Enter data for inserting in left of " << data << endl; + root->left = buildTree(root->left); + cout << "Enter data for inserting in right of " << data << endl; + root->right = buildTree(root->right); + return root; +} +void levelOrderTraversal(Node *root) +{ + queue q; + q.push(root); + q.push(NULL); + while (!q.empty()) + { + Node *temp = q.front(); + + q.pop(); + if (temp == NULL) + { // purana level complete traverse ho chuka h + cout << endl; + if (!q.empty()) + { // queue still has some nodes + q.push(NULL); + } + } + else + { + cout << temp->data << " "; + if (temp->left) + { + q.push(temp->left); + } + if (temp->right) + { + q.push(temp->right); + } + } + } +} +void InOrder(Node*root){ + if(root==NULL){ + return; + } + stack s; + Node*curr=root; + while (curr!=NULL || !s.empty()) + { + s.push(curr->data); + curr=curr->left; + + } + curr->data=s.top(); + s.pop(); + cout<data; + curr=curr->right; + +} +/* +void InOrder(Node *root) +{ + // base case + if (root == NULL) + { + return; + } + InOrder(root->left); + cout << root->data << " "; + InOrder(root->right); +} +*/ +void PreOrder(Node *root) +{ + // base case + if (root == NULL) + { + return; + } + cout << root->data << " "; + PreOrder(root->left); + PreOrder(root->right); +} +void PostOrder(Node *root) +{ + // base case + if (root == NULL) + { + return; + } + PostOrder(root->left); + PostOrder(root->right); + cout << root->data << " "; +} +void buildFromLevelOrder(Node *&root) +{ + queue q; + cout << "Enter data for root " << endl; + int data; + cin >> data; + root = new Node(data); + q.push(root); + while (!q.empty()) + { + Node *temp = q.front(); + q.pop(); + cout << "Enter left node for : " << temp->data << endl; + int LeftData; + cin >> LeftData; + if (LeftData != -1) + { + temp->left = new Node(LeftData); + q.push(temp->left); + } + cout << "Enter Right node for : " << temp->data << endl; + int RightData; + cin >> RightData; + if (RightData != -1) + { + temp->right = new Node(RightData); + q.push(temp->right); + } + } +} +int main() +{ + + Node *root = NULL; + levelOrderTraversal(root); + InOrder(root); + // buildFromLevelOrder(root); + // 1 3 7 -1 -1 11 -1 -1 5 17 -1 -1 -1 + + // creating a tree + /* + root = buildTree(root); + // 1 3 7 -1 -1 11 -1 -1 5 17 -1 -1 -1 + // level order + cout << "Printing the level order traversal output " << endl; + levelOrderTraversal(root); + cout << "InOrder traversal is :" << endl; + cout << endl; + cout << "PreOrder traversal is :" << endl; + PreOrder(root); + cout << endl; + cout << "PostOrder traversal is :" << endl; + PostOrder(root); + */ + + + return 0; +} + + + + + + + + + + diff --git a/BinaryTrees.exe b/Trees/BinaryTrees.exe similarity index 100% rename from BinaryTrees.exe rename to Trees/BinaryTrees.exe diff --git a/LCAinBST.cpp b/Trees/LCAinBST.cpp similarity index 95% rename from LCAinBST.cpp rename to Trees/LCAinBST.cpp index f82c1d4..60cfaed 100644 --- a/LCAinBST.cpp +++ b/Trees/LCAinBST.cpp @@ -1,42 +1,42 @@ -struct Node -{ - int data; - struct Node*left; - struct Node*right; - Node(int x){ - data=x; - left=right=NULL; - } -}; -class Solution -{ - public: - //Function to return the lowest common ancestor in a Binary Tree. - Node* lca(Node* root ,int n1 ,int n2 ) - { - //Your code here - - if(root==NULL){ - return NULL; - } - if(root->data==n1 || root->data==n2){ - return root; - } - Node*leftAns=lca(root->left,n1,n2); - Node*rightAns=lca(root->right,n1,n2); - if(leftAns==NULL && rightAns==NULL){ - return NULL; - } - else if(leftAns!=NULL && rightAns==NULL){ - return leftAns; - } - else if(leftAns==NULL && rightAns!=NULL){ - return rightAns; - } - else if(leftAns!=NULL && rightAns!=NULL){ - return root; - } - - } - -}; +struct Node +{ + int data; + struct Node*left; + struct Node*right; + Node(int x){ + data=x; + left=right=NULL; + } +}; +class Solution +{ + public: + //Function to return the lowest common ancestor in a Binary Tree. + Node* lca(Node* root ,int n1 ,int n2 ) + { + //Your code here + + if(root==NULL){ + return NULL; + } + if(root->data==n1 || root->data==n2){ + return root; + } + Node*leftAns=lca(root->left,n1,n2); + Node*rightAns=lca(root->right,n1,n2); + if(leftAns==NULL && rightAns==NULL){ + return NULL; + } + else if(leftAns!=NULL && rightAns==NULL){ + return leftAns; + } + else if(leftAns==NULL && rightAns!=NULL){ + return rightAns; + } + else if(leftAns!=NULL && rightAns!=NULL){ + return root; + } + + } + +}; diff --git a/LargestBST.cpp b/Trees/LargestBST.cpp similarity index 95% rename from LargestBST.cpp rename to Trees/LargestBST.cpp index b1dfbfe..33eb6fa 100644 --- a/LargestBST.cpp +++ b/Trees/LargestBST.cpp @@ -1,41 +1,41 @@ -class sol{ - public: - int maxi; - int mini; - bool isBST; - int size; -}; -sol solve(Node*root,int &ans){ -if(root==NULL){ - return {INT_MIN,INT_MAX,true,0}; - -} -sol left=solve(root->left,ans); -sol right=solve(root->right,ans); -sol curr; -curr.size=left.size+right.size+1; -curr.maxi=max(root->data,right.maxi); -curr.mini=min(root->data,left.mini); -if(left.isBST && right.isBST &&(root->data>left.maxi && root->dataleft,ans); +sol right=solve(root->right,ans); +sol curr; +curr.size=left.size+right.size+1; +curr.maxi=max(root->data,right.maxi); +curr.mini=min(root->data,left.mini); +if(left.isBST && right.isBST &&(root->data>left.maxi && root->dataleft,ans); - int right=solve(root->right,ans); - ans=max({ans,root->val+left+right,root->val,root->val+left,root->val+right}); - return max({root->val, root->val + left, root->val + right}); - } - int maxPathSum(TreeNode* root) { - int ans=INT_MIN; - int x=solve(root,ans); - return ans; - } +class Solution { +public: + int solve(TreeNode*root,int &ans){ + if(root==NULL){ + return 0; + } + int left=solve(root->left,ans); + int right=solve(root->right,ans); + ans=max({ans,root->val+left+right,root->val,root->val+left,root->val+right}); + return max({root->val, root->val + left, root->val + right}); + } + int maxPathSum(TreeNode* root) { + int ans=INT_MIN; + int x=solve(root,ans); + return ans; + } }; \ No newline at end of file diff --git a/PreorderToBST.cpp b/Trees/PreorderToBST.cpp similarity index 96% rename from PreorderToBST.cpp rename to Trees/PreorderToBST.cpp index 3482650..ad4b7fd 100644 --- a/PreorderToBST.cpp +++ b/Trees/PreorderToBST.cpp @@ -1,35 +1,35 @@ -#include -using namespace std; - - class Solution -{ -public: - - Node *solve(int pre[], int mini, int maxi, int &index, int n) - { - if (index >= n) - { - return NULL; - } - // check for out of range - if (pre[index] < mini || pre[index] > maxi) - { - return NULL; - } - // we are in range now - // recursive calls - Node *root = newNode(pre[index++]); - root->left = solve(pre, mini, root->data, index, n); - root->right = solve(pre, root->data, maxi, index, n); - return root; - } - // Function that constructs BST from its preorder traversal. - Node *post_order(int pre[], int size) - { - // code here - int mini = INT_MIN; - int maxi = INT_MAX; - int index = 0; - return solve(pre, mini, maxi, index, size); - } +#include +using namespace std; + + class Solution +{ +public: + + Node *solve(int pre[], int mini, int maxi, int &index, int n) + { + if (index >= n) + { + return NULL; + } + // check for out of range + if (pre[index] < mini || pre[index] > maxi) + { + return NULL; + } + // we are in range now + // recursive calls + Node *root = newNode(pre[index++]); + root->left = solve(pre, mini, root->data, index, n); + root->right = solve(pre, root->data, maxi, index, n); + return root; + } + // Function that constructs BST from its preorder traversal. + Node *post_order(int pre[], int size) + { + // code here + int mini = INT_MIN; + int maxi = INT_MAX; + int index = 0; + return solve(pre, mini, maxi, index, size); + } }; \ No newline at end of file diff --git a/TreePractice.cpp b/Trees/TreePractice.cpp similarity index 95% rename from TreePractice.cpp rename to Trees/TreePractice.cpp index 3ef5870..52d7dd0 100644 --- a/TreePractice.cpp +++ b/Trees/TreePractice.cpp @@ -1,73 +1,73 @@ -#include -#include -using namespace std; -class Node -{ -public: - int data; - Node *left; - Node *right; - Node(int d) - { - this->data = d; - this->left = NULL; - this->right = NULL; - } -}; - -Node *BuildTree(Node *root) -{ - cout << "Enter the data for node" << endl; - int data; - cin >> data; - root = new Node(data); - if (data == -1) - { - return NULL; - } - cout << "Enter the data for left node of " << data << endl; - root->left = BuildTree(root->left); - cout << "Enter the data for right node of " << data << endl; - root->right = BuildTree(root->right); - return root; -} -void LevelOrderTraversal(Node *root) -{ - queue q; - q.push(root); - q.push(NULL); - while (!q.empty()) - { - Node *temp = q.front(); - q.pop(); - if (temp == NULL) // ek level traverse hogya - { - cout << endl; - if (!q.empty()) - { - q.push(NULL); - } - } - else - { - cout << temp->data << " "; - if (temp->left) - { - q.push(temp->left); - } - if (temp->right) - { - q.push(temp->right); - } - } - } -} -int main() -{ - Node *root = NULL; - root = BuildTree(root); - // 1 3 7 -1 -1 11 -1 -1 5 17 -1 -1 -1 - cout << "Level Order Traversal of the tree is : " << endl; - LevelOrderTraversal(root); - return 0; +#include +#include +using namespace std; +class Node +{ +public: + int data; + Node *left; + Node *right; + Node(int d) + { + this->data = d; + this->left = NULL; + this->right = NULL; + } +}; + +Node *BuildTree(Node *root) +{ + cout << "Enter the data for node" << endl; + int data; + cin >> data; + root = new Node(data); + if (data == -1) + { + return NULL; + } + cout << "Enter the data for left node of " << data << endl; + root->left = BuildTree(root->left); + cout << "Enter the data for right node of " << data << endl; + root->right = BuildTree(root->right); + return root; +} +void LevelOrderTraversal(Node *root) +{ + queue q; + q.push(root); + q.push(NULL); + while (!q.empty()) + { + Node *temp = q.front(); + q.pop(); + if (temp == NULL) // ek level traverse hogya + { + cout << endl; + if (!q.empty()) + { + q.push(NULL); + } + } + else + { + cout << temp->data << " "; + if (temp->left) + { + q.push(temp->left); + } + if (temp->right) + { + q.push(temp->right); + } + } + } +} +int main() +{ + Node *root = NULL; + root = BuildTree(root); + // 1 3 7 -1 -1 11 -1 -1 5 17 -1 -1 -1 + cout << "Level Order Traversal of the tree is : " << endl; + LevelOrderTraversal(root); + return 0; } \ No newline at end of file diff --git a/TreePractice.exe b/Trees/TreePractice.exe similarity index 100% rename from TreePractice.exe rename to Trees/TreePractice.exe diff --git a/trees.cpp b/Trees/trees.cpp similarity index 95% rename from trees.cpp rename to Trees/trees.cpp index e17b0d9..0452e03 100644 --- a/trees.cpp +++ b/Trees/trees.cpp @@ -1,183 +1,183 @@ -#include -#include -using namespace std; -class Node -{ -public: - int data; - Node *left; - Node *right; - Node(int d) - { - this->data = d; - this->left = NULL; - this->right = NULL; - } -}; -Node *buildTree(Node *root) -{ - cout << "Enter the data for node " << endl; - int data; - cin >> data; - root = new Node(data); - if (data == -1) - { - return NULL; - } - cout << "Enter data for inserting in left of " << data << endl; - root->left = buildTree(root->left); - cout << "Enter data for inserting in right of " << data << endl; - root->right = buildTree(root->right); - return root; -} -void levelOrderTraversal(Node *root) -{ - queue q; - q.push(root); - q.push(NULL); - while (!q.empty()) - { - Node *temp = q.front(); - - q.pop(); - if (temp == NULL) - { // purana level complete traverse ho chuka h - cout << endl; - if (!q.empty()) - { // queue still has some nodes - q.push(NULL); - } - } - else - { - cout << temp->data << " "; - if (temp->left) - { - q.push(temp->left); - } - if (temp->right) - { - q.push(temp->right); - } - } - } -} -void InOrder(Node*root){ - if(root==NULL){ - return; - } - stack s; - Node*curr=root; - while (curr!=NULL || !s.empty()) - { - s.push(curr->data); - curr=curr->left; - - } - curr->data=s.top(); - s.pop(); - cout<data; - curr=curr->right; - -} -/* -void InOrder(Node *root) -{ - // base case - if (root == NULL) - { - return; - } - InOrder(root->left); - cout << root->data << " "; - InOrder(root->right); -} -*/ -void PreOrder(Node *root) -{ - // base case - if (root == NULL) - { - return; - } - cout << root->data << " "; - PreOrder(root->left); - PreOrder(root->right); -} -void PostOrder(Node *root) -{ - // base case - if (root == NULL) - { - return; - } - PostOrder(root->left); - PostOrder(root->right); - cout << root->data << " "; -} -void buildFromLevelOrder(Node *&root) -{ - queue q; - cout << "Enter data for root " << endl; - int data; - cin >> data; - root = new Node(data); - q.push(root); - while (!q.empty()) - { - Node *temp = q.front(); - q.pop(); - cout << "Enter left node for : " << temp->data << endl; - int LeftData; - cin >> LeftData; - if (LeftData != -1) - { - temp->left = new Node(LeftData); - q.push(temp->left); - } - cout << "Enter Right node for : " << temp->data << endl; - int RightData; - cin >> RightData; - if (RightData != -1) - { - temp->right = new Node(RightData); - q.push(temp->right); - } - } -} -int main() -{ - - Node *root = NULL; - InOrder(root); - levelOrderTraversal(root); - buildFromLevelOrder(root); - // 1 3 7 -1 -1 11 -1 -1 5 17 -1 -1 -1 - - // creating a tree - root = buildTree(root); - // 1 3 7 -1 -1 11 -1 -1 5 17 -1 -1 -1 - // level order - cout << "Printing the level order traversal output " << endl; - levelOrderTraversal(root); - cout << "InOrder traversal is :" << endl; - cout << endl; - cout << "PreOrder traversal is :" << endl; - PreOrder(root); - cout << endl; - cout << "PostOrder traversal is :" << endl; - PostOrder(root); - - - return 0; -} - - - - - - - - - - +#include +#include +using namespace std; +class Node +{ +public: + int data; + Node *left; + Node *right; + Node(int d) + { + this->data = d; + this->left = NULL; + this->right = NULL; + } +}; +Node *buildTree(Node *root) +{ + cout << "Enter the data for node " << endl; + int data; + cin >> data; + root = new Node(data); + if (data == -1) + { + return NULL; + } + cout << "Enter data for inserting in left of " << data << endl; + root->left = buildTree(root->left); + cout << "Enter data for inserting in right of " << data << endl; + root->right = buildTree(root->right); + return root; +} +void levelOrderTraversal(Node *root) +{ + queue q; + q.push(root); + q.push(NULL); + while (!q.empty()) + { + Node *temp = q.front(); + + q.pop(); + if (temp == NULL) + { // purana level complete traverse ho chuka h + cout << endl; + if (!q.empty()) + { // queue still has some nodes + q.push(NULL); + } + } + else + { + cout << temp->data << " "; + if (temp->left) + { + q.push(temp->left); + } + if (temp->right) + { + q.push(temp->right); + } + } + } +} +void InOrder(Node*root){ + if(root==NULL){ + return; + } + stack s; + Node*curr=root; + while (curr!=NULL || !s.empty()) + { + s.push(curr->data); + curr=curr->left; + + } + curr->data=s.top(); + s.pop(); + cout<data; + curr=curr->right; + +} +/* +void InOrder(Node *root) +{ + // base case + if (root == NULL) + { + return; + } + InOrder(root->left); + cout << root->data << " "; + InOrder(root->right); +} +*/ +void PreOrder(Node *root) +{ + // base case + if (root == NULL) + { + return; + } + cout << root->data << " "; + PreOrder(root->left); + PreOrder(root->right); +} +void PostOrder(Node *root) +{ + // base case + if (root == NULL) + { + return; + } + PostOrder(root->left); + PostOrder(root->right); + cout << root->data << " "; +} +void buildFromLevelOrder(Node *&root) +{ + queue q; + cout << "Enter data for root " << endl; + int data; + cin >> data; + root = new Node(data); + q.push(root); + while (!q.empty()) + { + Node *temp = q.front(); + q.pop(); + cout << "Enter left node for : " << temp->data << endl; + int LeftData; + cin >> LeftData; + if (LeftData != -1) + { + temp->left = new Node(LeftData); + q.push(temp->left); + } + cout << "Enter Right node for : " << temp->data << endl; + int RightData; + cin >> RightData; + if (RightData != -1) + { + temp->right = new Node(RightData); + q.push(temp->right); + } + } +} +int main() +{ + + Node *root = NULL; + InOrder(root); + levelOrderTraversal(root); + buildFromLevelOrder(root); + // 1 3 7 -1 -1 11 -1 -1 5 17 -1 -1 -1 + + // creating a tree + root = buildTree(root); + // 1 3 7 -1 -1 11 -1 -1 5 17 -1 -1 -1 + // level order + cout << "Printing the level order traversal output " << endl; + levelOrderTraversal(root); + cout << "InOrder traversal is :" << endl; + cout << endl; + cout << "PreOrder traversal is :" << endl; + PreOrder(root); + cout << endl; + cout << "PostOrder traversal is :" << endl; + PostOrder(root); + + + return 0; +} + + + + + + + + + + diff --git a/trees.exe b/Trees/trees.exe similarity index 100% rename from trees.exe rename to Trees/trees.exe diff --git a/tempCodeRunnerFile.cpp b/tempCodeRunnerFile.cpp deleted file mode 100644 index 9d7a71d..0000000 --- a/tempCodeRunnerFile.cpp +++ /dev/null @@ -1,2 +0,0 @@ -deleteNode(tail, 3); - print \ No newline at end of file