单链表声明节点,初始化头节点,建立头插和尾插,按值删找写一个代码里并覆值操作两次
时间: 2024-12-10 22:35:48 浏览: 24
在Python中,我们可以使用一个Node类表示单链表的节点,然后定义一个LinkedList类来处理链表的操作。这里是一个简单的示例,包括节点的声明、初始化头节点、头部插入、尾部插入以及按值删除和覆盖操作:
```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 self.head is not None:
new_node.next = self.head
self.head = new_node
# 尾部插入
def insert_at_tail(self, data):
new_node = Node(data)
if self.head is None:
self.head = new_node
return
last_node = self.head
while last_node.next:
last_node = last_node.next
last_node.next = new_node
# 按值查找并删除节点(如果存在)
def delete_by_value(self, value):
current = self.head
if current and current.data == value:
self.head = current.next
current = None
return
prev = None
while current and current.data != value:
prev = current
current = current.next
if current:
prev.next = current.next
current = None
# 覆盖操作(例如替换最后一个节点的值)
def override_last_value(self, new_data):
if self.head is not None:
last_node = self.head
while last_node.next:
last_node = last_node.next
last_node.data = new_data
# 示例
ll = LinkedList()
ll.insert_at_head(1) # [1]
ll.insert_at_head(0) # [0, 1]
ll.insert_at_tail(2) # [0, 1, 2]
print("Before deletion:", ll) # [0, 1, 2]
ll.delete_by_value(1) # [0, 2]
print("After deleting 1:", ll) # [0, 2]
ll.override_last_value(3) # [0, 2] -> [0, 3]
print("After overriding last value:", ll) # [0, 3]
```
阅读全文