---
title: 'LeetCode 21. Merge Two Sorted Lists'
disqus: hackmd
---
# LeetCode 21. Merge Two Sorted Lists
## Description
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
Input: list1 = [1,2,4], list2 = [1,3,4]
Output: [1,1,2,3,4,4]
## 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.
## Answer
此題可藉由取餘數將每個數字都抓出,然後再做前後比對,而INT最大就是10位數。
```Cin=
struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2){
if(l1 == NULL){return l2;}
if(l2 == NULL){return l1;}
struct ListNode *ans = NULL, *opr = NULL;
if(l1->val > l2->val){
opr = l2;
l2 = l2->next;
}
else{
opr = l1;
l1 = l1->next;
}
ans = opr;
while(l1 && l2){
if(l1->val > l2->val){
opr->next = l2;
l2 = l2->next;
}
else{
opr->next = l1;
l1 = l1->next;
}
opr = opr->next;
}
if(l1){opr->next = l1;}
if(l2){opr->next = l2;}
return ans;
}
```
## Link
https://leetcode.com/problems/merge-two-sorted-lists/
###### tags: `Leetcode`