One Java solution


  • 0
    C

    '''
    public void removeElements(int val){

        Node temp = head;
    
        while(temp.next != null){
            if(temp.data == val ){
                delete(temp);
            }
            temp = temp.next;
        }
    
        if(temp.next == null && temp.data == val){
            deleteTailNode();
        }
     return;
    }
    
    private void delete(Node n){
    
        if (n == head){
            head = n.next;
            return;
        }
    
        if( n.next == null){
           deleteTailNode();
           return;
        }
    
         n.data = n.next.data;
         n.next = n.next.next;
         return;
      }
    
    private void deleteTailNode(){
    
        Node tempNode = head;
        while(tempNode.next.next != null){
            tempNode = tempNode.next;
        }
        tempNode.next = null;
        return;
    }
    

    '''


Log in to reply
 

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