Java - Removing an element from LinkedList except first

Blanc IT :

I'm new to Java.

I have created a method where it will remove elements from LinkedList except the first one. The idea is a boolean will be set to true if a LinkedList's element data (Which is in Integer) matched with parameter. Once the boolean sets to true, it will remove any element that also matched with initial one.

Now for the problem. For example, if I were to remove 5 except the first one from this LinkedList:

5 5 5 6 5 7 8 9

I will get result like this:

5 5 6 7 8 9

As you can see, it didn't remove the 5 on the second position. Is there anything wrong with my code?

Here's the code by the way

public void append(int data) {
    Node newNode = new Node(data);
    if (head == null) {
        head = new Node(data);
        return;
    }

    Node lastNode = head;
    while (lastNode.next != null) {
        lastNode = lastNode.next;
    }

    lastNode.next = newNode;
    return;
}

public void insert(int data) {
    Node newData = new Node(data);
    newData.next = head;
    head = newData;
}

public void removeExceptFirst(int dataValue) { //The mentioned method
    boolean duplicate = false;
    Node currentNode = head;
    while (currentNode.next != null) {
        int value = currentNode.next.data;
        if (value == dataValue) {
            if (!duplicate) {
                duplicate = true;
                currentNode = currentNode.next;
            } else {
                currentNode.next = currentNode.next.next;
            }
        } else {
        currentNode = currentNode.next;
        }
    }
    return;
}
lauthu :

You skipped head node. Try replace

    Node currentNode = head;

with

    Node currentNode = new Node();
    currentNode.next = head;

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=159227&siteId=1