Java 1ms Solution


  • 0

    Take 2 pointers, previous and current
    If you find the current node's value as required one then
    previous.next should point to current.next
    continue doing this till current is not null

    public ListNode removeElements(ListNode head, int val) {
            if(head == null){
                return head;
            }
            while (head != null && head.val == val){
                head = head.next;
            }
            ListNode current = head;
            ListNode previous = null;
            while (current != null){
                if(current.val == val){
                    previous.next = current.next;
                }
                else {
                    previous = current;
                }
                current = current.next;
            }
            return head;
        }
    

Log in to reply
 

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