1

数値 (リンクされたリストで要素が見つかった回数) を返すメソッドを作成する必要があります。これまでのところ、私は持っています。

package Question4;

import net.datastructures.Node;

public class SLinkedListExtended<E> extends SLinkedList<E> {
    // returns the number of occurrences of the given element in the list
    public int count(E elem) {

        Node<E> cursor = tail;
    int counter = 0;

    if ((cursor != null) && (!(cursor.getElement().equals(elem)))) { //tail isnt null and element is not equal to elem 

        cursor = cursor.getNext(); //go to next node

    } else if ((cursor != null) && (cursor.getElement().equals(elem))){ //cursor isn't null and element equals elem

        counter++; //increment counter
    }
    else { 
        return counter; //return counter 
    }
    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 を返します。これはおそらくカウンター整数が 0 のままで、ループ ステートメントを通過していないためです。どんなアイデアでも大歓迎です。

編集。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<String> list = new SLinkedList<String>();

    list.insertAtHead("lol");

}

}

4

4 に答える 4

0

マーティンの答え(要素を数える方法を教えてくれます)をこれと組み合わせることをお勧めします。これは foreach を使用できるようにする方法を教えてくれSLinkedListExtendedますIterable. onSLinkedListですが、そのコードを変更しないように言われたと思います):

public class SLinkedListExtended<E> extends SLinkedList<E> implements Iterable<E> () {

    public Iterator<E> iterator() {
        final Node<E> itHead = head;
        return new Iterator<E>() {

            Node<E> current = itHead;
            long position = 0;

            public boolean hasNext() {
                return current != null && position < size;
            }

            public E next() {
                current = current.getNext();
                ++position;
                return current.getElement();
            }

            public void remove() {
                throw new UnsupportedOperationException("Not supported yet.");
            }

        };
    }

};

すべての詳細を保証することはできませんが、これで大部分をカバーできるはずです。equalsの代わりに を使用することも検討できますが==、要素が null かどうかを確認することを忘れないでください。

nexthasNextisの場合にのみ呼び出す必要がtrueあるため、例外がスローされても問題ありません (ただしNoSuchElementException、契約に準拠する必要があります)。

実装Iterableすると、クラスが Collections ライブラリと互換性を持つようになるため、foreach がサポートされますが、それを使用してiteratorhasNextnext自分自身を呼び出して生の反復を行うことができます。

于 2013-02-24T22:48:58.953 に答える
0

欠けていた基本的なものの 1 つはループでした。基本的に何かを検索しているので、リスト全体をループする必要があります。検索している要素と一致する要素に遭遇したら、カウントを 1 増やします。リスト全体のループが終了したら、そのカウントを返します。これが私の解決策です。あなたが理解できるように、私はそれを単純に保ちます:

import java.util.LinkedList;

public class Duplicates<E> extends LinkedList<E> {

    public static void main(String[] args) {
        Duplicates<String> duplicates = new Duplicates<String>();
        duplicates.add("abc");
        duplicates.add("def");
        duplicates.add("def");
        duplicates.add("xyz");
        System.out.println(duplicates.duplicateCount("def"));
        duplicates.add(null);
        duplicates.add("def");
        duplicates.add(null);
        System.out.println(duplicates.duplicateCount("def"));
        System.out.println(duplicates.duplicateCount(null));
    }

    public int duplicateCount(E element) {
        int count = 0;
        for (E e : this) {
            if (e == element) {
                count++;
            }
        }
        return count;
    }
}

出力:

2
3
2
于 2013-02-24T01:04:22.890 に答える