📅  最后修改于: 2023-12-03 14:54:56.872000             🧑  作者: Mango
给定一个单向链表的头节点 head 和一个整数 num,删除链表中所有值为 num 的节点,并返回新的头节点。
def delete_node(head, num):
"""
:param head: 头节点
:param num: 要删除的节点值
:return: 新的头节点
"""
# 处理头节点需要被删除的情况
while head and head.val == num:
head = head.next
if not head:
return None
# 处理除头节点外其他节点需要删除的情况
cur_node = head
pre_node = None
while cur_node:
if cur_node.val == num:
pre_node.next = cur_node.next
cur_node = pre_node.next
else:
pre_node = cur_node
cur_node = cur_node.next
return head
# 定义链表
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
# 构造用例
node1 = ListNode(1)
node2 = ListNode(2)
node3 = ListNode(3)
node4 = ListNode(2)
node5 = ListNode(5)
node6 = ListNode(2)
node1.next = node2
node2.next = node3
node3.next = node4
node4.next = node5
node5.next = node6
# 测试用例1:删除中间节点
new_head = delete_node(node1, 2)
assert new_head.val == 1
assert new_head.next.val == 3
assert new_head.next.next.val == 5
assert new_head.next.next.next is None
# 测试用例2:删除头节点
new_head = delete_node(node1, 1)
assert new_head.val == 3
assert new_head.next.val == 2
assert new_head.next.next.val == 5
assert new_head.next.next.next.val == 2
assert new_head.next.next.next.next is None
# 测试用例3:删除所有节点
new_head = delete_node(node1, 2)
assert new_head.val == 1
assert new_head.next.val == 3
assert new_head.next.next.val == 5
assert new_head.next.next.next is None