-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path232_ImplementQueueUsingStacks.py
More file actions
45 lines (40 loc) · 1.12 KB
/
232_ImplementQueueUsingStacks.py
File metadata and controls
45 lines (40 loc) · 1.12 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
class Queue:
# initialize your data structure here.
def __init__(self):
self.stack = []
def size(self):
return len(self.stack)
# @param x, an integer
# @return nothing
def push(self, x):
# push on stack
self.stack.append(x)
# @return nothing
def pop(self):
# pop all elements to another stack
if self.size() == 0:
return None
tmp = []
length = self.size()
for i in range(length - 1):
tmp.append(self.stack.pop(-1))
ans = self.stack.pop(-1)
for i in range(length - 1):
self.stack.append(tmp.pop(-1))
return ans
# @return an integer
def peek(self):
if self.size() == 0:
return None
tmp = []
length = self.size()
for i in range(length - 1):
tmp.append(self.stack.pop(-1))
ans = self.stack.pop(-1)
self.stack.append(ans)
for i in range(length - 1):
self.stack.append(tmp.pop(-1))
return ans
# @return an boolean
def empty(self):
return self.size() == 0