单链表实验python
时间: 2024-10-25 18:00:41 浏览: 25
单链表是一种基础的数据结构,它由一系列节点组成,每个节点包含数据和指向下一个节点的引用。在Python中,我们可以手动创建一个单链表并进行一些基本操作,如添加元素、删除元素以及遍历链表。
下面是一个简单的单链表实现示例:
```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 delete(self, value):
if self.head is not None and self.head.data == value:
self.head = self.head.next
return
current = self.head
prev = None
while current is not None:
if current.data == value:
prev.next = current.next
return
prev = current
current = current.next
# 遍历链表打印所有元素
def print_list(self):
current = self.head
while current:
print(current.data, end=" -> ")
current = current.next
print("None")
# 使用例子
ll = LinkedList()
ll.append(1)
ll.append(2)
ll.append(3)
ll.print_list() # 输出: 1 -> 2 -> 3 -> None
ll.delete(2)
ll.print_list() # 输出: 1 -> 3 -> None
```
阅读全文