---
# System prepended metadata

title: '#21 Merge Two Sorted Lists'
tags: [LeetCode, ' Top100']

---

---
title: "#21 Merge Two Sorted Lists"
tags: LeetCode, Top100
---
#21 Merge Two Sorted Lists
==
題目描述
--
Merge two sorted linked lists and return it as a new **sorted** list. The new list should be made by splicing together the nodes of the first two lists.

Example 1:
--
>Input: l1 = [1,2,4], l2 = [1,3,4]
>Output: [1,1,2,3,4,4]

解題思維
--

簡單的比較法。

Compare
--
```python
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
        result = ListNode()
        head = result
        while l1 is not None or l2 is not None:
            if l1 is None:
                result.next = ListNode(l2.val)
                l2 = l2.next
            elif l2 is None:
                result.next = ListNode(l1.val)
                l1 = l1.next
            elif l1.val > l2.val:
                result.next = ListNode(l2.val)
                l2 = l2.next
            elif l1.val <= l2.val:
                result.next = ListNode(l1.val)
                l1 = l1.next
            result = result.next
        return head.next
```
