思路:不用设置两个外部引用,可以每次检查当前节点的下一个节点的值是否等于给定值
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def removeElements(self, head: ListNode, val: int) -> ListNode:
copy=ListNode(None)
copy.next=head
p=copy
while p.next:
if p.next.val==val:
p.next=p.next.next
else:
p=p.next
return copy.next
class Solution(object):
def removeElements(self, head, val):
"""
:type head: ListNode
:type val: int
:rtype: ListNode
"""
if head == None:
return None
copy = head
while copy.next != None:
if copy.next.val == val:
copy.next = copy.next.next
continue
copy = copy.next
if head.val == val:
return head.next
else:
return head