NotToBrag NotToBrag - 2 months ago 17
Java Question

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;
).

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;
}

Answer

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.