[LeetCode]225. Implement Stack using Queues
225. Implement Stack using Queues
import collections
class MyStack(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.queue = collections.deque()
self.queue_temp = collections.deque()
def push(self, x):
"""
Push element x onto stack.
:type x: int
:rtype: void
"""
self.queue.append(x)
def pop(self):
"""
Removes the element on top of the stack and returns that element.
:rtype: int
"""
if not self.queue:
return None
i, l = 0, len(self.queue)
while i < l - 1:
self.queue_temp.append(self.queue.popleft())
i += 1
val = self.queue.popleft()
while self.queue_temp:
self.queue.append(self.queue_temp.popleft())
return val
def top(self):
"""
Get the top element.
:rtype: int
"""
if not self.queue:
return None
val = None
while self.queue:
val = self.queue.popleft()
self.queue_temp.append(val)
while self.queue_temp:
self.queue.append(self.queue_temp.popleft())
return val
def empty(self):
"""
Returns whether the stack is empty.
:rtype: bool
"""
return bool(len(self.queue) == 0)
![](https://i.loli.net/2018/11/17/5beff4d639cbb.jpg)
关注公众号:数据结构与算法那些事儿,每天一篇数据结构与算法