数据结构 | Python实现列表队列 | 源码和示例

python 复制代码
# List node class
class Queue:
    def __init__(self):
        # Initialize an empty list to store queue elements
        self.items = []

    def is_empty(self):
        # Check if the queue is empty
        return len(self.items) == 0

    def enqueue(self, item):
        # Enqueue (add) an item to the end of the queue
        self.items.append(item)

    def dequeue(self):
        if not self.is_empty():
            # Dequeue (remove and return) the item from the front of the queue
            return self.items.pop(0)
        else:
            # If the queue is empty, return a message indicating so
            return "Queue is empty"

    def peek(self):
        if not self.is_empty():
            # Peek at (view) the item at the front of the queue without removing it
            return self.items[0]
        else:
            # If the queue is empty, return a message indicating so
            return "Queue is empty"

    def size(self):
        # Get the number of elements in the queue
        return len(self.items)

    def output_queue(self):
        # Output the elements of the queue
        print("Queue elements:", self.items)

def main():
    # Create a new queue
    my_queue = Queue()

    # Check if the queue is empty
    print("Is the queue empty?", my_queue.is_empty())

    # Enqueue elements to the queue
    my_queue.enqueue(1)
    my_queue.enqueue(2)
    my_queue.enqueue(3)

    # Output the elements of the queue
    my_queue.output_queue()

    # Check the size of the queue
    print("Queue size:", my_queue.size())

    # Peek at the front element of the queue
    print("Front element:", my_queue.peek())

    # Dequeue elements from the queue
    dequeued_item = my_queue.dequeue()
    print("Dequeued item:", dequeued_item)

    # Check the size of the queue after dequeue
    print("Queue size after dequeue:", my_queue.size())

    # Check if the queue is empty again
    print("Is the queue empty now?", my_queue.is_empty())

    # Output the elements of the queue
    my_queue.output_queue()

if __name__ == "__main__":
    main()

结果:

Is the queue empty? True

Queue elements: [1, 2, 3]

Queue size: 3

Front element: 1

Dequeued item: 1

Queue size after dequeue: 2

Is the queue empty now? False

Queue elements: [2, 3]

相关推荐
--fancy3 小时前
股票预测情感分析研究案例分析
python
shughui3 小时前
PyCharm 完整教程(旧版本卸载+旧/新版本下载安装+基础使用,2026最新版附安装包)
ide·python·pycharm
小糖学代码4 小时前
LLM系列:1.python入门:15.JSON 数据处理与操作
开发语言·python·json·aigc
yejqvow124 小时前
CSS如何控制placeholder文字的颜色_使用--placeholder伪元素
jvm·数据库·python
m0_743623924 小时前
HTML怎么创建多语言切换器_HTML语言选择下拉结构【指南】
jvm·数据库·python
pele4 小时前
Angular 表单中基于下拉选择动态启用字段必填校验的完整实现
jvm·数据库·python
HHHHH1010HHHHH4 小时前
Redis怎样判断节点是否主观下线_哨兵基于down-after-milliseconds参数的心跳超时判定
jvm·数据库·python
小白学大数据4 小时前
现代Python爬虫开发范式:基于Asyncio的高可用架构实战
开发语言·爬虫·python·架构
不爱吃炸鸡柳4 小时前
数据结构精讲:树 → 二叉树 → 堆 从入门到实战
开发语言·数据结构
qq_654366985 小时前
CSS如何处理@import样式表的嵌套加载_评估递归对加载的影响
jvm·数据库·python