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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值