Merge Two Sorted List

Link: https://leetcode.com/problems/merge-two-sorted-lists/

Constarints:


    The number of nodes in both lists is in the range [0, 50].
    -100 <= Node.val <= 100
    Both l1 and l2 are sorted in non-decreasing order.

Code

class Solution {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode dummy = new ListNode(0);
        ListNode tail = dummy;
        while (l1 != null && l2 != null) {
            if (l1.val <= l2.val) {
                tail.next = l1;
                tail = l1;
                l1 = l1.next;
            } else {
                tail.next = l2;
                tail = l2;
                l2 = l2.next;
            }
        }
        
        if (l1 != null) {
            tail.next = l1;
        } else if (l2 != null) {
            tail.next = l2;
        }
        
        return dummy.next;
    }
}
  • Time: O(m + n), the total number of nodes in two lists.
  • Space: O(1).

Similar problem:

posted on 2021-08-08 16:58  blackraven25  阅读(21)  评论(0)    收藏  举报