数据结构 | 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]

相关推荐
小龙报5 分钟前
算法通关指南:数据结构和算法篇 --- 队列相关算法题》--- 1. 【模板】队列,2. 机器翻译
c语言·开发语言·数据结构·c++·算法·学习方法·visual studio
晚秋大魔王10 分钟前
基于python的jlink单片机自动化批量烧录工具
前端·python·单片机
胖哥真不错11 分钟前
Python基于PyTorch实现多输入多输出进行CNN卷积神经网络回归预测项目实战
pytorch·python·毕业设计·课程设计·毕设·多输入多输出·cnn卷积神经网络回归预测
程序员-小李14 分钟前
基于PyTorch的动物识别模型训练与应用实战
人工智能·pytorch·python
晨非辰21 分钟前
【数据结构初阶】--从排序算法原理分析到代码实现操作,参透插入排序的奥秘!
c语言·开发语言·数据结构·c++·算法·面试·排序算法
三川6981 小时前
排序算法介绍
数据结构·算法·排序算法
闲人编程3 小时前
Python在网络安全中的应用:编写一个简单的端口扫描器
网络·python·web安全·硬件·端口·codecapsule·扫描器
Mr_Xuhhh6 小时前
GUI自动化测试--自动化测试的意义和应用场景
python·集成测试
2301_764441336 小时前
水星热演化核幔耦合数值模拟
python·算法·数学建模
循环过三天6 小时前
3.4、Python-集合
开发语言·笔记·python·学习·算法