请实现完整的结点定义、单链表的插入和删除结点函数定义及调用
时间: 2024-10-14 21:09:40 浏览: 18
在Python中,我们可以定义一个简单的节点类`Node`,然后创建单链表相关的插入(`insert`)和删除(`delete`)操作。这里是一个基础的实现:
```python
class Node:
def __init__(self, data=None):
self.data = data
self.next = None
# 插入节点到链表的头部
def insert_at_head(head, data):
new_node = Node(data)
new_node.next = head
return new_node
# 插入节点到链表的尾部
def insert_at_tail(head, data):
if not head:
return Node(data)
current = head
while current.next:
current = current.next
current.next = Node(data)
return head
# 删除指定值的节点(如果存在)
def delete_node(head, value):
if not head:
return head
if head.data == value:
return head.next
previous = head
current = head.next
while current:
if current.data == value:
previous.next = current.next
return head
previous = current
current = current.next
# 如果值没找到,返回原链表
return head
# 示例调用
head = None
head = insert_at_head(head, 5) # 将5添加到链表头部
head = insert_at_tail(head, 7) # 将7添加到链表尾部
# 删除值为5的节点
new_head = delete_node(head, 5)
#
阅读全文