python 如何记录链表,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
列表。
使用上述代码,我们可以轻松地记录并操作链表。