[英]Concatenating 2 Linked Lists - Java
I am having some trouble with NullPointExceptions when attempting to concatenate two linked lists in JAVA. 尝试在JAVA中连接两个链接列表时,NullPointExceptions出现了一些麻烦。
The code for main to test it is: 用于测试它的主要代码是:
d1 = new MyDeque ();
d2 = new MyDeque ();
d2.pushLeft (11);
d1.concat (d2);
While the code for the concat function is: 虽然concat函数的代码是:
public void concat (MyDeque that) {
if (!that.isEmpty())
{
this.last.next = that.first;
this.N += that.N;
that.first = null;
that.last = null;
that.N = 0;
}
}
The portion that I don't understand is that it flags NullPointerException. 我不了解的部分是它标记了NullPointerException。 "d2" or that isn't empty, and "d1" is, which sort of makes me understand that there would be a null value, "d1", pointing to the first value in "d2", aka 11, with this.last.next = that.first. “ d2”或不为空,而“ d1”是,让我理解到会有一个空值“ d1”指向“ d2”中的第一个值,也就是11。 last.next = that.first。 Should I make another statement that handles this differently if "d1" is empty as well? 如果“ d1”也为空,我是否应该做出另一条处理不同的语句?
Although I don't have your entire node class, I see 2 possible places for you to have a NullPointerException. 尽管我没有整个节点类,但我看到两个可能的地方包含NullPointerException。
(1) (1)
if (!that.isEmpty())
You should verify (that != null)
. 您应该验证(that != null)
。 Your code will throw a NullPointerException if that
is null. 如果为null that
则您的代码将引发NullPointerException。
(2) (2)
this.last.next = that.first;
Your code will throw a NullPointerException if this.last
is null. 如果this.last
为null,则您的代码将引发NullPointerException。 Make sure it isn't, or check beforehand. 确保不是,否则请事先检查。
Make sure you are checking that the next node is not empty 确保您正在检查下一个节点不为空
while (list.next != null)
Is the standard approach, it may be slightly different if you are using a custom end token 这是标准方法,如果您使用自定义结束令牌,则可能会略有不同
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.