剑指 Offer 09. 用两个栈实现队列
用两个栈实现一个队列。队列的声明如下,请实现它的两个函数 appendTail 和 deleteHead ,分别完成在队列尾部插入整数和在队列头部删除整数的功能。(若队列中没有元素,deleteHead 操作返回 -1 )
一个栈用插入
一个栈用删除
删除比较特殊:当删除栈空时,需要插入栈中的所有元素都要先弹入删除栈中,
弹出后,再进行删除操作,如果此时删除栈不为为空,则将栈中元素再进行弹出
class CQueue {
Stack<Integer> stakcA;//用来插入
Stack<Integer> stakcB;//用来删除
public CQueue(){
stakcA=new Stack<>();
stakcB=new Stack<>();
}
public void appendTail(Integer value){
stakcA.push(value);
}
public int deleteHead(){
if(stakcB.isEmpty()){
while(!stakcA.isEmpty()){
stakcB.push(stakcA.pop());
}
}
if(stakcB.isEmpty()){
return -1;
}else{
int deletenum=stakcB.pop();
return deletenum;
}
}
}
/**
* Your CQueue object will be instantiated and called as such:
* CQueue obj = new CQueue();
* obj.appendTail(value);
* int param_2 = obj.deleteHead();
*/