python 如何记录链表,Python中如何使用链表及其记录方法

原创
admin 10小时前 阅读数 3 #Python

Python中可以使用类来记录链表,以下是一个简单的示例:

class Node:
    def __init__(self, data=None):
        self.data = data
        self.next = None
class LinkedList:
    def __init__(self):
        self.head = None
    def insert(self, data):
        if not self.head:
            self.head = Node(data)
        else:
            current = self.head
            while current.next:
                current = current.next
            current.next = Node(data)
    def display(self):
        elements = []
        current_node = self.head
        while current_node:
            elements.append(current_node.data)
            current_node = current_node.next
        return elements

在上面的代码中,Node类表示链表中的每个节点,它包含两个属性:data表示节点的值,next表示指向下一个节点的指针。LinkedList类表示整个链表,它包含一个属性head表示链表的头节点。

LinkedList类中包含两个方法:insert表示在链表末尾插入一个节点,display表示显示链表中的所有元素,在insert方法中,我们首先检查链表是否为空,如果为空则直接将头节点设置为新节点,如果不为空,则遍历链表找到最后一个节点,并将新节点连接到最后一个节点的next指针上,在display方法中,我们遍历链表中的所有节点,并将节点的值添加到elements列表中,最后返回elements列表。

使用上述代码,我们可以轻松地记录并操作链表。

热门