📜  数据结构|链表|问题10(1)

📅  最后修改于: 2023-12-03 14:54:56.872000             🧑  作者: Mango

数据结构 | 链表 | 问题10

问题描述

给定一个单向链表的头节点 head 和一个整数 num,删除链表中所有值为 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