[LeetCode 155]C++实现最小栈
设计一个支持 push ,pop ,top 操作,并能在常数时间内检索到最小元素的栈。
push(x) —— 将元素 x 推入栈中。
pop() —— 删除栈顶的元素。
top() —— 获取栈顶元素。
getMin() —— 检索栈中的最小元素。
来源:力扣(LeetCode 155)
链接:https://leetcode-cn.com/problems/min-stack
class MinStack {
public:
stack<int>min_stack;
stack<int>data_stack;
/** initialize your data structure here. */
MinStack() {
}
void push(int x) {
data_stack.push(x);
if(min_stack.empty()){
min_stack.push(x);
}
else{
if(x>min_stack.top()){
x=min_stack.top();
}
min_stack.push(x);
}
}
void pop() {
data_stack.pop();
min_stack.pop();
}
int top() {
return data_stack.top();
}
int getMin() {
return min_stack.top();
}
};