簡體   English   中英

為什么我不能將LinkedList的最后一個節點設置為null?

[英]Why can't I set the last node of a LinkedList as null?

我的removeLast方法用於返回鏈表中的最后一個元素,然后返回它。 這是我到目前為止:

public int removeLast() {
    int x = getLast();
    removeLast(first);
    return x;
}

private void removeLast(Node n) {
    if (n == null) {
        throw new ListException("Empty list");
    } else {
        if (n.next == null) {
            n = null;
        } else {
            removeLast(n.next);
        }
    }
}

first = LinkedList類中的實例變量

removeLast()成功返回最后一個數字(getLast()實際上是這樣做的,然后removeLast(Node n)應該實際刪除它。但是,該部分不起作用。

您沒有正確地將鏈接列表的最后一個節點設置為null 正如@Kevin Esche所說,
n = nulln設置為null,而不是鏈表的節點。 在我的代碼中,我引用帶有link引用的節點並將其設置為null

這應該工作。

public int removeLast(Node n){  //returns and removes the last node

    int x = getLast();
    if(n == start && n.link == null) //list has only last node
        start = null;
    else {
        if(n.link.link == null)
            n.link = null;
        else
            x = removeLast(n.link);
    }
    return x;
}

從某處調用removeLast()方法時,將startfirst作為參數傳遞。

main()調用removeLast() main()

這是從main方法調用removeLast()方法的示例。

public static void main(String[] args){
    LinkedList ll = new LinkedList();
    /* add the nodes */
    System.out.println("The original LinkedList is");
    /* display the LinkedList */
    System.out.println("The last node is "+ll.removeLast(ll.start));
    System.out.println("After removing the last node, LinkedList is");
    /* display the current LinkedList */
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM