import java.util.Stack;
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() {
// 当stack2不为空的时候 继续出stack2中的元素
if (!stack2.isEmpty()){
return stack2.pop();
}
// 当stack2中为空时候 将stack1中的元素全部出栈 并入栈stack2
while (!stack1.isEmpty()) {
int temp = stack1.pop();
stack2.push(temp);
}
// 如果stack2还是空的话 说明stack1 stack2均为空 此时返回-1
if (stack2.isEmpty())
return -1;
// 将stack2 中元素出栈
return stack2.pop();
}
public static void main(String[] args) {
// 1 4 3 5 8
CQueue cQueue = new CQueue();
cQueue.appendTail(1);
cQueue.appendTail(4);
cQueue.appendTail(3);
System.out.println(cQueue.deleteHead());
System.out.println(cQueue.deleteHead());
cQueue.appendTail(5);
System.out.println(cQueue.deleteHead());
cQueue.appendTail(8);
System.out.println(cQueue.deleteHead());
System.out.println(cQueue.deleteHead());
}
}
剑指 Offer 09. 用两个栈实现队列
最新推荐文章于 2025-05-23 17:03:50 发布