155. Min Stack
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
- push(x) – Push element x onto stack.
- pop() – Removes the element on top of the stack.
- top() – Get the top element.
- getMin() – Retrieve the minimum element in the stack.
Example:
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); --> Returns -3.
minStack.pop();
minStack.top(); --> Returns 0.
minStack.getMin(); --> Returns -2.
Approach
题目简单易懂,最快的解法就是用单调栈,维持栈顶为最小值。
Code
struct List {
int value;
List *next;
List(int a) {
value = a;
next = nullptr;
}
};
class MinStack {
public:
List *head;
List *minHead;
/** initialize your data structure here. */
MinStack() {
head = new List(INT32_MIN);
minHead = new List(INT32_MIN);
}
void push(int x) {
List *elem = new List(x);
List *tmp = head->next;
head->next = elem;
elem->next = tmp;
List *minTmp = minHead->next;
if (!minTmp) {
minTmp = new List(x);
minHead->next = minTmp;
} else if (minTmp->value >= x) {
List *e = new List(x);
minHead->next = e;
e->next = minTmp;
}
}
void pop() {
if (!head->next)
return;
List *del = head->next;
head->next = del->next;
List *minDel = minHead->next;
if (del->value == minDel->value) {
minHead->next = minDel->next;
delete minDel;
}
delete del;
}
int top() {
if (!head->next)return INT32_MIN;
return head->next->value;
}
int getMin() {
if (!minHead->next)return INT32_MIN;
return minHead->next->value;
}
};