python之队列实现

一、用列表模拟队列

队列支持先进先出的协议。与栈一样,也可以用列表来模拟队列,列表的哪一端是队头,哪一端是队尾,都无关紧要。最简单的策略就是使用列表的append方法来把项添加到队列的队尾,并且使用列表的pop(0)方法从列表的前面删除项并返回它。用这种方法的主要缺点是:所有其他的列表操作也可以操作这个栈,包括任意位置插入、替换和删除元素,这些操作就违反了队列作为一种抽象数据类型的本意。

1.1 队列方法

队列方法 作用
q.isEmpty() 如果为空,返回True,否则返回False
q.size() 返回q中项目的数目
q.iter() 从队头到队尾,访问q中的每一项
q.add(item) 在q的队尾添加item
q.pop() 在q的队头删除一项,并返回该项。先验条件:q必须不为空,如果栈为空,将抛出KeyError
q.peek()

返回q的队头的项,先验条件:q必须不为空,如果栈为空,将抛出KeyError

q.clear() 将q清空

1.2用列表实现队列的代码:

#用列表实现队列
class Queue:
    """A list_based queue implementation."""
    
    # Constructor
    def __init__(self):
        """Sets the initial state of self,and the initial state is []"""
        self.items = []
    
    # Accessor methods
    def iter(self):
         """Supports iteration over a view of self.
         Visits items from bottom to top of queue."""
         for i in range(len(self.items)):
             yield self.items[i]
         
    def isEmpty(self):
        """Returns True if len(self) == 0, or False otherwise."""
        return len(self.items)==0

    def peek(self):
        """
        Returns the item at the top of the queue.
        Precondition: the queue is not empty.
        Raises: KeyError if the queue is empty."""
        if self.isEmpty():
            raise KeyError("The queue is empty.")
        return self.items[0]
     
    def size(self):
        """return the len(self)"""
        return len(self.items)
    
    # Mutator methods
    def clear(self):
        """Makes self become empty."""
        self.items = []
        
    def add(self, item):
        """Adds item to the top of the queue."""
        self.items.append(item)
   
    def pop(self):
        """
        Removes and returns the item at the top of the queue.
        Precondition: the queue is not empty.
        Raises: KeyError if the queue is empty.
        Postcondition: the top item is removed from the queue."""
        if self.isEmpty():
            raise KeyError("The queue is empty.")
        return self.items.pop(0) 

1.3 测试队列

if __name__=='__main__':
    q=Queue()
    q.add(1)
    q.add(2)
    q.add(3)
    print(list(q.iter()))       #return:[1,2,3]
    print(q.size())             #return:3
    print(q.pop())              #return:1
    print(q.peek())             #return:2
    print(q.pop())              #return:2
    print(q.pop())              #return:3
    #若在此处添加一句:q.pop()或q.peek(),将报错:"The queue is empty."
    q.clear()
    print(q.isEmpty())          #return:True
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值