【发布时间】:2019-11-11 16:52:43
【问题描述】:
我正在使用 java 中的链表实现堆栈。问题是当下面没有元素时我得到一个 nullPointerException ,例如StackNode.link 不存在。因此,如果我尝试分配 StackNode.link,我会得到异常。
使用 if 语句仅在代码存在时运行代码,我只是在 if 语句中得到异常。我该怎么办?
int pop() {
StackNode temp = top;
// update top
top = belowTop;
belowTop = top.link; // this is where I get the nullPointExcpetion
return temp.data;
}
我希望当 top.link 不存在(例如为 null)时,belowTop 将只是 null。这很好,但如上所述,我得到了例外。
编辑:这是我尝试使用 if 语句的方法
if (top.link != null) {
belowTop = top.link;
}
else {
belowTop = null;
}
【问题讨论】:
-
您得到异常是因为
top为空,而不是因为top.link为空。 -
您说您尝试使用 if 语句。你能展示一下你的尝试吗?
-
@Sweeper 我更新了它:)
标签: java if-statement linked-list nullpointerexception