Skip to content

Commit 120f263

Browse files
committed
feat(leetcode): add No.225
1 parent 93d200d commit 120f263

File tree

1 file changed

+69
-0
lines changed

1 file changed

+69
-0
lines changed
Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
# https://leetcode.com/problems/implement-stack-using-queues/
2+
#
3+
# algorithms
4+
# Medium (39.64%)
5+
# Total Accepted: 132,639
6+
# Total Submissions: 334,578
7+
# beats 94.52% of python submissions
8+
9+
from collections import deque
10+
11+
12+
class MyStack(object):
13+
14+
def __init__(self):
15+
"""
16+
Initialize your data structure here.
17+
"""
18+
self.q_1 = deque()
19+
self.q_2 = deque()
20+
self.use_1 = True
21+
22+
def push(self, x):
23+
"""
24+
Push element x onto stack.
25+
:type x: int
26+
:rtype: void
27+
"""
28+
if self.use_1:
29+
self.q_1.appendleft(x)
30+
else:
31+
self.q_2.appendleft(x)
32+
33+
def pop(self):
34+
"""
35+
Removes the element on top of the stack and returns that element.
36+
:rtype: int
37+
"""
38+
return self._pop_or_top(True)
39+
40+
def top(self):
41+
"""
42+
Get the top element.
43+
:rtype: int
44+
"""
45+
return self._pop_or_top(False)
46+
47+
def _pop_or_top(self, is_pop):
48+
if self.use_1:
49+
from_q, to_q = self.q_1, self.q_2
50+
else:
51+
from_q, to_q = self.q_2, self.q_1
52+
53+
while len(from_q) > 1:
54+
to_q.appendleft(from_q.pop())
55+
56+
res = from_q.pop()
57+
58+
if not is_pop:
59+
to_q.appendleft(res)
60+
self.use_1 = not self.use_1
61+
62+
return res
63+
64+
def empty(self):
65+
"""
66+
Returns whether the stack is empty.
67+
:rtype: bool
68+
"""
69+
return len(self.q_1) + len(self.q_2) == 0

0 commit comments

Comments
 (0)