0

私のコードは次のとおりです。

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

}

メソッド count は、指定された要素 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


}
}
4

2 に答える 2

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;
}
于 2013-02-24T12:32:17.240 に答える
0

MrSmithの答えはそれを釘付けにしていると思います。ループにサイズは使用しませんが、次がないという事実を底として取り上げます。もちろん、count メソッドは、0 ではなく、すべてのケースでカウンターを返す必要があります。

于 2013-02-24T13:29:46.943 に答える