写一个完整的python单链表代码
时间: 2023-05-15 17:04:53 浏览: 78
单链表代码
以下是一个简单的 Python 单链表实现:
class Node:
def __init__(self, data=None):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def append(self, data):
new_node = Node(data)
if self.head is None:
self.head = new_node
return
current_node = self.head
while current_node.next is not None:
current_node = current_node.next
current_node.next = new_node
def display(self):
current_node = self.head
while current_node is not None:
print(current_node.data)
current_node = current_node.next
# 测试代码
linked_list = LinkedList()
linked_list.append(1)
linked_list.append(2)
linked_list.append(3)
linked_list.display() # 输出 1 2 3
阅读全文