From bd35fbfd5e44bc5ec2a55fa28f51f50f64b971be Mon Sep 17 00:00:00 2001 From: saiteja623 Date: Fri, 9 Jul 2021 22:00:15 +0530 Subject: [PATCH] added-stack-min-solution --- .../3.2_stack_min_sol.cpp | 80 +++++++++++++++++++ 1 file changed, 80 insertions(+) create mode 100644 Chapter-3-Stacks-and-Queues/3.2_stack_min_sol.cpp diff --git a/Chapter-3-Stacks-and-Queues/3.2_stack_min_sol.cpp b/Chapter-3-Stacks-and-Queues/3.2_stack_min_sol.cpp new file mode 100644 index 0000000..e4da405 --- /dev/null +++ b/Chapter-3-Stacks-and-Queues/3.2_stack_min_sol.cpp @@ -0,0 +1,80 @@ +/* + * Cracking the coding interview edition 6 + * Problem 3-2 : Return the min from a stack. + */ +#include +#include +#include +#include + +using namespace std; + +//stack stores the pairs +//pair.first stores the value +//pair.second stores the current min element found in the stack +class minStack{ +private: + stack> s1; + +public: + //adds a pair to the top of the stack + void push(int x){ + int currMin=x; + if(!isEmpty()) + { + //check if current element can be minimum of all elements + if(currMin > top().second) + { + currMin=top().second; + } + } + s1.push({x,currMin}); + } + + //pops the stack top pair + void pop(){ + if(isEmpty()){ + cout<<"Cannot be popped"< top(){ + if(isEmpty()){ + return {INT_MAX,INT_MAX}; + } + return s1.top(); + } +}; + +int main(){ + minStack myStack; + pair stk; + int arr[] = {6, 3, 5, 2, 2, 9, 2, 8, 1, 1}; + for(int i=0; i<10; i++){ + myStack.push(arr[i]); + cout<<"push in the element "<