添加虚拟头结点
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def removeElements(self, head, val):
"""
:type head: ListNode
:type val: int
:rtype: ListNode
"""
dummy_head = ListNode(next=head) #添加一个虚拟节点
cur = dummy_head
while(cur.next!=None):
if cur.next.val == val:
cur.next = cur.next.next
else:
cur = cur.next
# 不能这样,因为链表的下下一个可能为空
## if cur.next.val == val:
## cur.next = cur.next.next
##
## cur = cur.next
return dummy_head.next