繁体   English   中英

尝试将Last()添加到链表中时出现“ java.lang.NullPointerException”

[英]“java.lang.NullPointerException” when trying to addLast() into a linkedlist

我正在尝试在单个链表的末尾插入一个新节点。 但是我一直在编译后得到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。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM