Skip to content

Commit 2dfdd5e

Browse files
committed
Update implement-stack-using-queues.py
1 parent 7338b2e commit 2dfdd5e

File tree

1 file changed

+37
-9
lines changed

1 file changed

+37
-9
lines changed

Python/implement-stack-using-queues.py

+37-9
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
# Time: push: O(n), pop: O(1), top: O(1)
2-
# Space: O(1)
2+
# Space: O(n)
33
#
44
# Implement the following operations of a stack using queues.
55
#
@@ -41,24 +41,52 @@ def empty(self):
4141
class Stack:
4242
# initialize your data structure here.
4343
def __init__(self):
44-
self.q = Queue()
44+
self.q_ = Queue()
4545

4646
# @param x, an integer
4747
# @return nothing
4848
def push(self, x):
49-
q = self.q
50-
q.push(x)
51-
for _ in xrange(q.size() - 1):
52-
q.push(q.pop())
49+
self.q_.push(x)
50+
for _ in xrange(self.q_.size() - 1):
51+
self.q_.push(self.q_.pop())
5352

5453
# @return nothing
5554
def pop(self):
56-
self.q.pop()
55+
self.q_.pop()
5756

5857
# @return an integer
5958
def top(self):
60-
return self.q.peek()
59+
return self.q_.peek()
6160

6261
# @return an boolean
6362
def empty(self):
64-
return self.q.empty()
63+
return self.q_.empty()
64+
65+
# Time: push: O(1), pop: O(n), top: O(1)
66+
# Space: O(n)
67+
class Stack2:
68+
# initialize your data structure here.
69+
def __init__(self):
70+
self.q_ = Queue()
71+
self.top_ = None
72+
73+
# @param x, an integer
74+
# @return nothing
75+
def push(self, x):
76+
self.q_.push(x)
77+
self.top_ = x
78+
79+
# @return nothing
80+
def pop(self):
81+
for _ in xrange(self.q_.size() - 1):
82+
self.top_ = self.q_.pop()
83+
self.q_.push(self.top_)
84+
self.q_.pop()
85+
86+
# @return an integer
87+
def top(self):
88+
return self.top_
89+
90+
# @return an boolean
91+
def empty(self):
92+
return self.q_.empty()

0 commit comments

Comments
 (0)