剑指offer 09:
题目描述:
用两个栈实现一个队列。队列的声明如下,请实现它的两个函数 appendTail 和deleteHead ,分别完成在队列尾部插入整数和在队列头部删除整数的功能。(若队列中没有元素,deleteHead 操作返回 -1 )
代码实现:
class CQueue {
public CQueue() {
}
Stack sta1 = new Stack();
Stack sta2 = new Stack();
public void appendTail(int value) {
sta1.push(value);
}
public int deleteHead() {
if (sta2.isEmpty()){
while (!sta1.isEmpty())
sta2.push(sta1.pop());
}
if (sta2.isEmpty())
return -1;
return (int) sta2.pop();
}
}