【问题标题】:Merge Two Sorted LinkedLists in Java (using the default LinkedList class, not custom class)在 Java 中合并两个排序的 LinkedList(使用默认的 LinkedList 类,而不是自定义类)
【发布时间】:2021-12-31 00:21:20
【问题描述】:

所以我试图解决合并两个排序列表的 Leetcode 问题(#21),但是我试图使用 Java 中的标准 LinkedList 类来解决这个问题(Leetcode 问题使用自定义的“ListNode”类。这是一个使用 ListNode 类的优雅解决方案:

public class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {

    ListNode head = new ListNode(0);
    ListNode tail = head;
    while(l1 != null && l2 != null) {
        if (l1.val <= l2.val) {
            tail.next = l1;
            l1 = l1.next;
        } else {
            tail.next = l2;
            l2 = l2.next;
        }
        tail = tail.next;
    }
    
    if (l1 != null) {
        tail.next = l1;
    } else if (l2 != null) {
        tail.next = l2;
    }
    
    return head.next;
}

我理解得很好,但是如果我使用 LinkedList 类,我会用什么来代替 l1.vall2.val? LinkedList 似乎没有检索当前节点值的功能,但肯定有办法做到这一点吗?看起来这对于 List 来说是非常标准的。

【问题讨论】:

标签: java list merge linked-list singly-linked-list


【解决方案1】:

LinkedList 类不能让您访问节点,只能访问值。所以从来没有像l1.vall1.next 这样的属性访问。遍历链表实例的一种方法是使用listIterator 方法创建一个迭代器。这个迭代器不会产生节点,而是产生值。

尽管使用LinkedList 类可以接近第一个循环,但不能执行在最后一个if...else 块中完成的步骤:您必须将剩余列表的每个值添加到结果列表中-- 无法将结果列表的尾部与另一个列表链接。

以下是使用迭代器的方法。请注意,我已将while 条件设为逻辑 OR 条件而不是 AND 条件,以便处理上一段中提到的问题:

public LinkedList<Integer> mergeTwoLists(LinkedList<Integer> l1, LinkedList<Integer> l2) {
    LinkedList<Integer> result = new LinkedList<Integer>();
    ListIterator<Integer> iter1 = l1.listIterator();
    ListIterator<Integer> iter2 = l2.listIterator();
    Integer value1 = iter1.hasNext() ? iter1.next() : null;
    Integer value2 = iter2.hasNext() ? iter2.next() : null;
    while (value1 != null || value2 != null) {
        if (value2 == null || value1 != null && value1 <= value2) {
            result.add(value1);
            value1 = iter1.hasNext() ? iter1.next() : null;
        } else {
            result.add(value2);
            value2 = iter2.hasNext() ? iter2.next() : null;
        }
    }
    return result;
}

【讨论】:

  • 这回答了您的问题吗?可以给点意见吗?
猜你喜欢
  • 2016-01-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多