剑指 Offer 09. 用两个栈实现队列
用两个栈实现一个队列。队列的声明如下,请实现它的两个函数 appendTail 和 deleteHead ,分别完成在队列尾部插入整数和在队列头部删除整数的功能。(若队列中没有元素,deleteHead 操作返回 -1 )
class CQueue {
public CQueue() {
}
public void appendTail(int value) {
}
public int deleteHead() {
if()
}
}
/**
* Your CQueue object will be instantiated and called as such:
* CQueue obj = new CQueue();
* obj.appendTail(value);
* int param_2 = obj.deleteHead();
*/
思路
记得之前写过使用两个栈实现队列的文章,翻了翻,没找到
其实,也很简单
建立两个栈:栈A和栈B
入栈的时候,只在栈A进行入栈
出栈的时候,判断栈B是否为空:
如果栈B不为空,则将栈B栈顶元素出栈
如果栈B为空,则将栈A的元素依次出栈,放入栈B中,栈A全部都放入栈B后,将栈B栈顶元素出栈
class CQueue {
private Stack stackA = null;
private Stack stackB = null;
public CQueue() {
stackA = new Stack();
stackB = new Stack();
}
public void appendTail(int value) {
stackA.push(value);
}
public int deleteHead() {
if(stackB.empty())
{
if(stackA.empty()){
return -1;
}else{
while(!stackA.empty())
{
stackB.push(stackA.pop());
}
return (int)stackB.pop();
}
}else{
return (int)stackB.pop();
}
}
}
/**
* Your CQueue object will be instantiated and called as such:
* CQueue obj = new CQueue();
* obj.appendTail(value);
* int param_2 = obj.deleteHead();
*/
难点,对于栈的操作不熟
翻到了之前的笔记: