剑指
Contents
1. 使用栈实现队列
// front,back两个两个栈实现一个队列的功能
// 所有的入队列操作在front中进行
// 所有的出队列操作在back中进行
// 为了从先入后出逻辑变更为陷入先出,front栈底元素就要变成栈顶元素,故出队列的时候,优先出back的栈顶元素,
// 只有当back栈顶元素出完时才从front那里取数据过来
if(back.empty()){
while(!front.empty()){
back.push(front.top());
front.pop();
}
}
if(back.empty()) return -1;
auto ret = back.top();
back.pop();
return ret;
2. 包含min函数的栈
// 记录栈中的最小元素
// 需要记录当前栈顶的最小元素,当栈顶元素弹出时,最小元素也弹出
class MinStack {
public:
/** initialize your data structure here. */
MinStack() {
}
void push(int x) {
element_.push(x);
if(min_.empty()){
min_.push(x);
}else{
min_.push(std::min(min_.top(), x));
}
}
void pop() {
element_.pop();
min_.pop();
}
int top() {
return element_.top();
}
int min() {
return min_.top();
}
private:
int MIN_INT = INT_MIN;
//std::stack<std::pair<int, int>> stack_;
std::stack<int> element_;
std::stack<int> min_;
};