【发布时间】:2020-10-12 09:09:34
【问题描述】:
我们的任务是完成函数swapkthnode()
这个特定的代码有什么问题?它适用于对问题本身给出的示例测试用例/示例进行自定义检查。我已经在在线 IDE jdoodle 中测试了示例案例,它在那里运行良好。 但是在 gfg IDE 中编译和测试时,它在下面的注释行给出了 NullPointerException(相同逻辑的 c++ 中的分段错误);
Node swapkthnode(Node head, int num, int K)
{
// your code here
if(num == 1 || 2*K - 1 == num) return head;
if(K == 1 || K == num)
{
Node start = head;
Node end = head;
while(end.next.next != null) end = end.next;
head = end.next;
head.next = start.next;
end.next = start;
start.next = null;
return head;
}
else
{
Node lastK = head;
Node firstK = head;
for(int i=K-2; i>0; i--) firstK = firstK.next;
for(int i=num-K-1; i>0; i--) lastK = lastK.next;
Node tmp1 = firstK.next;
Node tmp2 = lastK.next.next;
firstK.next = lastK.next;
lastK.next = tmp1;
firstK.next.next = tmp1.next; // <<<===== May be This is the faulty line according to exception thrown, but I am unable to see any fault in there.
tmp1.next = tmp2; // beacause if firstK.next is going to be null in any example,
return head; // then it will be already handled by above 2nd if condition.
}
}
堆栈跟踪:stackTrace
【问题讨论】:
-
如果您怀疑该行,为什么不检查
firstK.next是否为空?您能否提供指示特定代码行的堆栈跟踪? -
@AlexRudenko 看看stackTrace,我已经上传了。 swapkthnode 在类“GFG”中。对于问题设计者提供的进一步代码(驱动程序代码-除此功能之外),您可以访问我给出的链接,但我认为驱动程序代码与此无关。
-
无法用您的可用代码重现此问题。该问题可能与链表的错误构建有关。建议你抓NPE,打印链表的内容,找出原因。
-
我猜你是对的,结束问题! @AlexRudenko
标签: java pointers nullpointerexception segmentation-fault singly-linked-list