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

时间:2016-09-22 10:28:17

标签: 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-class

中的实例变量

removeLast()成功返回最后一个数字(getLast()确实是这样做的,然后removeLast(Node n)应该实际删除它。但是,那部分不起作用。

1 个答案:

答案 0 :(得分:0)

您未正确将链接列表的最后一个节点设置为n = null。正如@Kevin Esche所说,
nlink设置为null,而不是链接列表的节点。在我的代码中,我引用带有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()

从某处调用start方法时,请传递firstremoveLast()作为参数。

main()

致电removeLast()

以下是从main方法调用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 */ } 方法的示例。

$testAmount
相关问题