gpt4 book ai didi

java - 在 Java 中通过从每个单链表获取 2 个元素来合并两个单链表

转载 作者:太空宇宙 更新时间:2023-11-04 13:39:45 25 4
gpt4 key购买 nike

我需要输出 SLL(单链表),它是通过这种方式合并另外两个列表的结果:

列表1 = 5 6 7

列表2 = 1 2 3 4

输出列表 = 5 6 1 2 7 3 4

列表1 = 5 6 0 2 3 3

列表2 = 2 4 5 2

输出列表 = 5 6 2 4 0 2 5 2 3 3

要么我在分配节点的后继者时遇到 NullPointerException,要么我陷入 while 循环。你能帮我吗?

这是我到目前为止所做的事情:

public SLL < E > specialJoin(SLL < E > list1, SLL < E > list2) {
SLL result = new SLL();
SLLNode temp1 = list1.first;
SLLNode temp2 = list2.first;

while (temp1 != null && temp2 != null) { // if there are still nodes in the lists
result.insertLast(temp1.element); // first insert the first element
if (temp1.succ != null) { // then check if there is still something
result.insertLast(temp1.succ.element); // and add the second element
temp1 = temp1.succ.succ; // at the end the next node will be the node after the succ of the temporary element
}

rezultat.insertLast(temp2.element); // the same for the seconod list
if (temp2.succ != null) {
result.insertLast(temp2.succ.element);
temp2 = temp2.succ.succ;
}
}
// if there are still nodes in on of the lists we are apending them
while (temp1 != null) {
result.insertLast(temp1.element);
temp1 = temp1.succ;
}
while (temp2 != null) {
result.insertLast(temp2.element);
temp2 = temp2.succ;
}
return result;
}

最佳答案

当到达任一列表的末尾时,您在第一个 while 循环中缺少一件事:

    while(temp1 != null && temp2 != null){ // if there are still nodes in the lists
result.insertLast(temp1.element); // first insert the first element
if(temp1.succ != null){ // then check if there is still something
result.insertLast(temp1.succ.element); // and add the second element
temp1= temp1.succ.succ; // at the end the next node will be the node after the succ of the temporary element
} else { // added
temp1= temp1.succ; // which is the same as temp1=null;
}

rezultat.insertLast(temp2.element); // the same for the seconod list
if(temp2.succ != null){
result.insertLast(temp2.succ.element);
temp2 = temp2.succ.succ;
} else { // added
temp2 = temp2.succ; // which is the same as temp2=null;
}
}

这些添加的 else 子句负责处理其中一个列表中只剩下一个节点的情况。没有它们,您可能会陷入无限循环。

关于java - 在 Java 中通过从每个单链表获取 2 个元素来合并两个单链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31339266/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com