下面是一个Python实现的删除链表元素的程序:

class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

def removeElements(head: ListNode, val: int) -> ListNode:
    # 如果链表头节点的值等于要删除的值,则直接将头节点向后移动一位
    while head and head.val == val:
        head = head.next
    # 如果链表已经为空或者只有一个节点,直接返回
    if not head or not head.next:
        return head
    # 定义一个指针用于遍历链表
    cur = head
    # 遍历链表,判断当前节点的下一个节点是否需要删除,如果需要,则将当前节点的next指针指向下一个节点的next指针
    while cur.next:
        if cur.next.val == val:
            cur.next = cur.next.next
        else:
            cur = cur.next
    # 返回删除元素后的链表头节点
    return head

这个程序的时间复杂度是O(n),其中n是链表的长度

写一个删除链表元素的程序

原文地址: https://www.cveoy.top/t/topic/ey1P 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录