返回

203. 移除链表元素:用Python优雅地解决难题

闲谈

def remove_elements(head: ListNode, val: int) -> ListNode:
    """
    Remove all elements from a linked list of integers that have value val.
    
    Args:
        head (ListNode): The head of the linked list.
        val (int): The value to remove.
    
    Returns:
        ListNode: The head of the linked list after removing all elements with value val.
    """
    
    # Initialize a dummy node to simplify the code.
    dummy = ListNode(0)
    dummy.next = head
    
    # Initialize the current node to the dummy node.
    current = dummy
    
    # Iterate over the linked list.
    while current.next is not None:
        
        # If the next node has the value we want to remove, skip it.
        if current.next.val == val:
            current.next = current.next.next
        
        # Otherwise, move the current node forward.
        else:
            current = current.next
    
    # Return the head of the linked list after removing all elements with value val.
    return dummy.next

# Example usage
head = ListNode(1)
head.next = ListNode(2)
head.next.next = ListNode(3)
head.next.next.next = ListNode(4)
head.next.next.next.next = ListNode(5)

val = 2

# Remove all elements with the value 2 from the linked list.
new_head = remove_elements(head, val)

# Print the linked list after removing all elements with the value 2.
current = new_head
while current is not None:
    print(current.val)
    current = current.next

简介

链表是一种常用的数据结构,广泛应用于各种编程任务中。当需要存储和处理有序数据时,链表通常是一个不错的选择。然而,在某些情况下,我们可能需要从链表中删除具有特定值的元素。这就是LeetCode 203. 移除链表元素问题所要解决的难题。

算法

为了解决这个问题,我们可以使用以下算法:

  1. 初始化一个哨兵节点(dummy node)并将其指向链表的头节点。哨兵节点简化了代码,使我们可以将链表视为一个循环链表。
  2. 使用一个指针current指向哨兵节点。
  3. 循环遍历链表,直到current.next为None。
  4. 如果current.next.val等于要删除的值,则将current.next指向current.next.next,跳过具有该值的节点。
  5. 否则,将current移到下一个节点。
  6. 返回哨兵节点的下一个节点作为新的头节点。

代码实现

def remove_elements(head, val):
    """
    Remove all elements from a linked list of integers that have value val.
    
    Args:
        head (ListNode): The head of the linked list.
        val (int): The value to remove.
    
    Returns:
        ListNode: The head of the linked list after removing all elements with value val.
    """
    dummy = ListNode(0)
    dummy.next = head
    current = dummy
    
    while current.next is not None:
        if current.next.val == val:
            current.next = current.next.next
        else:
            current = current.next
    
    return dummy.next

示例

给定一个链表:[1, 2, 3, 4, 5]和一个值val = 2,应用remove_elements算法后,链表将变为:[1, 3, 4, 5]。

总结

LeetCode 203. 移除链表元素问题考验了程序员对链表数据结构的理解和算法应用能力。通过使用哨兵节点和循环遍历的方式,我们能够有效地从链表中删除具有特定值的元素。希望本文对您理解和解决此问题有所帮助。如果您有任何疑问或建议,欢迎在评论区留言。