思路比较简单,先把头部得所有值为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