-1
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);”处显示空指针异常我只想知道发生了什么?

4

1 回答 1

0

在您的代码中,

tail.setNext(newNode); // tail isn't initialized yet
tail = newNode;

相反,

tail = newNode;    
tail.setNext(newNode);
于 2013-09-27T03:18:40.043 回答