剑指 Offer 09. 用两个栈实现队列
用两个栈实现一个队列。队列的声明如下,请实现它的两个函数 appendTail 和 deleteHead ,分别完成在队列尾部插入整数和在队列头部删除整数的功能。(若队列中没有元素,deleteHead 操作返回 -1 )
示例:
输入:
["CQueue","appendTail","deleteHead","deleteHead"]
[[],[3],[],[]]
输出:[null,null,3,-1]
class CQueue {
public:
stack<int> s1,s2;
CQueue() {
}
void appendTail(int value) {
s1.push(value);
}
int deleteHead() {
if(!s2.empty())
{
int res =s2.top();
s2.pop();
return res;
}
else{
while(!s1.empty())
{
int k =s1.top();
s1.pop();
s2.push(k);
}
if(s2.empty())
{
return -1;
}else{
int res = s2.top();
s2.pop();
return res;
}
}
}
};
/**
* Your CQueue object will be instantiated and called as such:
* CQueue* obj = new CQueue();
* obj->appendTail(value);
* int param_2 = obj->deleteHead();
*/
思路:定义两个栈,队列push时输入到st1,pop时如果st2有元素直接弹出,没有的话将s1中的全部弹到s2,然后判断s2如果为空那么返回-1,如果非空弹出栈顶元素。
剑指 Offer 30. 包含min函数的栈
定义栈的数据结构,请在该类型中实现一个能够得到栈的最小元素的 min 函数在该栈中,调用 min、push 及 pop 的时间复杂度都是 O(1)。
示例:
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.min(); --> 返回 -3.
minStack.pop();
minStack.top(); --> 返回 0.
minStack.min(); --> 返回 -2.
class MinStack {
public:
/** initialize your data structure here. */
stack<int> datastack;
stack<int> minstack;
MinStack() {
}
void push(int x) {
datastack.push(x);
if(minstack.empty())
{
minstack.push(x);
}
else
{
if(x > minstack.top()) minstack.push(minstack.top());
else{
minstack.push(x);
}
}
}
void pop() {
datastack.pop();
minstack.pop();
}
int top() {
return datastack.top();
}
int min() {
return minstack.top();
}
};
/**
* 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();
*/
思路:定义两个栈,一个数据栈实现正常栈的功能,一个最小栈,存与数据栈对应位置的min值。有一种键值对的思想在其中。