【发布时间】:2019-08-01 08:28:48
【问题描述】:
我是 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;
}
【问题讨论】:
-
如果你想防止重复,有什么原因不能使用LinkedHashSet?
-
@D.B.这可能有效,但我试图在不使用它的情况下删除重复项
标签: java linked-list singly-linked-list