クラス 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 の初期化に関する参照はありますか?