> For the complete documentation index, see [llms.txt](https://longxingtan.gitbook.io/mle-interview/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://longxingtan.gitbook.io/mle-interview/01_leetcode/05_stack_queue/232.-implement-queue-using-stacks.md).

# 232. Implement Queue using Stacks

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

## solution

```python
class MyQueue:
    def __init__(self):
        self.stack1 = []
        self.stack2 = []

    def push(self, x: int) -> None:
        self.stack1.append(x)

    def pop(self) -> int:
        if self.stack2:
            return self.stack2.pop()
        elif self.stack1:
            while self.stack1:
                self.stack2.append(self.stack1.pop(-1))
            return self.stack2.pop(-1)
        else:
            return

    def peek(self) -> int:
        if self.stack2:
            return self.stack2[-1]
        elif self.stack1:
            return self.stack1[0]
        else:
            return

    def empty(self) -> bool:
        if len(self.stack1) + len(self.stack2) > 0:
            return False
        else:
            return True
```

时间复杂度：O()\
空间复杂度：O()
