剑指offer 09

class CQueue {
private Stack<Integer> stack1;
private Stack<Integer> stack2;
public CQueue() {
stack1 = new Stack();
stack2 = new Stack();
}
public void appendTail(int value) {
stack1.push(value);
}
public int deleteHead() {
if(stack2.isEmpty()){
while(!stack1.isEmpty()){
stack2.push(stack1.pop());
}
}
if(stack2.isEmpty()){
return -1;
}else{
return stack2.pop();
}
}
}
/**
* Your CQueue object will be instantiated and called as such:
* CQueue obj = new CQueue();
* obj.appendTail(value);
* int param_2 = obj.deleteHead();
*/
本文介绍了一种使用两个栈实现队列的方法。通过定义两个栈stack1和stack2,实现了队列的基本操作:appendTail(入队)和deleteHead(出队)。当stack2为空时,将stack1中的所有元素依次弹出并压入stack2,从而实现队列先进先出的特点。
459

被折叠的 条评论
为什么被折叠?



