【发布时间】:2016-10-31 03:12:11
【问题描述】:
试图弄清楚我的代码中缺少什么应该将链表 2 合并到链表 1 的末尾。现在它只是获取第二个列表中的最后一个元素并返回它。
我尝试使用的逻辑是遍历第一个列表 (L1) 并将这些元素一个接一个地添加到 new_list 中,然后在我到达 L1 的末尾后对第二个列表 (L2) 执行相同的操作.我也在尽量避免修改 L1 或 L2,这就是我创建 new_list 的原因。
任何帮助将不胜感激。
public NodeList(int item, NodeList next) {
this.item = item;
this.next = next;
}
public static NodeList merge(NodeList l1, NodeList l2) {
NodeList new_list = new NodeList(l1.item, l1.next);
NodeList new_list2 = new NodeList(l2.item, l2.next);
while (true) {
if (new_list.next == null) {
if (new_list2.next == null) {
return new_list;
}
else {
new_list.next = new NodeList(new_list2.next.item, new_list2.next.next);
new_list2 = new_list2.next;
}
}
else {
new_list.next = new NodeList(new_list.next.item, new_list.next.next);
new_list = new_list.next;
}
}
}
【问题讨论】:
-
你的 while 循环永远不会终止
-
看来你把
Node和NodeList的概念混在一起了。 -
@SeanPatrickFloyd 当两个列表都为空时,代码返回调用方法。
-
@azurefrog 啊,错过了
-
new_list = new_list.next;是你的问题。定义一个开始指向new_list的new_head引用并返回它。
标签: java merge linked-list