用两个栈实现队列
用两个栈实现一个队列。队列的声明如下,请实现它的两个函数 appendTail 和 deleteHead ,分别完成在队列尾部插入整数和在队列头部删除整数的功能。(若队列中没有元素,deleteHead 操作返回 -1 )
示例 1:
输入:
[“CQueue”,“appendTail”,“deleteHead”,“deleteHead”]
[[],[3],[],[]]
输出:[null,null,3,-1]
class CQueue {
Stack<Integer> a;
Stack<Integer> b;
public CQueue() {
a=new Stack<>();
b=new Stack<>();
}
public void appendTail(int value) {
a.push(value);
}
public int deleteHead() {
if(a.empty()&&b.empty())
return -1;
if(b.empty())
{
while(!a.empty())
{
b.push(a.peek());
a.pop();
}
}
int x=b.peek();
b.pop();
return x;
}
}
/**
* Your CQueue object will be instantiated and called as such:
* CQueue obj = new CQueue();
* obj.appendTail(value);
* int param_2 = obj.deleteHead();
*/
个人总结: 之前做过,现在已经掌握。
包含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 {
Stack<Integer> min;
Stack<Integer> a;
/** initialize your data structure here. */
public MinStack() {
a=new Stack<>();
min=new Stack<>();
min.push(Integer.MAX_VALUE);
}
public void push(int x) {
a.push(x);
if(x<=min.peek())
{
min.push(x);
}
}
public void pop() {
int x=a.pop();
if(x==min.peek())
min.pop();
}
public int top() {
return a.peek();
}
public int min() {
return min.peek();
}
}
/**
* 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();
*/
个人总结: 思路清晰