LinkedList输出null的Java实现
我在这里遇到了一点麻烦,我正在实现我自己的链表类,它实现了您所期望的功能,它将元素添加到列表中,并使用ToString方法输出它们。出于某种原因,它会将元素添加到列表中,但在输出列表时,它会在前面添加一个空元素,并忽略打印最后一个元素。以下是我的主要课程代码:
public class MyList {
public static void main(String[] args) {
List<Integer> list = new LinkedList<>();
list.add(1); // [1]
list.add(2); // [1 2]
list.add(3); // [1 2 3]
System.out.println(list);
}
}
下面是add And ToString方法:
public class LinkedList<E> {
private Node<E> first, last;
private int size = 0;
// new empty list constructor.
public LinkedList() {
first = last = new Node<>(null, null);
}
public void add(E e) {
last.next = new Node<>(e, null);
last = last.next;
++size;
}
public void addFirst(E e) {
Node<E> n = new Node<>(e, null);
n.next = first.next;
first = n;
++size;
}
public String toString() {
try {
if (first != null) {
Node<E> n = first;
String s = "[ ";
while (n.next != null) {
s = s + n.data + " ";
n = n.next;
}
return s + "]";
}
} catch (NoSuchElementException e) {
//return "List is empty!";
}
return "List is empty!";
}
当我试图编译上面的代码时,我得到了这个输出(当它应该是[ 1 2 3 ]
):
> [ null 1 2 ]
任何帮助都将不胜感激。谢谢
# 1 楼答案
这一行:
将第一个元素添加到列表时,应该抛出一个
NullPointerException
,因为当列表为空时first
和last
应该是null
。它显然没有在你身上出错这一事实意味着last
必须指向有效的Node
对象,然后才能将任何内容添加到列表中。您的帖子中没有所有的代码,但我非常确信您正在创建一个新的Node
,并在调用列表的构造函数时指向它first
和last
,这意味着您的列表将以一个“空”节点开始你应该做的是从
first
和last
都等于null
开始。然后在add()
方法中执行以下操作:此外,您还需要对
toString()
方法进行一些研究,因为这一行:将导致循环绕过列表中的最后一个元素(因为列表元素的
next
为空是正确的)