21. Merge Two Sorted Lists | Java最短代码实现

原题链接: 21. Merge Two Sorted Lists

【思路】

模仿归并排序,对两个已经有序的链表进行排序。创建一个节点dummyHead,用temp指向它,并用temp遍历,temp总是志向 l1 和 l2 中较小的一个节点:

    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode dummyHead = new ListNode(0);
        ListNode temp = dummyHead;
        while (l1 != null && l2 != null) {
            if (l1.val < l2.val) {
                temp.next = l1;
                l1 = l1.next;
            } else {
                temp.next = l2;
                l2 = l2.next;
            }
            temp = temp.next;
        }
        if (l1 != null) temp.next = l1;
        if (l2 != null) temp.next = l2;
        return dummyHead.next;
    }

208 / 208 test cases passed. Runtime: 1 ms  Your runtime beats 11.81% of javasubmissions.

【补充】

用递归实现,

    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        if (l1 == null) return l2;  //终止条件
        if (l2 == null) return l1;
        ListNode ret;
        if (l1.val < l2.val) {  //每次递归连接下一个节点的条件
            ret = l1;
            ret.next = mergeTwoLists(l1.next, l2);
        } else {
            ret = l2;
            ret.next = mergeTwoLists(l1, l2.next);
        }
        return ret;
    }


你可能感兴趣的:(21. Merge Two Sorted Lists | Java最短代码实现)