-
Notifications
You must be signed in to change notification settings - Fork 0
/
232-implement-queue-using-stacks.py
55 lines (43 loc) · 1.36 KB
/
232-implement-queue-using-stacks.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# class MyQueue:
# def __init__(self):
# self.queue = []
# def push(self, x: int) -> None:
# self.queue.append(x)
# def pop(self) -> int:
# if not self.empty():
# front = self.queue[0]
# self.queue = self.queue[1:]
# return front
# def peek(self) -> int:
# if not self.empty():
# return self.queue[0]
# else:
# return None
# def empty(self) -> bool:
# return True if not self.queue else False
# [Two Stacks]:
# Push - O(1) per operation
# Pop - Amortized O(1) per operation
# Worst-case O(n)
class MyQueue:
def __init__(self):
self.input_stack = []
self.output_stack = []
def push(self, x: int) -> None:
self.input_stack.append(x)
def pop(self) -> int:
self.peek()
return self.output_stack.pop()
def peek(self) -> int:
if not self.output_stack:
while self.input_stack:
self.output_stack.append(self.input_stack.pop())
return self.output_stack[-1]
def empty(self) -> bool:
return not self.input_stack and not self.output_stack
# Your MyQueue object will be instantiated and called as such:
# obj = MyQueue()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.peek()
# param_4 = obj.empty()