在Python中创建单链表,首先需要定义一个节点类`Node`,然后定义一个链表类`LinkedList`。以下是创建单链表的基本步骤和代码示例:
1. 定义节点类`Node`,包含数据域`data`和指针域`next`:
class Node:def __init__(self, data=None):self.data = dataself.next = None
2. 定义链表类`LinkedList`,包含头节点`head`和链表操作方法:
class LinkedList:def __init__(self):self.head = None在链表尾部添加节点def append(self, data):new_node = Node(data)if not self.head:self.head = new_nodeelse:current = self.headwhile current.next:current = current.nextcurrent.next = new_node打印链表所有节点def display(self):current = self.headwhile current:print(current.data, end=" -> ")current = current.nextprint("None")
3. 创建一个空链表实例,并添加节点:
创建链表实例my_list = LinkedList()在链表尾部添加节点my_list.append(1)my_list.append(2)my_list.append(3)打印链表my_list.display() 输出: 1 -> 2 -> 3 -> None
以上代码展示了如何在Python中创建单链表,包括定义节点类和链表类,以及如何在链表尾部添加节点和打印链表内容

