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;
).
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
.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.