不返回节点的数据



有人能告诉我为什么它没有给出toRemove的值吗??我正在尝试从链接列表中删除最后一个元素。

public E removeLast() throws Exception {
MyNode<E> temp = head;
if (isEmpty()) {
throw new Exception("CANNOT REMOVE FROM EMPTY LIST");
} else {
while (temp.next.next != null) {
temp = temp.next;
}
MyNode<E> toRemove = temp.next;
temp.next = null;
}
return toRemove.data;
}
static class MyNode<E> {
E data;
MyNode<E> next;
MyNode(E data) {
this.data = data;
next = null;
}
}

这是因为您在else范围内声明了toRemove变量,因此无法在if/else之外访问它。

最新更新