Leetcode问题21合并两个排序的列表

时间:2020-07-21 17:08:58

标签: java algorithm recursion

以下是我建议的答案,它无法返回包含l1和l2的列表。

    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        if (l1 == null) {
            return l2;
        }

        if (l2 == null) {
            return l1;
        }

        if (l1.val <= l2.val) {
            ListNode tmpNode_1 = l1;
            ListNode tmpNode_2 = l1.next;

            tmpNode_2 = mergeTwoLists(tmpNode_2, l2);

            //l1.next = mergeTwoLists(l1.next, l2);
            return tmpNode_1;
        } else {
            ListNode tmpNode_1 = l2;
            ListNode tmpNode_2 = l2.next;

            tmpNode_2 = mergeTwoLists(l1, tmpNode_2);

            // l2.next = mergeTwoLists(l1, l2.next);
            return tmpNode_1;
        }
    }

如果我遵循注释的代码,那么它将起作用。我使用变量的方式有什么问题?

1 个答案:

答案 0 :(得分:0)

我想通过定义这些临时变量,您将与递归算法断开两个链接列表的连接,如果您使用调试器或将其打印出来,将会看到。

class Solution {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        if (l1 == null)
            return l2;
        if (l2 == null)
            return l1;
        if (l1.val < l2.val) {
            l1.next = mergeTwoLists(l1.next, l2);
            return l1;
        } else {
            l2.next = mergeTwoLists(l1, l2.next);
            return l2;
        }
    }
}
public class Solution {
    public static final ListNode mergeTwoLists(final ListNode l1, final ListNode l2) {
        if (l1 == null) {
            return l2;
        }

        if (l2 == null) {
            return l1;
        }

        final ListNode merged;

        if (l1.val < l2.val) {
            merged = l1;
            merged.next = mergeTwoLists(l1.next, l2);

        } else {
            merged = l2;
            merged.next = mergeTwoLists(l1, l2.next);
        }

        return merged;
    }
}

参考文献