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

标签 java recursion linked-list

我的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 方法调用 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 */
}

关于java - 为什么不能将 LinkedList 的最后一个节点设置为 null?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39636593/

相关文章:

java - 传递不正确的媒体类型时无法捕获 WebApplicationException

java - 计算字母频率错误

c - C 和汇编器中的阶乘 - 递归

algorithm - 最短根到叶路径

c++ - 指向单链表中内存地址的指针,其中没有变量表示每个元素

c - 链接列表和结构

java - 为什么我只会在部署了相同耳朵的三个 Web 服务器之一上收到 ConcurrentModificationException

java - 在 Java 中实现素数查找算法的最佳方法是什么?我们如何创建库类然后在 Java 中使用?

java - 无法下载 Spring Boot 2.1.7.RELEASE

python - 使用 yield 递归