---
# System prepended metadata

title: 21.Merge Two Sorted Lists
tags: [Leetcode, '2021']

---

---
title: 21.Merge Two Sorted Lists
tags: Leetcode,2021
---
# 【LeetCode】 21. Merge Two Sorted Lists
## Description
>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.

>請合併兩個已經排序過的linked lists並回傳新的list。
新的list應該要由前面兩個list所有的節點構成。
```
Example:
Example:

Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4
```
## Solution

## Code
```
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     public int val;
 *     public ListNode next;
 *     public ListNode(int val=0, ListNode next=null) {
 *         this.val = val;
 *         this.next = next;
 *     }
 * }
 */
public class Solution {
    //首先先宣告一個ListNode head 為 0
    
    public ListNode MergeTwoLists(ListNode l1, ListNode l2) {
        if (l1 == null)
                return l2;
            if (l2 == null)
                return l1;

            var tmp1 = l1.next;
            var tmp2 = l2.next;
            if (l2.val > l1.val)
            {
                l1.next = MergeTwoLists(tmp1, l2);               

                return l1; 
            }

            l2.next = MergeTwoLists(l1, tmp2);           
            return l2;                       
    }
}
```