我正在尝试将Integer
数组添加到链接列表的末尾。我的代码添加了第一个整数,然后当它读取第二个整数时,它只是替换了前一个数字。该列表不会为第二个项创建新节点,依此类推,然后获取空指针异常。任何帮助,将不胜感激。
Integer[] values = { 0, 10, 20, 30, 40, 50, 60, 70, 80, 90};
这是我的方法
public boolean addAll(Integer [] c)
{
Node cur = this.head;
if(cur != null)
{
cur = cur.next;
}
int i = 0;
for(; i < c.length; i++)
{
if(cur == null)
{
cur = add(c[i]);
}
else
{
cur = cur.next;
cur.next = add(c[i]);
}
}
size++;
return true;
}
这些是我使用的节点
protected Node ( Comparable data )
{
this.data = data;
this.next = null;
}// end constructor
protected Node ( Comparable data, Node next )
{
this.data = data;
this.next = next;
}// end constructor
所以我很困惑的是如何能够在两个给定节点中传入一个整数数组。这就是我被困的地方。如果我要做这样的事情cur.next = new Node(add(c [i]));它不起作用,因为参数与这两个节点都不匹配。
答案 0 :(得分:0)
试试这个:
public static Node addLast(Node n, Object obj) {
Node node = n;
while ((n.next != null)) {
n = n.next;
}
n.next = new Node(obj, null);
return node;
}
不幸的是,您必须循环查找最后一项,然后插入它。
答案 1 :(得分:0)
我建议您保留指向链接列表中最后一个节点的指针。这大大加快了您的大部分操作。
public void add (Integer[] toAdd) {
int x;
for (x=0; x < x.Length ;x++) {
this.last.next = new Node(toAdd[x]);
this.last = last.next;
}
last.next = null;
}