Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

added-stack-min-solution #79

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
80 changes: 80 additions & 0 deletions Chapter-3-Stacks-and-Queues/3.2_stack_min_sol.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
/*
* Cracking the coding interview edition 6
* Problem 3-2 : Return the min from a stack.
*/
#include<iostream>
#include<stack>
#include<utility>
#include<climits>

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<pair<int,int>> 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"<<endl;
return ;
}
s1.pop();
}

//returns the current min element in the stack
int min(){
if(isEmpty()){
cout<<"Stack is empty "<<endl;
return INT_MAX; //Maximum value for an object of type int (climits is used)
}
return s1.top().second;
}

//returns true if stack is empty else false
bool isEmpty(){
return s1.empty();
}

//returns the stack top pair
pair<int,int> top(){
if(isEmpty()){
return {INT_MAX,INT_MAX};
}
return s1.top();
}
};

int main(){
minStack myStack;
pair<int,int> 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 "<<arr[i]<<", the current min is "<<myStack.min()<<'\n';
}
for(int i=0; i<10; i++){
stk = myStack.top();
myStack.pop();
cout<<"pop out the element "<<stk.first<<" from the stack and the current min is "<<myStack.top().second<<'\n';
}
return 0;
}