Created
September 15, 2018 11:08
-
-
Save shubhampateliitm/37bdf7b453ea8d354ca492fd29a99521 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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