用两个栈实现一个队列。队列的声明如下,请实现它的两个函数 appendTail 和 deleteHead ,分别完成在队列尾部插入整数和在队列头部删除整数的功能。(若队列中没有元素,deleteHead 操作返回 -1 )
- 一个队列中的数两次经过栈,还是保持先进先出的性质。
- 如果我们让所有的数都顺序经过A和B,那么队列就仍然保持原来的性质。如果要删队列头部的数,那么就是删除栈B的栈顶元素。
- 如果栈B为空并且栈A不为空,说明还有一部分元素没有两次经过栈,并且我们要删除的元素在栈A的底部,将栈A的元素依次加入到栈B中,再删除栈B的栈顶元素即可。
- 两栈均为空,返回-1
class CQueue {
Stack<Integer> A; //A作存数
Stack<Integer> B; //B作辅助
public CQueue() {
A = new Stack<Integer>();
B = new Stack<Integer>();
}
public void appendTail(int value) {
A.add(value);
}
public int deleteHead() {
if(A.isEmpty() && B.isEmpty()) { //两栈均空
return -1;
}else if(B.isEmpty()) { //A不空,B空
while(!A.isEmpty()) {
B.add(A.pop());
}
return B.pop();
}else { //B不空,此时A可能有元素,也可能没有
return B.pop();
}
}
}
/**
* Your CQueue object will be instantiated and called as such:
* CQueue obj = new CQueue();
* obj.appendTail(value);
* int param_2 = obj.deleteHead();
*/
ps:调用stack类基本很少会碰到溢出,但是笔试的时候,入队一定要判满,出队一定要判空。