Search code examples
javarecursionsingly-linked-list

203. Remove Linked List Elements from the leetcode


This code has to remove the node of the value sent from LinkedList where head and the value is given Can someone tell me what is wrong with the code?

/**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode() {}
     *     ListNode(int val) { this.val = val; }
     *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
     * }
     */
    class Solution {
        public ListNode removeElements(ListNode head, int val) {
            if(head==null) return head;
            if(head.val==val) {head=head.next;}
            ListNode currentNode = head;
            ListNode previousNode = head;
            while(currentNode.val!=val) {
                previousNode=currentNode;
                currentNode = currentNode.next;
            }
            previousNode.next=currentNode.next;
            removeElements(currentNode.next,val);
            return head;
        }
    }

For the test case [7,7,7,7] expected answer is [] but the code is giving the output [7,7,7]


Solution

  • you just need to pass through the list and checking the current node and update the reference if needed

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