---
tags: leetcode
---
# [21. Merge Two Sorted Lists](https://leetcode.com/problems/merge-two-sorted-lists/)
---
# My Solution
## The Key Idea for Solving This Coding Question
## C++ Code
```cpp=
/**
* 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 *list1, ListNode *list2) {
ListNode *dummy = new ListNode(), *it = dummy;
while (list1 != nullptr && list2 != nullptr) {
if (list1->val < list2->val) {
it->next = list1;
list1 = list1->next;
} else {
it->next = list2;
list2 = list2->next;
}
it = it->next;
}
if (list1 != nullptr) {
it->next = list1;
} else if (list2 != nullptr) {
it->next = list2;
}
ListNode *head = dummy->next;
delete dummy;
return head;
}
};
```
## Time Complexity
$O(n1 + n2)$
$n1$ is the number of nodes in `l1`.
$n2$ is the number of nodes in `l2`.
## Space Complexity
$O(1)$
# Miscellaneous
<!--
# Test Cases
```
[1,2,4]
[1,3,4]
```
```
[]
[]
```
```
[]
[0]
```
```
[2,4,6]
[1,3,5,7,9,11]
```
```
[4,5,8,9,12,14]
[8,12,14]
```
```
[1]
[]
```
```
[]
[1,2,4,5,6,7]
```
```
[2,4,6,8,9]
[]
```
```
[1,11,21,31,41,51,61,71,81,91]
[2,22,32]
```
-->