Easy to understand Python with comments, but a little slow

  • 0
    # 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
            while h1:
                if h1.val==val:
                    h1=h1.next  # h2 does not change since we remove a node
                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.