当前位置:   article > 正文

用Python实现队列---1顺序表_python如何创建顺序队列

python如何创建顺序队列

代码

class Queue:
    def __init__(self):
        # 以列表的最后一个元素作为队尾
        self.items = []

    def is_empty(self):
        return self.items == []

    def length(self):
        return len(self.items)

    def push(self, item):
        # 添加一个元素item的队尾
        # 最后一个元素作为队尾
        self.items.append(item)

    def pop(self):
        # 抛出队首元素
        if self.is_empty():
            raise ValueError("队列为空")
        return self.items.pop(0)

    def peek(self):
        if self.is_empty():
            raise ValueError("队列为空")
        return self.items[0]


if __name__ == "__main__":
    queue = Queue()
    queue.push(1)  # 进入队列
    queue.push(2)
    queue.push(3)
    queue.push(4)
    print(queue.length())  # 队列长度
    print(queue.peek())  # 队头元素
    print(queue.pop())  # 出队
    print(queue.pop())
    print(queue.pop())
    print(queue.pop())
    #print(queue.pop())
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
'
运行

结果

在这里插入图片描述

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号