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

相关推荐
爱笑的眼睛115 分钟前
超越MSE与交叉熵:深度解析损失函数的动态本质与高阶设计
java·人工智能·python·ai
yBmZlQzJ1 小时前
免费内网穿透-端口转发配置介绍
运维·经验分享·docker·容器·1024程序员节
Rose sait1 小时前
【环境配置】Linux配置虚拟环境pytorch
linux·人工智能·python
Nandeska1 小时前
2、数据库的索引与底层数据结构
数据结构·数据库
过期动态1 小时前
JDBC高级篇:优化、封装与事务全流程指南
android·java·开发语言·数据库·python·mysql
一世琉璃白_Y2 小时前
pg配置国内数据源安装
linux·python·postgresql·centos
liwulin05062 小时前
【PYTHON】COCO数据集中的物品ID
开发语言·python
小鸡吃米…2 小时前
Python - XML 处理
xml·开发语言·python·开源
我赵帅的飞起2 小时前
python国密SM4加解密
python·sm4加解密·国密sm4加解密
yaoh.wang2 小时前
力扣(LeetCode) 1: 两数之和 - 解法思路
python·程序人生·算法·leetcode·面试·跳槽·哈希算法