---
# System prepended metadata

title: 0021. Merge Two Sorted Lists
tags: [Leetcode, Linked List, Medium]

---

# 0021. Merge Two Sorted Lists
###### tags: `Leetcode` `Medium` `Linked List`
Link: https://leetcode.com/problems/merge-two-sorted-lists/
## 思路
### 思路一
递归
### 思路二
当 l1 和 l2 都不是空链表时，判断 l1 和 l2 哪一个链表的头节点的值更小，将较小值的节点添加到结果里，当一个节点被添加到结果里之后，将对应链表中的节点向后移一位。
## Code
### 思路一
```c=
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
        if(l1 == nullptr){
            return l2;
        }
        else if(l2 == nullptr){
            return l1;
        }
        else if(l1->val < l2->val){
            l1->next = mergeTwoLists(l1->next, l2);
            return l1;
        }
        else{
            l2->next = mergeTwoLists(l1, l2->next);
            return l2;
        }
    }
};
```
### 思路二
```c=
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
        if(l1 == nullptr){
            return l2;
        }
        if(l2 == nullptr){
            return l1;
        }
        ListNode* head = new ListNode;
        ListNode* prev = head;
        while(l1!=nullptr && l2!=nullptr){
            if(l1->val < l2->val){
                prev->next = l1;
                l1 = l1->next;
            }
            else{
                prev->next = l2;
                l2 = l2->next;
            }
            prev = prev->next;
        }
        prev->next = l1 == nullptr?l2:l1;
        return head->next;
    }
};
```
## Result
### 思路一

### 思路二
Runtime: 8 ms, faster than **70.36%** of C++ online submissions for Merge Two Sorted Lists.
Memory Usage: 14.8 MB, less than **73.95%** of C++ online submissions for Merge Two Sorted Lists.