题目:(移除链表元素)给你一个链表的头节点 head 和一个整数 val ,请你删除链表中所有满足 Node.val == val 的节点,并返回 新的头节点 。
示例 1:
输入:head = [1,2,6,3,4,5,6], val = 6 输出:[1,2,3,4,5]
示例 2:输入:head = [], val = 1 输出:[]
示例 3:输入:head = [7,7,7,7], val = 7 输出:[]
提示:
列表中的节点数目在范围 [0, 104] 内 1 <= Node.val <= 50 0 <= val <= 50
程序说明:
1、此方法创建了一个哑节点,便于后面返回结果,若dummy.next 也就是head 不为0,且它的值等于目标值的的话,就跳过此节点,若不相等,就 pre 指针继续往后走。(其实我之前想出的是下面的第二个代码,但是会发现它在测试通过了40多组测试集 ,但在( [1,2] 1 )测试集出错了,仔细观察会发现若 head 等于目标值的话,则程序代码就错误了。因此最后我想到使用了哑节点,便可轻松解决问题)
全部代码:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def removeElements(self, head: ListNode, val: int) -> ListNode:
dummy = ListNode(0)
dummy.next = head
pre = dummy
while pre:
if pre.next and pre.next.val == val:
pre.next = pre.next.next
else:
pre = pre.next
return dummy.next
错误代码:
class Solution:
def removeElements(self, head: ListNode, val: int) -> ListNode:
if head is None:
return head
pre = head
cur = head.next
while cur:
if cur and cur.val == val:
pre.next = cur.next
else:
pre = cur
cur = cur.next
if pre.val == val:
return None
return head
题目来源:力扣(LeetCode)



