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

难度:easy

题目:
合并两个列表并返回新的列表。新列表由两个列表的片断组成。

思路:直接遍历合并

Runtime: 6 ms, faster than 100.00% of Java online submissions for Merge Two Sorted Lists.
Memory Usage: 30.5 MB, less than 44.63% of Java online submissions for Merge Two Sorted Lists.

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode head = new ListNode(0), ptr = head;
        while (l1 != null && l2 != null) {
            if (l1.val > l2.val) {
                ptr.next = l2;
                ptr = l2;
                l2 = l2.next;
            } else {
                ptr.next = l1;
                ptr = l1;
                l1 = l1.next;
            }
        }
        ptr.next = (l1 != null) ? l1 : l2;
        
        return head.next;
    }
}

linm
1 声望4 粉丝

〜〜〜学习始于模仿,成长得于总结〜〜〜