每日一题力扣203

给你一个链表的头节点 head 和一个整数 val ,请你删除链表中所有满足 Node.val == val 的节点,并返回 新的头节点 。

class Solution:
    def removeElements(self, head: ListNode, val: int) -> ListNode:
        #设置链表头
        current = head
        #如果链表为空,返回空
        if head == None:
            return None
        #当链表头为需要移除的元素时,使链表头指向下一个结点
        while(head):
            if (head.val == val):
                current = head.next
                head = head.next
            else:
                break
        #循环,如果下一个结点的值是需要移除的元素,跳过该结点,指向下一个结点
        while (head and head.next):
            if head.next.val == val:
                head.next = head.next.next
            else:
                head = head.next
        #放回链表头结点
        return current
原文地址:https://www.cnblogs.com/liuxiangyan/p/14532085.html