文章目录
一、两个栈实现队列
思路: 我们将这两个栈分别命名为A和B,并定义如下规则:
1、入队:(A为进栈默认的操作对象) 将新入队的元素压入栈A
2、出队:(B为出栈默认的操作对象) 如果栈B不为空,将在B栈顶的元素出队
如果栈B为空,且栈A不为空,将栈A中所有的元素压入栈B,然后将在B栈顶的元素出队 如果栈B为空,且栈A也为空,出队函数直接返回-1
class CQueue {
private:
stack<int> in;
stack<int> out;
public:
// 初始化清空栈
CQueue() {
// while(!in.empty())
// {
// in.pop();
// }
// while(!out.empty())
// {
// out.pop();
// }
}
void appendTail(int value) {
in.push(value);
}
int deleteHead() {
if(in.empty()) return -1;
// in不为空,现在要出栈,把in里面的数据倒入out栈里
while(!in.empty())
{
int tmp=in.top();
in.pop();
out.push(tmp);
}
int top=out.top();
out.pop();
// 将剩余元素放回in,方便入队操作
while(!out.empty())
{
int tmp=out.top();
out.pop();
in.push(tmp);
}
return top;
}
};
二、包含min函数的栈
思路:同样也是辅助栈思想
1、当一个元素要入栈时,我们取当前辅助栈的栈顶存储的最小值,与当前元素比较得出最小值,将这个最小值插入辅助栈中;
2、当一个元素要出栈时,我们把辅助栈的栈顶元素也一并弹出; 在任意一个时刻,栈内元素的最小值就存储在辅助栈的栈顶元素中
class MinStack {
private:
stack<int> st;
stack<int> minst;
public:
/** initialize your data structure here. */
MinStack() {
while(!st.empty())
{
st.pop();
}
while(!minst.empty())
{
minst.pop();
}
// 初始化最小栈,为了防止访问top为空报错
minst.push(INT_MAX);
}
void push(int x) {
st.push(x);
int min=std::min(minst.top(),x);
minst.push(min);
}
void pop() {
st.pop();
minst.pop();
}
int top() {
return st.top();
}
int min() {
return minst.top();
}
};