题目
两个栈实现一个堆
解析
- push 负责压入
- pop 负责弹出
代码
public class TwoStackQueue {
private Stack<Integer> pushStack;
private Stack<Integer> popStack;
private int count;
public TwoStackQueue() {
this.popStack = new Stack<>();
this.pushStack = new Stack<>();
}
//入队
public void add(Integer newNew) {
pushStack.push(newNew);
count++;
}
//出队
public int pop() {
if (popStack.empty() && pushStack.empty()) {
throw new RuntimeException("Queue is empty");
} else if (popStack.empty()) {
while (!pushStack.empty()) {
popStack.push(pushStack.pop());
}
}
return popStack.pop();
}
public static void main(String[] args) {
TwoStackQueue queue = new TwoStackQueue();
queue.add(3);
queue.add(1);
queue.add(7);
for (int i = 0; i < queue.count; i++) {
System.out.println(queue.pop());
}
}
}