题目
分析
用两个栈实现队列,一个用来加,一个用来删
代码
class CQueue {
LinkedList<Integer> stack1;
LinkedList<Integer> stack2;
public CQueue() {
//用来增加
stack1 = new LinkedList<Integer>();
//用来删除
stack2 = new LinkedList<Integer>();
}
public void appendTail(int value) {
stack1.push(value);
}
public int deleteHead() {
//如果第二个栈为空
if (stack2.isEmpty()) {
//如果第一个栈也为空,则返回-1
if (stack1.isEmpty()) return -1;
//如果第一个不是空的,就从1中提取一个,放到2中
while (!stack1.isEmpty()) {
stack2.push(stack1.pop());
}
//从2中提取一个,作为输出
return stack2.pop();
}else {
//如果2不空,从2中提取一个作为输出
return stack2.pop();
}
}
}