-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path232_Implement_Queue_Using_Stacks.py
More file actions
73 lines (59 loc) · 1.63 KB
/
232_Implement_Queue_Using_Stacks.py
File metadata and controls
73 lines (59 loc) · 1.63 KB
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# Author: cym
class MyQueue:
def __init__(self):
"""
Initialize your data structure here.
"""
self.queue = []
def push_to_top(self, x):
self.queue.append(x)
def pop_from_top(self):
x = self.queue[self.size()-1]
self.queue = self.queue[:self.size()-1]
return x
def size(self):
return len(self.queue)
def is_empty(self):
return len(self.queue) == 0
def push(self, x):
"""
Push element x to the back of queue.
:type x: int
:rtype: void
"""
self.push_to_top(x)
def pop(self):
"""
Removes the element from in front of queue and returns that element.
:rtype: int
"""
tmp = MyQueue()
for i in range(self.size()-1):
x = self.pop_from_top()
tmp.push_to_top(x)
ans = self.pop_from_top()
for i in range(tmp.size()):
x = tmp.pop_from_top()
self.push_to_top(x)
return ans
def peek(self):
"""
Get the front element.
:rtype: int
"""
tmp = MyQueue()
for i in range(self.size()-1):
x = self.pop_from_top()
tmp.push_to_top(x)
ans = self.pop_from_top()
self.push_to_top(ans)
for i in range(tmp.size()):
x = tmp.pop_from_top()
self.push_to_top(x)
return ans
def empty(self):
"""
Returns whether the queue is empty.
:rtype: bool
"""
return self.is_empty()