单链表python代码
时间: 2024-09-29 11:13:19 浏览: 35
在Python中,单链表是一种线性的数据结构,每个节点包含两个部分:存储数据的数据域(value),以及指向下一个节点的指针(next)。以下是创建一个简单单链表节点及基本操作(如添加、删除节点)的基本示例:
```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):
if not self.head:
self.head = Node(data)
else:
current = self.head
while current.next:
current = current.next
current.next = Node(data)
# 删除节点
def remove(self, value):
if self.head is None or self.head.data == value:
self.head = self.head.next
return
current = self.head
while current.next and current.next.data != value:
current = current.next
if current.next:
current.next = current.next.next
# 遍历并打印链表
def display(self):
elements = []
current = self.head
while current:
elements.append(current.data)
current = current.next
print("Elements in the list:", elements)
# 示例用法
linked_list = LinkedList()
linked_list.append(1)
linked_list.append(2)
linked_list.append(3)
linked_list.display() # 输出: Elements in the list: [1, 2, 3]
linked_list.remove(2)
linked_list.display() # 输出: Elements in the list: [1, 3]
```
阅读全文