牛客网&剑指Offer&包含min函数的栈
代码实现
class Solution {
stack<int> stack1;
stack<int> min_stack;
bool top_flag = true;
public:
void push(int value) {
stack1.push(value);
if(min_stack.empty() == true || value < min_stack.top())
min_stack.push(value);
else
min_stack.push(min_stack.top());
}
void pop() {
if(stack1.empty() != true)
stack1.pop();
if(min_stack.empty() != true)
min_stack.pop();
}
int top() {
if(stack1.empty() != true)
return stack1.top();
else
{
top_flag = false;
return 0;
}
if(min_stack.empty() != true)
min_stack.top();
else
{
top_flag = false;
return 0;
}
}
int min() {
return min_stack.top();
}
};
编程笔记
- 代码实现解题思路:考虑使用辅助栈,由于多次的出栈入栈会使栈的最小值发生变化。
- 熟悉栈的数据结构。