有人能告诉我我做错了什么吗?通过LinkedList计数和循环

时间:2013-02-24 12:26:26

标签: java loops linked-list counter

我的代码如下:

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 SuperClass

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


}
}

2 个答案:

答案 0 :(得分:2)

如果两种情况都不匹配,您似乎错过了转到下一个节点。

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

答案 1 :(得分:0)

我认为史密斯先生的回答是钉在它上面的。我不会使用大小的循环,但采取的事实是没有下一个作为底部。当然,你的count方法必须在所有情况下返回计数器,而不是0。