---
# System prepended metadata

title: 21.Merge Two Sorted Lists

---

21.Merge Two Sorted Lists
===

### Description
(easy)

You are given the heads of two sorted linked lists list1 and list2.

Merge the two lists in a one sorted list. The list should be made by splicing together the nodes of the first two lists.

Return the head of the merged linked list.

#### example 1:
![](https://i.imgur.com/M3alGhC.jpg)

    Input: list1 = [1,2,4], list2 = [1,3,4]
    Output: [1,1,2,3,4,4]

#### example 2:
    Input: list1 = [], list2 = []
    Output: []
#### example 3:
    Input: list1 = [], list2 = [0]
    Output: [0]
#### Constraints:
- The number of nodes in both lists is in the range [0, 50].
- -100 <= Node.val <= 100
- Both list1 and list2 are sorted in non-decreasing order.

### 想法

### 程式碼
#### c:
```c=
struct ListNode* mergeTwoLists(struct ListNode* L1, struct ListNode* L2){
    struct ListNode *head;
    struct ListNode **ptr = &head;
    for (; L1 && L2; ptr = &(*ptr)->next) {
        if (L1->val < L2->val) {
            *ptr = L1;
            L1 = L1->next;
        } else {
            *ptr = L2;
            L2 = L2->next;
        }
    }
    *ptr = (struct ListNode *)((uintptr_t) L1 | (uintptr_t) L2);
    return head;
}
```

#### python:
