Skip to content

Instantly share code, notes, and snippets.

@shubhampateliitm
Created September 15, 2018 11:08
Show Gist options
  • Save shubhampateliitm/37bdf7b453ea8d354ca492fd29a99521 to your computer and use it in GitHub Desktop.
Save shubhampateliitm/37bdf7b453ea8d354ca492fd29a99521 to your computer and use it in GitHub Desktop.
struct Node{
int val;
struct Node * next;
struct Node * nextMin;
Node(int v){
val = v;
next = NULL;
nextMin = NULL;
}
};
struct Node* head = NULL;
struct Node* minElement = NULL;
MinStack::MinStack() {
head = NULL;
minElement = NULL;
}
void MinStack::push(int x) {
if(head==NULL){
head = new Node(x);
minElement = head;
}else{
Node* temp = new Node(x);
temp->next = head;
head = temp;
if(head->val < minElement->val){
head->nextMin = minElement;
minElement = head;
}
}
}
void MinStack::pop() {
if(head!=NULL){
if(head==minElement){
minElement = minElement->nextMin;
}
Node* temp = head;
head = head->next;
delete temp;
}
}
int MinStack::top() {
if(head!=NULL){
return head->val;
}else{
return -1;
}
}
int MinStack::getMin() {
if(minElement==NULL){
return -1;
}else{
return minElement->val;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment