python//Jan.21th,2020//双端队列

﹥>﹥吖頭↗ 提交于 2020-01-22 08:19:03
# coding=utf-8
 
# 双端队列(允许两端都可以插入,删除)的实现
class Deque(object):
  def __init__(self):
    self.list = []
 
  # 从队列头部添加元素
  def add_front(self, item):
    # self.list.push(item)  # O(n)
    self.list.insert(0, item)
 
  # 从队列尾部添加元素
  def add_rear(self, item):
    self.list.append(item)
 
  # 出队列
  def pop_front(self):
    # list的头部出队列,O(n)
    return self.list.pop(0)
  
  # 出队列
  def pop_rear(self):
    # list的尾部出队列,O(n)
    return self.list.pop()
 
  # 判断队列是否为空
  def is_empty(self):
    return self.list == []
 
  # 获取队列的大小
  def size(self):
    return len(self.list)
 
 
if __name__ == "__main__":
  q = Deque()
  q.add_front(1)
  q.add_front(2)
  q.add_rear(3)
  q.add_front(4)
  # print(q.pop_front())
  # print(q.pop_front())
  # print(q.pop_front())
  # print(q.pop_front())
 
  print(q.pop_rear())
  print(q.pop_rear())
  print(q.pop_rear())
  print(q.pop_rear())
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!