首页 > 代码库 > 【leetcode?python】 203. Remove Linked List Elements

【leetcode?python】 203. Remove Linked List Elements

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def removeElements(self, head, val):
        """
        :type head: ListNode
        :type val: int
        :rtype: ListNode
        """
        if head==None:return []
        dummy=ListNode(-1)
        dummy.next=head
        p=dummy
        
        while head:
            
            if head.val==val:
                p.next=head.next

                #!!!写的时候一直报错,是因为没有把head节点替换,删除节点时一定要将删除节点替换掉。
                head=p
            
            p=head
            head=head.next
            
            
        return dummy.next

【leetcode?python】 203. Remove Linked List Elements