Implement Queue using Stacks

LeetCode

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

Implement a first in first out (FIFO) queue using only two stacks.

1class MyQueue:
2 def __init__(self):
3 self.s1 = []
4 self.s2 = []
5
6 def push(self, x: int) -> None:
7 self.s1.append(x)
8
9 def pop(self) -> int:
10 self._move()
11 return self.s2.pop()
12
13 def peek(self) -> int:
14 self._move()
15 return self.s2[-1]
16
17 def empty(self) -> bool:
18 return not self.s1 and not self.s2
19
20 def _move(self) -> None:
21 if not self.s2:
22 while self.s1:
23 self.s2.append(self.s1.pop())
1
0
top
2
1
s1=[1, 2]
s2=[]
op=push(1); push(2)
Step 1 / 5
Step 1:
Push 1 then 2 into s1. Queue front is still at the bottom of s1.
Pointers: top=1
Focus: select @ [0, 1]
op="push(1); push(2)"