目录
学习计划链接
题目解析
1. 剑指 Offer 09 —— 用两个栈实现队列
1) 问题描述
2) 思路分析
通过两个栈,其中一个栈in用于入队操作,另一个out栈用于出队操作。
- 当需要入队时,将out栈中的所有的元素导到in栈中,并将out栈中的所有元素进行出栈操作,再将新元素执行入栈操作;
- 当需要出队时,则相反。若两个栈同时为空,则说明此时队列无元素,直接返回-1;否则,将in栈中的所有的元素导到out栈中,并将in栈中的所有元素进行出栈操作,再将out栈的栈顶元素保存作为返回值,对栈顶元素进行出栈操作,返回。
3) leetcode链接
4) 代码实现
class CQueue {
public:
CQueue() {
}
void appendTail(int value) {
if(in.empty())
{
while(!out.empty())
{
in.push(out.top());
out.pop();
}
}
in.push(value);
}
int deleteHead() {
if(out.empty())
{
if(in.empty()) //如果in和out同时为空,则说明队列无元素
{
return -1;
}
while(!in.empty())
{
out.push(in.top());
in.pop();
}
}
int ret=out.top();
out.pop();
return ret;
}
private:
stack<int> in; //用于入队的栈
stack<int> out; //用于出队的栈
};
/**
* Your CQueue object will be instantiated and called as such:
* CQueue* obj = new CQueue();
* obj->appendTail(value);
* int param_2 = obj->deleteHead();
*/
2. 剑指 Offer 30 —— 包含min函数的栈
1) 问题描述
2) 思路分析
通过两个栈,其中一个s栈完成正常的栈相关操作,另一个m栈用于保存当前栈的min值。
- 入栈操作。
判断当前栈是否为空。- 若为空,将新元素直接插入两个栈中;
- 若非空,则比较新插入的元素和当前栈的最小元素,将两者中较小值的元素插入到m栈中,同时将新元素插入到s栈中;
- 出栈操作
对正常栈s和最小值栈m均执行出栈操作 - 取栈顶元素操作
取正常栈——s栈的栈顶元素 - 取栈中最小元素操作
取最小值栈——m栈的栈顶元素
3) leetcode链接
4) 代码实现
class MinStack {
public:
/** initialize your data structure here. */
MinStack() {
}
void push(int x) {
if(m.empty()||x<m.top())
m.push(x);
else
m.push(m.top());
s.push(x);
}
void pop() {
if(!s.empty())
{
s.pop();
m.pop();
}
}
int top() {
return s.top();
}
int min() {
return m.top();
}
private:
stack<int> m; //保存最小值的栈
stack<int> s; //正常栈
};
/**
* Your MinStack object will be instantiated and called as such:
* MinStack* obj = new MinStack();
* obj->push(x);
* obj->pop();
* int param_3 = obj->top();
* int param_4 = obj->min();
*/