One possible Solution


  • 0
    N
    public class Solution {
        public ListNode removeElements(ListNode head, int val) {
            ListNode start = head;
            //no elements
            if(head == null) {
                return head;
            } if(head.val == val) { // if head value matches the element to be removed
                if(head.next == null) { // if there are no more elements
                    return null;
                }else { // remove this element and process the remaining list
                    return removeElements(head.next, val);
                }
            } else {
                head.next = removeElements(head.next, val);
                return head;
            }
        }    
    }
    

    Complexity: O(n)


Log in to reply
 

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