Easy solution of Remove Linked List Elements

  • 0
    public ListNode removeElements(ListNode head, int val) {
        //if list is empty
        if(head == null){
            return head;
        ListNode temp = head, prev = null;
            //if head contains val
            if(head.val == val){
                head = head.next;
            }else if(temp.val != val){
                prev = temp;
            }else{ //when temp.val is equal to val
                prev.next = temp.next;
            temp = temp.next;
        return head;

Log in to reply

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