Home > other >  203. Remove Linked List Elements from the leetcode
203. Remove Linked List Elements from the leetcode

Time:01-01

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]

CodePudding user response:

The original code will only remove one occurrence of the item from the list, and will not work if there are multiple occurrences of the item in the list. You need to remove all the occurrences of the value 7 from the linked list. Use a while loop to iterate through the linked list and remove all the occurrences of the value 7 should solve the issue.

Here is the code:

class Solution {
    public ListNode removeElements(ListNode head, int val) {
        if(head==null) return head;
        while(head.val==val) {
            if(head.next!=null)
                head=head.next;
            else
                return head.next;
        }
        if(head==null) return head;
        ListNode currentNode = head;
        while(currentNode.next!=null) {
            if(currentNode.next.val == val)
                currentNode.next = currentNode.next.next;
            else
                currentNode = currentNode.next;
        }
        return head;
    }
}

CodePudding user response:

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;
        }
  • Related