实现单向链表的插入与删除代码
时间: 2024-09-24 16:07:23 浏览: 36
C语言之单向链表详解及实例代码
在许多编程语言中,如Python、C++或者Java,单向链表是一种常见的数据结构,它的节点包含数据和指向下一个节点的指针。以下是使用Python编写的基本单向链表插入和删除操作的例子:
```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 or not head.data == value:
return head
if head.data == value:
head = head.next
return head
current = head
while current.next and current.next.data != value:
current = current.next
if current.next:
current.next = current.next.next
return head
```
阅读全文