用两个栈实现队列java oj
时间: 2025-03-23 16:03:01 浏览: 58
### 使用两个栈实现队列的Java代码示例
通过使用两个栈来模拟队列的行为是一种常见的数据结构设计方法。以下是基于此逻辑的一个具体实现:
#### 实现原理
为了使两个栈能够完成队列的功能,可以定义一个输入栈 `inStack` 和一个输出栈 `outStack`。当执行入队操作时,元素被压入 `inStack`;而当需要出队时,则将所有元素从 `inStack` 转移到 `outStack` 并弹出顶部元素。
```java
import java.util.Stack;
class MyQueue {
private Stack<Integer> inStack;
private Stack<Integer> outStack;
/** Initialize your data structure here. */
public MyQueue() {
inStack = new Stack<>();
outStack = new Stack<>();
}
/** Push element x to the back of queue. */
public void push(int x) {
inStack.push(x);
}
/** Removes the element from in front of queue and returns that element. */
public int pop() {
if (outStack.isEmpty()) {
while (!inStack.isEmpty()) {
outStack.push(inStack.pop());
}
}
return outStack.pop();
}
/** Get the front element. */
public int peek() {
if (outStack.isEmpty()) {
while (!inStack.isEmpty()) {
outStack.push(inStack.pop());
}
}
return outStack.peek();
}
/** Returns whether the queue is empty. */
public boolean empty() {
return inStack.isEmpty() && outStack.isEmpty();
}
}
```
上述代码展示了如何利用两个栈来构建一个基本的队列功能[^1]。其中的关键在于理解何时以及如何在两个栈之间转移数据以保持 FIFO 的顺序。
#### 测试用例
下面是一个简单的测试例子用于验证该类的工作情况:
```java
public class Main {
public static void main(String[] args) {
MyQueue obj = new MyQueue();
obj.push(1);
obj.push(2);
System.out.println(obj.peek()); // 输出 1
System.out.println(obj.pop()); // 输出 1
System.out.println(obj.empty()); // 输出 false
}
}
```
这段程序创建了一个新的队列对象并进行了几个基础的操作演示其行为是否符合预期[^2]。
---
###
阅读全文
相关推荐




















