尝试将 Last() 添加到链接列表时"java.lang.NullPointerException"



我正试图在单个链表的末尾插入一个新节点。但是我在编译后一直得到NullPointerException。

这是Node类。

class Node {
    private int data;
    private Node next;
    public Node(int x){
        data = x;
        next = null;
    }
    public int getData(){
        return data;
    }
    public Node getNext(){
        return next;
    } 
    public void setData(int newx){
        data = newx;
    }
    public void setNext(Node n){
        next = n;
    }   
}

这是单个LL级

public class SingleLL {
    protected Node head=null;
    protected Node tail=null;
    protected int size=0;
    public int getSize(){
        return size;
    }
    public void addLast(int x){
        Node newnode = new Node(x);
        if(size==0){
            head = newnode;
        }
        else{
            tail.setNext(newnode);
            tail = newnode;
        }
        size = size+1;
    }
    public void addfirst(int x){
        Node newnode = new Node(x);
        if(size==0){
            tail = newnode;
        }
        else{
            newnode.setNext(head);
            head = newnode;
        }
        size = size+1;
    }

方法addFirst()有效。当我试图通过addLast()创建LL时,会出现NullPointerException。我想if(size==0){head = newnode;}肯定有问题,但我想不通。

public static void main(String arg[]){
        int[] a = {1,2,3,4,5,6};
        SingleLL myList = new SingleLL();
        for(int i=0;i<a.length;i++){
            myList.addLast(a[i]);
        }
    }           
}

addLastaddFirst中,当列表为空时,需要初始化headtail。否则,其中一个或另一个将永远无法设置,并将导致您的NullPointerException

// In your two add methods:
// addLast: because when size = 1, head equals tail
    if(size==0){
        head = newnode;
        tail = head;
    }
    // addFirst: because when size = 1, head equals tail
    if(size==0){
        tail = newnode;
        head = tail;
    }

记住,NullPointException只会出现在"."之前,就像tail.setNext()一样;让我们看看,如果size=1,那么您调用addLast。目前,head是您添加的新节点,但tail为null。因此,当它使用tail.setNext()时(实际上,null.setNext())将导致NullPointException。

最新更新