01 · Question
Implement a first in first out (FIFO) queue using only two stacks.
02 · Solution
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.s219 20 def _move(self) -> None:21 if not self.s2:22 while self.s1:23 self.s2.append(self.s1.pop())