2ms easy to understand iterative solution


  • 0
    B

    public class Solution {
    public ListNode removeElements(ListNode head, int val) {
    if (head == null) {
    return head;
    }

        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode prev = dummy;
        
        while (head != null) {
            while (head != null && head.val == val) {
                head = head.next;
            }
            prev.next = head;
            prev = prev.next;
            
            //edge case, [1] 1, without this 'if statement' will possibly throw exception.
            if (head != null) {
            head = head.next;
            }
        }
        return dummy.next;
    }
    

    }


Log in to reply
 

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