题目
思路
可以设置一个虚拟头结点,这样原链表的所有节点就都可以按照统一的方式进行移除。
代码
class Solution:
def removeElements(self, head: Optional[ListNode], val: int):
new_head = ListNode(val=0,next=head)
current = new_head
while current.next:
if current.next.val == val: # 不能使用while,末尾为val时有bug
current.next = current.next.next
else:
current = current.next
return new_head.next