【leetCode】21. Merge Two Sorted Lists合并两个有序数组

描述:

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 class MergeTwoSortedLists {
    public static class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
        }
    }

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

    public static void main(String[] args) {
        ListNode l1One = new ListNode(1);
        ListNode l1Two = new ListNode(2);
        ListNode l1Four = new ListNode(4);
        l1One.next = l1Two;
        l1Two.next = l1Four;
        ListNode l2One = new ListNode(1);
        ListNode l2Three = new ListNode(3);
        ListNode l2Four = new ListNode(4);
        l2One.next = l2Three;
        l2Three.next = l2Four;
        ListNode result = new MergeTwoSortedLists().mergeTwoLists(l1One, l2One);
        while (result != null) {
            System.out.println(result.val);
            result = result.next;
        }
    }
}

 

你可能感兴趣的:(算法,leetCode)