方法一:使用一个队列实现栈
思路:队列为先进先出的数据结构,栈为先进后出的数据结构,用队列实现栈,即要遵循队列的先进先出规则(即对头的数先出,此处注意:将队列想成一个容器,容器中东西先从头部出来,至于东西的顺序可以自己改变),通过遵循队列的操作来实现栈的思想/功能
1. push()实现:将先进队列的数放入队列的尾部,后进队列的数放入队列头部(通过顺序调换实现)
2. pop()实现:直接弹出队列的头部数据即可实现栈的先进后出功能
3. top()实现:获取队列的头部数据
4. empty()实现:直接判断队列是否为空即可判断队列是否为空
class MyStack:
def __init__(self):
self.que1 = [] #用列表模拟队列
#self.que = collections.deque() #创建双向队列,能快速的在两端进行插入和删除元素,性能比列表优
def push(self, x: int) -> None:
n = len(self.que1)
self.que1.append(x)
for i in range(n):
self.que1.append(self.que1.pop(0)) #使用pop(0)获得最左边的数——用列表模拟队列
def pop(self) -> int:
num = self.que1[0]
self.que1.pop(0)
return num
def top(self) -> int:
return self.que1[0]
def empty(self) -> bool:
return not self.que1 #比判断语句更节省时间
# Your MyStack object will be instantiated and called as such:
# obj = MyStack()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.top()
# param_4 = obj.empty()
方法二:使用两个队列实现栈
思路:主队列用来装最后队列数九反转后的结果,辅助队列用来实现数据的反转,当数据反转后,将辅助队列的数据放入主队列,最后通过对主队列的操作来实现栈的思想
class MyStack(object):
def __init__(self):
self.que1 = collections.deque() #主队列
self.que2 = collections.deque() #辅助队列
def push(self, x):
"""
:type x: int
:rtype: None
"""
self.que2.append(x)
while self.que1:
self.que2.append(self.que1.popleft())
self.que1,self.que2 = self.que2,self.que1
def pop(self):
"""
:rtype: int
"""
return self.que1.popleft()
def top(self):
"""
:rtype: int
"""
return self.que1[0]
def empty(self):
"""
:rtype: bool
"""
return not self.que1
两点注意:
1. 队列的创建有两种,第一:通过列表模拟队列,第二:通过collections模块的deque()创建双向队列
collections模块deque()的使用,参考:(33条消息) Python collections模块之deque()详解_chl183的博客-CSDN博客https://blog.csdn.net/chl183/article/details/106958004
python的deque(双向)队列详解 - 然终酒肆 - 博客园 (cnblogs.com)https://www.cnblogs.com/ranzhong/p/12438841.html
2.判断队列、列表、元组、字典、集合、字符串是否为空时,可直接使用if not 队列/列表/.....或者if 队列/列表/...