gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 10:05:45 24 4
gpt4 key购买 nike

我是 Java 新手。

我创建了一个方法,它将从 LinkedList 中删除除第一个元素之外的元素。这个想法是,如果 LinkedList 的元素数据(以整数形式)与参数匹配,则 boolean 值将设置为 true。一旦 boolean 值设置为 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;
}

最佳答案

这里的问题是

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.

希望这能奏效

关于Java - 从 LinkedList 中删除一个元素,除了第一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55094847/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com