剑指 Offer 09. 用两个栈实现队列
用两个栈实现一个队列。队列的声明如下,请实现它的两个函数 appendTail 和 deleteHead ,分别完成在队列尾部插入整数和在队列头部删除整数的功能。(若队列中没有元素,deleteHead 操作返回 -1 )
输入:
["CQueue","appendTail","deleteHead","deleteHead"]
[[],[3],[],[]]
输出:[null,null,3,-1]
输入:
["CQueue","deleteHead","appendTail","appendTail","deleteHead","deleteHead"]
[[],[],[5],[2],[],[]]
输出:[null,-1,null,null,5,2]
提示:
1 <= values <= 10000最多会对 appendTail、deleteHead 进行 10000 次调用
class CQueue {
Stack<Integer> first = new Stack<>();
Stack<Integer> second = new Stack<>();
public CQueue() {
}
public void appendTail(int value) {
first.add(value);
}
public int deleteHead() {
if(second.isEmpty()){
while(!first.isEmpty()){
second.add(first.pop());
}
}
if(second.isEmpty()){
return -1;
}
return second.pop();
}
}
/**
* Your CQueue object will be instantiated and called as such:
* CQueue obj = new CQueue();
* obj.appendTail(value);
* int param_2 = obj.deleteHead();
*/
剑指 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.
提示:
- 各函数的调用总次数不超过 20000 次
class MinStack {
Stack<Integer> first = new Stack<>();
Stack<Integer> second = new Stack<>();
/** initialize your data structure here. */
public MinStack() {
}
public void push(int x) {
first.push(x);
if(second.isEmpty() || second.peek() >= x){
second.push(x);
}
}
public void pop() {
if(second.isEmpty()){
return;
}
if(second.peek().equals(first.peek())){
second.pop();
}
first.pop();
}
public int top() {
return first.peek();
}
public int min() {
if(second.isEmpty()){
return -1;
}
return second.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();
*/