Easy to understand Python with comments, but a little slow


  • 0
    R
    # 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
            """
            while head and head.val==val:
                head=head.next    # if the first one has value of val
            if not head:
                return None
            h1=h2=head
            while h1:
                if h1.val==val:
                    h2.next=h2.next.next
                    h1=h1.next  # h2 does not change since we remove a node
                    continue
                h1,h2=h1.next,h1  # h1,h2 shift to next node
            return head

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.