203. 移除链表元素

<虚拟头结点>

题目

删除链表中等于给定值 val 的所有节点。

示例:

输入: 1->2->6->3->4->5->6, val = 6
输出: 1->2->3->4->5

我的思路

class Solution(object):
    def removeElements(self, head, val):
        """
        1.构造一个val=-1的节点,让它连上head链表作为头结点
        2.定义前一个节点为pre,当前节点为cur
        3.遇到要删除的节点cur,就pre.next = cur.next
        """
        node = ListNode(-1)
        node.next = head
        if not head:
            return None
        pre = node
        cur = node.next
        while cur:
            if cur.val == val:
                pre.next = cur.next
            else:
                pre = cur
            cur = cur.next
        return node.next

题解 - 递归

...

总结

原文地址:https://www.cnblogs.com/remly/p/11450476.html