【问题标题】:Merge Two Linked Lists using Java使用 Java 合并两个链表
【发布时间】: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 循环永远不会终止
  • 看来你把NodeNodeList的概念混在一起了。
  • @SeanPatrickFloyd 当两个列表都为空时,代码返回调用方法。
  • @azurefrog 啊,错过了
  • new_list = new_list.next; 是你的问题。定义一个开始指向new_listnew_head 引用并返回它。

标签: java merge linked-list


【解决方案1】:

您需要保留对列表中第一个节点的引用,但您不需要这样做。在下面的示例中,我还将您的循环分成两个具有预定终止条件的循环,因为这在逻辑上是您想要做的。请注意,我从不复制对现有列表元素的引用,因为您提到您永远不想修改它们。但是,我确实增加了对输入的本地引用:

public static NodeList merge(NodeList l1, NodeList l2) {

    NodeList new_head = new NodeList(0, null);
    NodeList new_node = new_head;

    for(; l1 != null; l1 = l1.next) {
        new_node.next = new NodeList(l1.item, null);
        new_node = new_node.next;
    }

    for(; l2 != null; l2 = l2.next) {
        new_node.next = new NodeList(l2.item, null);
        new_node = new_node.next;
    }
    return new_head.next;
}

如你所见,这有很多代码重复,所以它可以很容易地推广到任意数量的列表:

public static NodeList merge(NodeList... l) {

    NodeList new_head = new NodeList(0, null);
    NodeList new_node = new_head;

    for(NodeList ln in l) {
        for(; ln != null; ln = ln.next) {
            new_node.next = new NodeList(ln.item, null);
            new_node = new_node.next;
        }
    }
    return new_head.next;
}

【讨论】:

  • 啊,谢谢!比我尝试做的要清楚得多。
猜你喜欢
  • 1970-01-01
  • 2021-02-26
  • 1970-01-01
  • 2016-03-30
  • 1970-01-01
  • 1970-01-01
  • 2011-01-21
相关资源
最近更新 更多