簡體   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