为什么链接列表合并函数在Java中不起作用?
问题出现在“while(m.next!=null)”处的合并函数中。它抛出一个“NullPointerException”为什么链接列表合并函数在Java中不起作用?,java,Java,问题出现在“while(m.next!=null)”处的合并函数中。它抛出一个“NullPointerException” 我在代码中添加了注释,以向您解释发生了什么 node ptr1; //ptr1 is null here node ptr2; void merge() { node m=ptr1; //you are assigning null to m while(m.next!=null) //you are accessing the "next" prope
我在代码中添加了注释,以向您解释发生了什么
node ptr1; //ptr1 is null here
node ptr2;
void merge()
{
node m=ptr1; //you are assigning null to m
while(m.next!=null) //you are accessing the "next" property of a null object
m=m.next;
m.next=ptr2;
}
必须实例化对象,否则它们将为null。初始化的
ptr1
在哪里?m为null,可能意味着ptr1也为null。
node ptr1; //ptr1 is null here
node ptr2;
void merge()
{
node m=ptr1; //you are assigning null to m
while(m.next!=null) //you are accessing the "next" property of a null object
m=m.next;
m.next=ptr2;
}