我正在尝试将类 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 也被错误初始化。在谷歌上很难找到合适的例子,有没有关于 ADT 初始化的参考资料?