-
Notifications
You must be signed in to change notification settings - Fork 62
/
queue_use_stack.py
40 lines (33 loc) · 908 Bytes
/
queue_use_stack.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
import sys
# 用栈实现队列
class MyQueue:
def __init__(self):
"""
Initialize your data structure here.
"""
self.input = []
self.output = []
def push(self, x: int) -> None:
"""
Push element x to the back of queue.
"""
self.input.append(x)
def pop(self) -> int:
"""
Removes the element from in front of queue and returns that element.
"""
self.peek()
return self.output.pop()
def peek(self) -> int:
"""
Get the front element.
"""
if len(self.output) == 0:
while len(self.input) > 0:
self.output.append(self.input.pop())
return self.output[-1]
def empty(self) -> bool:
"""
Returns whether the queue is empty.
"""
return len(self.input) == 0 and len(self.output) == 0