leetcode203. 移除链表元素

本文详细解析了LeetCode上移除链表元素问题的解决方案。通过双指针技巧,首先移除链表头部的所有目标值节点,再遍历链表移除剩余的目标值节点。文章提供了完整的Python代码实现,帮助读者理解并掌握这一算法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

思路比较简单,先把头部得所有值为val的元素移除,当然是在头不为None的时候,然后对后面值不为val的元素进行删除就行:
https://leetcode-cn.com/problems/remove-linked-list-elements

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def removeElements(self, head, val):
        """
        :type head: ListNode
        :type val: int
        :rtype: ListNode
        """
        while head:
            if head.val == val:
                head = head.next
            else:
                break
        if head:
            cur = head
            next = cur.next
            while next:
                if next.val != val:
                    cur = next
                else:
                    cur.next = next.next
                next = cur.next
        return head
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值