[LintCode/LeetCode] Merge Two Sorted Lists

424 查看

Problem

Merge two sorted (ascending) linked lists and return it as a new sorted list. The new sorted list should be made by splicing together the nodes of the two lists and sorted in ascending order.

Example

Given 1->3->8->11->15->null, 2->null, return 1->2->3->8->11->15->null.

Note

先考虑l1和l2有无空集,有则返回另一个。
新建链表dummy,指针node将l1和l2较小的放在链表顶端,然后向后遍历,直到l1或l2之一为空。再将非空的链表放在node后面。最后返回dummy.next结束。

Solution

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