2

クラス NumLinkedList の NumList の抽象データ型を単一リンクリストとして実装しようとしています。

public class NumLinkedList implements NumList
{

Node head;
int nItem;

private class Node
{
    public Node next;
    public double value;
    public Node(double i, Node j)
    {
        value = i;
        next = j;

    }

}

public NumLinkedList()
{
    head = null;
    nItem = 0;

}

は私の初期化であり、次の方法で問題が発生しています。

public void print()
{
    Node currNode = head;
    while(currNode.next != null)
    {
        currNode = currNode.next;
        System.out.println(currNode.value);
    }

}

public int size()
{
    int size = 0;
    Node currNode = head;
    while(currNode.next != null)
    {
        currNode = currNode.next;
        size++;
        nItem++;

    }
    return size;

}

public void insert(int i, double value)
{
    if( i < 0)
    {
        System.out.println("Error. out of bounds.");
    }
    if ( i > size())
    {
        Node currNode = head;
        for(int j = 0; j < i; j++)
        {
            currNode = currNode.next;
        }
        currNode.next = new Node(value,null);
    }

    if ( i <= size())
    {
        Node currNode = head;
        for(int j = 0; j < i-1; j++) // this moves CurrNode to the i-1th node
        {
            currNode = currNode.next;
        }
        currNode.next = new Node(value,currNode.next);
    }

    nItem++;
}

テストコードを実行すると、

public static void main (String[] args)
{
    NumLinkedList test;
    test = new NumLinkedList();

    //System.out.println("this is how many initial items the initialized list has");
    //System.out.println(test.size());
    test.insert(1, 0.1);
    System.out.println("have tried to insert value 0.1 @ position 1, that is the first element in list.");
    test.print();
    System.out.println("tried print(). did it work?");
    test.insert(4, -1);

エラーが表示されます

test.insert(1, 0.1);

、参照

if ( i > size())

while(currNode.next != null)

配列 ADT の初期化にも失敗したため、リスト ADT も誤って初期化されていると思われます。Google で適切な例を見つけるのは難しいですが、ADT の初期化に関する参照はありますか?

4

1 に答える 1

1

問題は初期化ではなく、メソッド自体にあります。

問題は、 を に初期化しているのに、headとのnull両方でprintを実行しsizeていることです。それはすぐそこに投げます。すべてのメソッドに移動し、制限の場合に特別なコードを追加する必要があります。currNode = headnullcurrNode.nextNullPointerException

の場合print:

if ( head == null )
    return;

の場合size:

if ( head == null )
    return 0;

sizeまたは、メソッド全体を単純なreturn nItem;ステートメントに単純に置き換えることもできます。

の場合insert:

if ( head == null )
{
    head = new Node(value,null);
    return;
}

余談ですが、 では、最初insertの 内にも が必要であり、3 番目を.に置き換える必要があります。returnififelse

于 2012-09-27T23:21:09.953 に答える