1. 程式人生 > >leetcode:(21) Merge Two Sorted Lists(java)

leetcode:(21) Merge Two Sorted Lists(java)

package LeetCode_LinkedList;

/**
 * 題目:
 *      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 MergeTwoLists_21_1017 {
    public ListNode MergeTwoLists(ListNode l1, ListNode l2) {
        if (l1 == null) {
            return l2;
        }
        if (l2 == null) {
            return l1;
        }

        ListNode temp = new ListNode(-1);
        ListNode result = temp;
        ListNode head1 = l1;
        ListNode head2 = l2;

        while (head1 != null && head2 != null) {
            if (head1.val < head2.val) {
                temp.next = head1;
                head1 = head1.next;
                temp = temp.next;
            }
            else {
                temp.next = head2;
                head2 = head2.next;
                temp = temp.next;
            }
        }
        if (head1 != null) {
            temp.next = head1;
        }

        if (head2 != null) {
            temp.next = head2;
        }
        return result.next;
    }
}