0
我的代碼如下:有人能告訴我我做錯了什麼嗎?計數和循環通過LinkedList的
import net.datastructures.Node;
public class SLinkedListExtended<E> extends SLinkedList<E> {
public int count(E elem) {
Node <E> currentNode = new Node <E>();
currentNode = head;
int counter = 0;
for (int i = 0; i<size; i++){
if (currentNode == null) {
return 0; //current is null
}
else if (elem.equals(currentNode.getElement())){
counter++;
currentNode = currentNode.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"
}
}
的方法計數應該返回給定元素,ELEM在列表中找到的倍量的數量。我寫了這個循環,但每次只返回0。一個nullpointerexception也被拋出。
編輯:SLinkedList父類
import net.datastructures.Node;
public class SLinkedList<E> {
protected Node<E> head; // head node of the list
protected Node<E> tail; // tail node of the list (if needed)
protected long size; // number of nodes in the list (if needed)
// default constructor that creates an empty list
public SLinkedList() {
head = null;
tail = null;
size = 0;
}
// update and search methods
public void insertAtHead(E element) {
head = new Node<E>(element, head);
size++;
if (size == 1) {
tail = head;
}
}
public void insertAtTail(E element) {
Node<E> newNode = new Node<E>(element, null);
if (head != null) {
tail.setNext(newNode);
} else {
head = newNode;
}
tail = newNode;
size++;
}
public static void main(String[] args) { // test
}
}
什麼是'SLinkedList'? – 2013-02-24 12:27:49
dos頭有什麼價值? – 2013-02-24 12:30:12
1.您應該在繼續之前驗證'elem'不爲空。'節點 currentNode =新節點();'是一個完全無用的行,將其刪除。 3.'currentNode = head;'意味着無法訪問你的超類狀態,那很糟糕,修復它。如果沒有看到超類的簽名,它的變量以及「equals」的實現,我們無法幫助你。 –
Perception
2013-02-24 12:30:24