-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathimplement-queue-using-stacks.py
49 lines (43 loc) · 1.16 KB
/
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
# https://leetcode.com/problems/implement-queue-using-stacks/
class MyQueue(object):
def __init__(self):
'''
initialize your data structure here
'''
self.queue = []
self.stack = []
def push(self, x):
'''
push element x to back of queue
:type x: int
:rtype: None
'''
self.queue.append(x)
def pop(self):
'''
removes the element from in front of queue and returns that element
:rtype: int
'''
while self.queue:
self.stack.append(self.queue.pop())
pop = self.stack.pop()
while self.stack:
self.queue.append(self.stack.pop())
return pop
def peek(self):
'''
get the front element
:rtype: int
'''
while self.queue:
self.stack.append(self.queue.pop())
frontelem = self.stack[-1]
while self.stack:
self.queue.append(self.stack.pop())
return frontelem
def empty(self):
'''
returns whether the queue is empty
:rtype: bool
'''
return (not self.queue) and (not self.stack)