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
        """
        dummy = ListNode(-217)
        dummy.next = head
        cur = dummy
        while(cur):
            if cur.next:
                while(cur.next and cur.next.val == val): # old wrong answer: if cur.next.val == val; once cur jumps to cur.next, cur.val would be ignored. so we have to make sure there is no val in any cur's following nodes before setting cur = cur.next
                    cur.next = cur.next.next  
                cur = cur.next
            else:
                cur = cur.next
        return dummy.next
                

Once cur jumps to cur.next, cur.val would be ignored. so we have to make sure there is no val in any cur's following nodes before setting cur = cur.next.

And again, always check node.next valid or not before using it. (while(cur.next and cur.next.val == val))

  • No need for two loops, just one loop with "while(cur.next)" is enough, and set cur.next = cur.next.next when cur.next.val == val. When the statement is satisfied, cur is cur.next = cur.next.next already; when the statement isn't satisfied, move cur = cur.next.

while(current.next != null) {
    if (current.next.val == val) {
        current.next = current.next.next;
    } else {
        current = current.next;
    }
}

Last updated