Skip to content

Commit 7338b2e

Browse files
committed
Create implement-stack-using-queues.py
1 parent 34cff13 commit 7338b2e

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
# Time: push: O(n), pop: O(1), top: O(1)
2+
# Space: O(1)
3+
#
4+
# Implement the following operations of a stack using queues.
5+
#
6+
# push(x) -- Push element x onto stack.
7+
# pop() -- Removes the element on top of the stack.
8+
# top() -- Get the top element.
9+
# empty() -- Return whether the stack is empty.
10+
# Notes:
11+
# You must use only standard operations of a queue -- which
12+
# means only push to back, peek/pop from front, size, and is
13+
# empty operations are valid.
14+
# Depending on your language, queue may not be supported natively.
15+
# You may simulate a queue by using a list or deque (double-ended
16+
# queue), as long as you use only standard operations of a queue.
17+
# You may assume that all operations are valid (for example, no pop
18+
# or top operations will be called on an empty stack).
19+
#
20+
21+
class Queue:
22+
def __init__(self):
23+
self.data = collections.deque()
24+
25+
def push(self, x):
26+
self.data.append(x)
27+
28+
def peek(self):
29+
return self.data[0]
30+
31+
def pop(self):
32+
return self.data.popleft()
33+
34+
def size(self):
35+
return len(self.data)
36+
37+
def empty(self):
38+
return len(self.data) == 0
39+
40+
41+
class Stack:
42+
# initialize your data structure here.
43+
def __init__(self):
44+
self.q = Queue()
45+
46+
# @param x, an integer
47+
# @return nothing
48+
def push(self, x):
49+
q = self.q
50+
q.push(x)
51+
for _ in xrange(q.size() - 1):
52+
q.push(q.pop())
53+
54+
# @return nothing
55+
def pop(self):
56+
self.q.pop()
57+
58+
# @return an integer
59+
def top(self):
60+
return self.q.peek()
61+
62+
# @return an boolean
63+
def empty(self):
64+
return self.q.empty()

0 commit comments

Comments
 (0)