Implement Queue using Stacks LeetCode solution in Python

1
# Runtime: 53 ms (Top 33.00%) | Memory: 13.9 MB (Top 98.49%)
2
class MyStack:
3
def __init__(self):
4
self.stack = []
5

6
def push(self, x):
7
self.stack.append(x)
8

9
def top(self):
10
return self.stack[-1]
11

12
def pop(self):
13
return self.stack.pop()
14

15
def size(self):
16
return len(self.stack)
17

18
def isEmpty(self):
19
return len(self.stack) == 0
20

21

22
class MyQueue:
23

24
def __init__(self):
25
self.stack1 = MyStack()
26
self.stack2 = MyStack()
27

28
def push(self, x: int) -> None:
29
self.stack1.push(x)
30

31
def pop(self) -> int:
32
while not self.stack1.isEmpty():
33
self.stack2.push(self.stack1.pop())
34
out = self.stack2.pop()
35
while not self.stack2.isEmpty():
36
self.stack1.push(self.stack2.pop())
37
return out
38

39
def peek(self) -> int:
40
while not self.stack1.isEmpty():
41
self.stack2.push(self.stack1.pop())
42
out = self.stack2.top()
43
while not self.stack2.isEmpty():
44
self.stack1.push(self.stack2.pop())
45
return out
46

47
def empty(self) -> bool:
48
return self.stack1.isEmpty()
49

50

51
# Your MyQueue object will be instantiated and called as such:
52
# obj = MyQueue()
53
# obj.push(x)
54
# param_2 = obj.pop()
55
# param_3 = obj.peek()
56
# param_4 = obj.empty()

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0