[英]Linked List Delete Method
Could anyone explain why the following delete method does not work? 谁能解释为什么以下删除方法不起作用? It appears to create an infinite loop at the value I am trying to remove.
它似乎在我要删除的值上创建了一个无限循环。 It should loop through a linked list, delete all instances of the value passed to the method, and return the total number of nodes deleted (
return num;
). 它应该遍历一个链表,删除传递给该方法的值的所有实例,并返回删除的节点总数(
return num;
)。
public int delete(T value)
{
int num = 0;
ListNode<T> trav = head;
ListNode<T> next = head.getNext();
while(trav != null) {
if(trav.getValue().compareTo(value) == 0) {
trav = next;
num++;
}
if(next.getValue().compareTo(value) == 0) {
trav = next.getNext();
num++;
}
trav = trav.getNext();
}
return num;
}
You never change the value of next
. 您永远不会更改
next
的值。
if(trav.getValue().compareTo(value) == 0) {
trav = next;
num++;
}
if(next.getValue().compareTo(value) == 0) {
trav = next.getNext();
num++;
}
Since next never changes, you're comparing the same value in the second if
every time. 由于未来永远不会改变,你在第二个比较相同的值
if
每次。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.