MergeTwoSortedLists2 [source code]

public class MergeTwoSortedLists2 {
static
/******************************************************************************/
public class Solution {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode res = new ListNode(0);
        ListNode tail = res;
        while (l1 != null && l2 != null) {
            if (l2.val <= l1.val) {
                tail.next = l2;
                ListNode newL2 = l2.next;
                l2.next = null;
                tail = l2;
                l2 = newL2;
            } else {
                tail.next = l1;
                ListNode newL1 = l1.next;
                l1.next = null;
                tail = l1;
                l1 = newL1;
            }
        }
        if (l1 == null) tail.next = l2;
        else tail.next = l1;
        return res.next;
    }
}
/******************************************************************************/

    public static void main(String[] args) {
        MergeTwoSortedLists2.Solution tester = new MergeTwoSortedLists2.Solution();
    }
}

这个是使用提前完成思路, 来处理一个 list 跑的比另外一个 list 快的情况, 果然速度就提上去了, 达到了最优解: 15(67);


Problem Description

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.

Difficulty:Easy
Category:Algorithms
Acceptance:38.92%
Contributor: LeetCode
Companies
amazon linkedin apple microsoft
Related Topics
linked list
Similar Questions
Merge k Sorted Lists Merge Sorted Array Sort List Shortest Word Distance II

results matching ""

    No results matching ""