此方法旨在每次 a 中的项目linked list
等于给定元素(在我的情况下为 elem)时添加到计数器。
我有;
public int count(E elem) {
Node <E> current = new Node <E>();
current = head;
int counter = 0;
if (current == null) {
return 0; //current is null
}
for (int i = 0; i<size; i++){
if (elem == current){
counter++;
head = current.getNext();
}
}
return counter;
}
public static void main(String[] args) {
SLinkedListExtended<String> x = new SLinkedListExtended<String>();
x.insertAtTail("abc");
x.insertAtTail("def");
x.insertAtTail("def");
x.insertAtTail("xyz");
System.out.println(x.count("def")); // should print "2"
x.insertAtTail(null);
x.insertAtTail("def");
x.insertAtTail(null);
System.out.println(x.count("def")); // should print "3"
System.out.println(x.count(null)); // should print "2"
}
}
但是在运行时,它每次都返回 0。我查看了我的循环,无法弄清楚我哪里出错了