单链表的头插尾插和查找删除写一个代码里
时间: 2024-12-13 19:21:17 浏览: 11
单链表是一种线性的数据结构,它由一系列节点组成,每个节点包含数据和指向下一个节点的指针。以下是使用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_at_head(self, data):
new_node = Node(data)
if not self.head:
self.head = new_node
else:
new_node.next = self.head
self.head = new_node
# 尾部插入节点
def insert_at_tail(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 find(self, value):
current = self.head
found = False
while current and not found:
if current.data == value:
found = True
else:
current = current.next
return current is not None
# 删除节点(这里仅删除第一个匹配的节点)
def delete(self, value):
if not self.head:
return
if self.head.data == value:
self.head = self.head.next
else:
current = self.head
while current.next and current.next.data != value:
current = current.next
if current.next:
current.next = current.next.next
# 示例
linked_list = LinkedList()
linked_list.insert_at_head(1) # 插入1到头
linked_list.insert_at_tail(2) # 插入2到尾
linked_list.insert_at_head(0) # 再次插入0到头
# 查找和删除节点
print(linked_list.find(1)) # 输出:True
node_to_delete = linked_list.find(0)
if node_to_delete:
linked_list.delete(node_to_delete.data)
# 打印链表(仅保留1和2)
current = linked_list.head
while current:
print(current.data, end=" -> ")
current = current.next
```
阅读全文