跳转至

21. Merge Two Sorted Lists

Leetcode Linked List

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

Example:

Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4

分析

合并排过序的链表。采用两个指针分别指向两个链表,依次比较这两个指针所指向的元素。将较小的元素放在最终链表中,并向后移动较小元素对应的链表,直到遍历到链表末尾。 最终,截取剩余的节点到最终链表末尾。

采用循环遍历的方法:

public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
    ListNode head = new ListNode(0), cur = head;
    while ((l1!=null) && (l2!= null)) {
        if (l1.val < l2.val) {
            cur.next = l1;
            l1 = l1.next;
        } else {
            cur.next = l2;
            l2 = l2.next;
        }
        pos = pos.next;
    }
    cur.next = (l1 == null) ? l2 : l1;
    return head.next;
}

采用递归的方法

public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
    // base case
    if (l1 == null) return l2;
    if (l2 == null) return l1;
    // current node
    ListNode res;
    if (l1.val < l2.val) {
        res = l1;
        l1 = l1.next;
    } else {
        res = l2;
        l2 = l2.next;
    }
    // current node + nodes continued
    res.next = mergeTwoLists(l1, l2);
    return res;
}