请编写程序实现单链表插入、删除结点等基本算法。给定一个单链表和一系列插入、删除结点的操作序列,输出实施上述操作后的链表。单链表数据域值为整数。请编写程序实现单链表插入、删除结点等基本算法。
时间: 2024-10-21 12:10:31 浏览: 28
在Python中,我们可以首先定义一个简单的单链表节点类`ListNode`,然后实现插入和删除结点的功能。这里是一个基础版本的实现:
```python
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
# 插入结点函数
def insert_node(head, val):
new_node = ListNode(val)
if not head:
head = new_node
else:
current = head
while current.next:
current = current.next
current.next = new_node
return head
# 删除结点函数(基于值删除)
def delete_node(head, val):
if not head:
return head
elif head.val == val:
return head.next
else:
current = head
while current.next and current.next.val != val:
current = current.next
if current.next:
current.next = current.next.next
return head
# 测试示例
# 初始化一个空链表
head = None
# 操作序列(例如:[5, 3, 7]表示插入5,然后插入3,再插入7)
operations = [5, 3, 7]
for op in operations:
if op == "insert":
head = insert_node(head, int(operations[operations.index(op) + 1]))
else: # 假设删除操作是"delete"
head = delete_node(head, int(operations[operations.index(op) + 1]))
# 输出当前链表的节点值
current = head
while current:
print(current.val, end=" -> ")
current = current.next
print("None") # 结尾的None表示链表结束
阅读全文