用两个栈实现一个队列。队列的声明如下,请实现它的两个函数 appendTail 和 deleteHead ,分别完成在队列尾部插入整数和在队列头部删除整数的功能。(若队列中没有元素,deleteHead 操作返回 -1 )
示例 1:
输入:
["CQueue","appendTail","deleteHead","deleteHead"]
[[],[3],[],[]]
输出:[null,null,3,-1]
示例 2:
输入:
["CQueue","deleteHead","appendTail","appendTail","deleteHead","deleteHead"]
[[],[],[5],[2],[],[]]
输出:[null,-1,null,null,5,2]
提示:
1 <= values <= 10000
最多会对 appendTail、deleteHead 进行 10000 次调用
1、原始想法
class CQueue {
Stack<Integer> stack;
Stack<Integer> helper;
public CQueue() {
stack=new Stack<Integer>();
helper=new Stack<Integer>();
}
public void appendTail(int value) {
stack.push(value);
}
public int deleteHead() {
if(stack.isEmpty()){
return -1;
}
while(!stack.isEmpty()){
helper.push(stack.pop());
}
int res=helper.pop();
while(!helper.isEmpty()){
stack.push(helper.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();
*/
2、优化
stack的底层是数组,有扩容和移位的问题。可以使用LinkedList来实现。
class CQueue {
LinkedList<Integer> stack;
LinkedList<Integer> helper;
public CQueue() {
stack=new LinkedList<Integer>();
helper=new LinkedList<Integer>();
}
public void appendTail(int value) {
stack.addLast(value);
}
public int deleteHead() {
if(!helper.isEmpty()){
return helper.removeLast();
}
if(stack.isEmpty()){
return -1;
}else{
while(!stack.isEmpty()){
helper.addLast(stack.removeLast());
}
return helper.removeLast();
}
}
}
/**
* Your CQueue object will be instantiated and called as such:
* CQueue obj = new CQueue();
* obj.appendTail(value);
* int param_2 = obj.deleteHead();
*/