java - Java - 从 LinkedList 中删除一个元素,除了第一个
问题描述
我是 Java 新手。
我创建了一个方法,它将从 LinkedList 中删除除第一个元素之外的元素。这个想法是,如果 LinkedList 的元素数据(在 Integer 中)与参数匹配,则布尔值将设置为 true。一旦布尔值设置为 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;
}
您正在标记重复 = 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 - Android BottomNavigationBar 使用 ConstraintLayout 和 ScrollView
- amazon-web-services - DynamoDB 扫描所有符合条件的项目
- c++ - 将一个类'对象设置为另一个类'方法
- android - :app:assembleRelease 和 assembleRelease 之间的区别
- javascript - 如何遍历两个数组的对象作为JavaScript中的以下输出
- reactjs - 不能用仅从 Github 获取的内容创建博客吗?
- java - 如果存在,则在 java 8 中使用反射器设置字段值
- sql - oracle查询从表中获取过去n(例如过去7)小时的每小时唯一用户计数
- java - 是否可以使用 JFR 和 JMC(JDK 任务控制)可视化每个线程的 cpu 使用情况?
- r - r 中的阻塞时间列取决于小时间隔