Java - 从 LinkedList 中删除一个元素,除了第一个

Java - Removing an element from LinkedList except first

我是 Java 的新手。

我创建了一个方法,它将从 LinkedList 中删除第一个元素以外的元素。这个想法是,如果 LinkedList 的元素数据(以整数形式)与参数匹配,则布尔值将设置为 true。一旦布尔值设置为真,它将删除任何也与初始元素匹配的元素。

问题来了。例如,如果我要从此 LinkedList 中删除除第一个之外的 5 个:

5 5 5 6 5 7 8 9

我会得到这样的结果:

5 5 6 7 8 9

如您所见,它没有删除第二个位置上的 5。我的代码有什么问题吗?

顺便贴一下代码

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

您跳过了头节点。尝试替换

    Node currentNode = head;

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

您应该更新当前节点引用以及删除节点后 head->next 应该指向当前节点。 试试下面的代码:

if (!duplicate) {
    duplicate = true;
    currentNode = currentNode.next;
     head.next= currentNode.next;
}else {
    currentNode.next = currentNode.next.next;
    currentNode = currentNode.next;
    head.next = currentNode;  }

`

这里的问题在于

if (!duplicate) {
     duplicate = true;
     currentNode = currentNode.next;
} 

您正在标记 duplicate = true 并立即分配 "currentNode = currentNode.next;" 由于此引用正在保留下一个节点 所以

1. Put the condition outside of the loop to check whether the head element itself is 
   that node, if->yes mark isDuplicate = true and proceed in the loop.
2. Inside the loop check afterward and then assign the next node.

希望这能奏效