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

相关推荐
卷无止境27 分钟前
在 awesome-fastapi 里,哪些库值得一看?
后端·python
zhanghaha13141 小时前
Python进阶教程:6_JSON 数据解析 —— 新手完全指南
开发语言·python·json
Python私教1 小时前
API 输出模型怎么设计:从 model_dump() 到显式展示层
python·fastapi
白狐_7981 小时前
408数据结构第8章:排序②——性质对比秒杀、场景选择与外部排序
java·数据结构·算法
Python私教1 小时前
本地 AI 工具服务该绑定 127.0.0.1 还是 0.0.0.0?
python·fastapi
zander2581 小时前
LeetCode 84:柱状图中的最大矩形——单调栈如何确定左右边界
java·数据结构·算法
卷无止境2 小时前
FastAPI 的Admin面板生态
后端·python
ctlover2 小时前
Streamlit 框架
python
ι:3 小时前
MATLAB 与 Python 搭建无人机地面站:优势、劣势与选型逻辑
python·matlab·无人机
船厂电气自动化ai大模型3 小时前
AI大模型与数学 第32课 函数凹凸性与二阶导数:拐点求解、凹凸区间计算(10道二阶导数计算题)
数据结构·人工智能·python·深度学习·算法