# Problem 232: Implement Queue using Stacks

> <https://leetcode.com/problems/implement-queue-using-stacks/>

## 思路

![](/files/-Lpv9wCbHvTfFbtV4jYQ)

```java
class MyQueue {
    private Stack<Integer> stack1 = new Stack<Integer>();;
    private Stack<Integer> stack2 = new Stack<Integer>();;

    private void stack2ToStack1() {
        while (!stack2.isEmpty()) {
            stack1.push(stack2.pop());
        }
    }

    // Push element x to the back of queue.
    public void push(int x) {
        stack2.push(x);
    }

    // Removes the element from in front of queue.
    public void pop() {
        if (stack1.isEmpty()) {
            stack2ToStack1();
        } 
        stack1.pop();
    }

    // Get the front element.
    public int peek() {
        if (stack1.isEmpty()) {
            stack2ToStack1();
        } 
        return stack1.peek();
    }

    // Return whether the queue is empty.
    public boolean empty() {
        return stack1.isEmpty() && stack2.isEmpty(); 
    }
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://liuyang89116.gitbook.io/my-leetcode-book/chapter_7_data_structure/stack--queue/problem_232_implement_queue_using_stacks.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
