---
# System prepended metadata

title: 21. Merge Two Sorted Lists

---

# 21. Merge Two Sorted Lists
https://leetcode.com/problems/merge-two-sorted-lists/

### 我的想法
```python
class Solution:
    def mergeTwoLists(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
        curr1 = l1
        curr2 = l2
        temp = ListNode()
        while (curr1 and curr2) and(curr1.next and curr2.next):
            if curr1.val >= curr2.val:
                temp.next = curr1
                curr1 = curr1.next
            else:
                temp.next = curr2
                curr2 = curr2.next
                
        return temp.next
```
思考的想法大概是 用一個新的ListNode，去串接答案
由curr1指向l1上的Node,curr2指向l2上的Node,
比較誰的值比較小；新的ListNode就接上(curr1,curr2)指到較小的那個Node

### 網友解法
```python
class Solution:
    def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:

        head = sort_list = ListNode(0)
        
        while(l1 and l2):
            if (l1.val < l2.val):
                sort_list.next = l1
                l1 = l1.next
                sort_list = sort_list.next
                
            elif (l1.val >= l2.val):
                sort_list.next = l2
                l2 = l2.next
                sort_list = sort_list.next

        sort_list.next = l1 or l2
        return head.next
```

搞不懂為何sort_list在操作，最後是return head.next 
在
```
head = sort_list = ListNode(0)
```
這行時，head , sort_list 被賦予同一個位子嗎?
所以sort_list後面做的事同時會接到head後面嗎? 目前只能這樣理解，但不曉得正確的觀念。

另外還有sort_list.next = l1 or l2這行



#### 亂想的過程
一開始的想法是有點混亂
第一個 if - elif 是在排除當其中是空的LinkedList時的狀況
第二個 if - elif 是看要從哪一串開始當Head
然後curr1：指向head後面的的node，curr2：指向另一條node
* 當curr1指到的這個node的下一個值，大於curr2指到的值時
* 代表現在curr1.next要指到curr2目前這個node
* 原本curr1後面的LinkedList 要讓curr2指標指過去
但這樣好想有點想得太複雜了
```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: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
        if l1 == None :
            return l2
        elif l2 == None:
            return l1
        if l1.val <=l2.val:
            head = l1
            curr1 = head
            curr2 = l2
        else :
            head = l2
            curr2 = l1
            curr1 = head
        while (curr1 and curr2) and(curr1.next and curr2.next):
            if curr1.next.val > curr2.val:
                #先例用一個暫時的Node把curr1.next後面那串接起來
                temp = ListNode()
                temp.next = curr1.next
                curr1.next = curr2 #curr1.next接到curr2
                curr1 = curr1.next #curr1往下移一格
                curr2 = temp.next #curr2指到原本curr1.next那串
            else:
                curr1=curr1.next
                
        return head 
        
```