Search code examples
javadata-structureslinked-listsingly-linked-listdoubly-linked-list

Remove the same elements from a linked list


I want to remove the required values(int) in a linked list. For example, {3,1,2,3,3}. I use remove(int 3), then it should be {1,2}. Can you help me, my code can just remove the 3 in the index 0, but I still need to remove the index 3 and 4.

public void remove(int value) {
    IntegerNode curr = head;
    IntegerNode prev = null;

    for(curr = head; curr != null; curr = curr.next) {
        if(curr.item == value) {
            break;
        }

        prev = curr;
    }

    if(prev == null) {
        head = curr.next;
    } else {
        prev.next = curr.next;
    }

    count--;
}

Solution

  • your code is good but you forgot to check all elements because in for loop when the first element 3 is found will get into break , so it won't check the rest of 3s elements . try this code ,also you don't need break just when you find this element delete it and go to the next:

    PS : The count variable you need to minimize it after every deletion process , in your code it will be executed just for one time .

    public void remove(int value) {
        IntegerNode curr = head;
        IntegerNode prev = null;
    
            for (curr = head; curr != null; curr = curr.next) {
                if(curr.item == value) {
                    if (prev == null) {
                        head = curr.next;
                    } else {
                        prev.next = curr.next;
                    }
                        count--;
                }
                prev = curr;
            }
    }