我的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 = null
将 n
设置为 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()
方法时,传递 start
或 first
作为参数。
从 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/