public class Node {
private String element;
private Node next;
public void setNext(Node newNext) {
next = newNext;
}
public class SLinkedList {
protected Node head;
protected Node tail;
protected long size;
public void addLast(Node newNode) {
newNode.setNext(null);
tail.setNext(newNode);
tail = newNode;
size = size + 1;
}
public class TestLinkedList {
public static void main(String args[]) {
SLinkedList myList = new SLinkedList();
//create 3 node
Node m = new Node("Tom1", null);
Node n = new Node("Tom2", null);
Node p = new Node("Tom3", null);
//add 1 node at the end
myList.addLast(m);
//print
System.out.println(myList);
System.out.println("Size=\t"+myList.getSize());
}
执行时“myList.addLast(m);它在”tail.setNext(newNode);“处显示nullpointerexception。” 我只是想知道发生了什么?
答案 0 :(得分:0)
在您的代码中,
tail.setNext(newNode); // tail isn't initialized yet
tail = newNode;
相反,
tail = newNode;
tail.setNext(newNode);