python实现的链表
时间: 2024-10-14 07:00:51 浏览: 36
Python中可以使用内置的数据结构`list`来模拟链表,但实际上更推荐直接使用`ListNode`或`LinkList`这样的自定义类来创建单向链表。链表由一系列节点组成,每个节点包含两个部分:数据域(data)和指向下一个节点的引用(next)。在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):
new_node = Node(data)
if not self.head:
self.head = new_node
else:
current = self.head
while current.next:
current = current.next
current.next = new_node
# 删除节点
def delete(self, key):
if self.head is None or self.head.data == key:
self.head = self.head.next
return
current = self.head
while current.next and current.next.data != key:
current = current.next
if current.next:
current.next = current.next.next
# 遍历链表
def traverse(self):
current = self.head
while current:
print(current.data, end=" -> ")
current = current.next
print("None")
# 使用示例
my_list = LinkedList()
my_list.insert(1)
my_list.insert(2)
my_list.insert(3)
my_list.traverse() # 输出: 1 -> 2 -> 3 -> None
```
阅读全文