简体   繁体   English

为什么我不能将LinkedList的最后一个节点设置为null?

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

My removeLast method are meant to return the last element in the linked list, and then return it. 我的removeLast方法用于返回链表中的最后一个元素,然后返回它。 This is what I have so far: 这是我到目前为止:

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 = an instance variabel in the LinkedList-class first = LinkedList类中的实例变量

removeLast() successfully returns the last number (well getLast() does it really, and then removeLast(Node n) is supposed to actually remove it. However, that part doesn't work. removeLast()成功返回最后一个数字(getLast()实际上是这样做的,然后removeLast(Node n)应该实际删除它。但是,该部分不起作用。

You are not correctly setting the last node of the linked list as null . 您没有正确地将链接列表的最后一个节点设置为null As @Kevin Esche said, 正如@Kevin Esche所说,
n = null sets n as null and not the node of the linked list. n = nulln设置为null,而不是链表的节点。 In my code, I refer to the node with the link reference and set it to null . 在我的代码中,我引用带有link引用的节点并将其设置为null

This should work. 这应该工作。

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;
}

While calling the removeLast() method from somewhere, pass start or first as the argument. 从某处调用removeLast()方法时,将startfirst作为参数传递。

Calling removeLast() from main() main()调用removeLast() main()

Here's an example of calling the removeLast() method from the main method. 这是从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