Given a class LinkedList
public class LinkedList {
public Node head = null;
public class Node {
public int value;
public Node next;
}
}
I would like to add a method public int count(int value) that counts the amount of times a number occurs in a list.
I tried the following but it doesn't always work and I'm not sure what I am doing wrong.
public int count(int value) {
int counter = 0;
while(head != null) {
Node tmp = head.next;
while(tmp != null) {
if(head.value == value) {
counter++;
}
tmp = tmp.next;
}
head = head.next;
}
return counter;
}
This method works for 1 4 3 4 4 5, int value = 4 (which returns 3, as it should)
but for 1 2 3 4 4 5, int value = 4, it returns 1.
