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

python 复制代码
# Linked list node class
class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

# Queue class
class Queue:
    def __init__(self):
        self.front = None  # Queue front
        self.rear = None  # Queue rear

    def is_empty(self):
        return self.front is None

    def enqueue(self, val):
        new_node = ListNode(val)
        if self.rear is None:
            self.front = self.rear = new_node
            return
        self.rear.next = new_node
        self.rear = new_node

    def dequeue(self):
        if self.is_empty():
            return "Queue is empty"
        val = self.front.val
        self.front = self.front.next
        if self.front is None:
            self.rear = None
        return val

    def peek(self):
        if self.is_empty():
            return "Queue is empty"
        return self.front.val

    def size(self):
        count = 0
        cur = self.front
        while cur:
            count += 1
            cur = cur.next
        return count

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
    print("Queue elements:")
    cur = my_queue.front
    while cur:
        print(cur.val, end=" ")
        cur = cur.next
    print()

    # 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
    print("Queue elements:")
    cur = my_queue.front
    while cur:
        print(cur.val, end=" ")
        cur = cur.next
    print()
    
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

相关推荐
yyfhq37 分钟前
sdnet
python
测试19981 小时前
2024软件测试面试热点问题
自动化测试·软件测试·python·测试工具·面试·职场和发展·压力测试
love_and_hope1 小时前
Pytorch学习--神经网络--搭建小实战(手撕CIFAR 10 model structure)和 Sequential 的使用
人工智能·pytorch·python·深度学习·学习
泉崎1 小时前
11.7比赛总结
数据结构·算法
你好helloworld1 小时前
滑动窗口最大值
数据结构·算法·leetcode
海阔天空_20131 小时前
Python pyautogui库:自动化操作的强大工具
运维·开发语言·python·青少年编程·自动化
零意@1 小时前
ubuntu切换不同版本的python
windows·python·ubuntu
思忖小下2 小时前
Python基础学习_01
python
q567315232 小时前
在 Bash 中获取 Python 模块变量列
开发语言·python·bash
是萝卜干呀2 小时前
Backend - Python 爬取网页数据并保存在Excel文件中
python·excel·table·xlwt·爬取网页数据