两个栈实现一个队列
// 队列:先进先出,后进后出
// 栈:先进后出,后进先出
class CQueue {
// 声明两个栈
public Stack<Integer> stack1;
public Stack<Integer> stack2;
public CQueue() {
stack1 = new Stack<Integer>();
stack2 = new Stack<Integer>();
}
public void appendTail(int value) {
// 同进,栈1模拟队列进元素
stack1.push(value);
}
public int deleteHead() {
// 用两个栈联合完成队列的出,‘负负为正’,出两次即可
System.out.println("stack1:"+stack1);
if (stack2.isEmpty()) {
while (!stack1.isEmpty()) {
stack2.push(stack1.pop());
}
}
System.out.println("stack2:"+stack2);
if (stack2.isEmpty()){
return -1;
}
int index = stack2.pop();
return index;
}
}
845

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



