Skip to content

Commit f83e627

Browse files
committed
2019-08-07
1 parent daa5557 commit f83e627

File tree

1 file changed

+16
-12
lines changed

1 file changed

+16
-12
lines changed

0232.用栈实现队列/0232-用栈实现队列.py

+16-12
Original file line numberDiff line numberDiff line change
@@ -4,43 +4,47 @@ def __init__(self):
44
"""
55
Initialize your data structure here.
66
"""
7-
self.s1 = list()
8-
self.s2 = list()
7+
self.stack1 = []
8+
self.stack2 = []
99

10-
1110
def push(self, x):
1211
"""
1312
Push element x to the back of queue.
1413
:type x: int
1514
:rtype: None
1615
"""
17-
self.s1.append(x)
18-
# for i in range(len(s1)):
19-
while(self.s1):
20-
self.s2.append(self.s1.pop())
21-
16+
self.stack1.append(x)
2217

2318
def pop(self):
2419
"""
2520
Removes the element from in front of queue and returns that element.
2621
:rtype: int
2722
"""
28-
return self.s2.pop(0)
29-
23+
if not self.stack2:
24+
while self.stack1:
25+
tmp = self.stack1.pop()
26+
self.stack2.append(tmp)
27+
res = self.stack2.pop()
28+
return res
3029

3130
def peek(self):
3231
"""
3332
Get the front element.
3433
:rtype: int
3534
"""
36-
return self.s2[0]
35+
# print self.stack1, self.stack2
36+
if not self.stack2:
37+
while self.stack1:
38+
tmp = self.stack1.pop()
39+
self.stack2.append(tmp)
40+
return self.stack2[-1]
3741

3842
def empty(self):
3943
"""
4044
Returns whether the queue is empty.
4145
:rtype: bool
4246
"""
43-
return len(self.s2) == 0
47+
return not self.stack1 and not self.stack2
4448

4549

4650
# Your MyQueue object will be instantiated and called as such:

0 commit comments

Comments
 (0)