剑指 Offer 09. 用两个栈实现队列
题解
class CQueue {
Stack<Integer> a, b;
public CQueue() {
a = new Stack<Integer>();
b = new Stack<Integer>();
}
public void appendTail(int value) {
a.push(value);//新加的值直接加在a中就可以了
}
public int deleteHead() {
if(b.empty()){//在进行删除的时候先判定b中是否有数据,如果没有就从a中拿数据
while(!a.empty()){
b.push(a.pop());
}
}
//最后再进行判定就可以了
if(!b.empty()){
return b.pop();
}
return -1;
}
}
/**
* Your CQueue object will be instantiated and called as such:
* CQueue obj = new CQueue();
* obj.appendTail(value);
* int param_2 = obj.deleteHead();
*/
如有错误,欢迎指正!