目录
题目描述
用两个栈实现一个队列。队列的声明如下,请实现它的两个函数 appendTail
和 deleteHead
,分别完成在队列尾部插入整数和在队列头部删除整数的功能。(若队列中没有元素,deleteHead
操作返回 -1 )
示例
示例 1:
输入: ["CQueue","appendTail","deleteHead","deleteHead"] [[],[3],[],[]] 输出:[null,null,3,-1]
代码
class CQueue {
Stack<Integer> st1;
Stack<Integer> st2;
public CQueue() {
st1 = new Stack<>();
st2 = new Stack<>();
}
public void appendTail(int value) {
st2.push(value);
}
public int deleteHead() {
if(!st1.isEmpty()){
return st1.pop();
}
while(!st2.isEmpty()){
st1.push(st2.pop());
}
if(st1.isEmpty()&&st2.isEmpty()){
return -1;
}
return st1.pop();
}
}
/**
* Your CQueue object will be instantiated and called as such:
* CQueue obj = new CQueue();
* obj.appendTail(value);
* int param_2 = obj.deleteHead();
*/