# 21. Merge Two Sorted Lists

## 1.問題

![](https://901207480-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LGKoChvN9am4__HCIRK%2F-LM2S3-2fHbaDxF4wiq1%2F-LM2SJkNgdtpNsPpuPB_%2F%E8%9E%A2%E5%B9%95%E5%BF%AB%E7%85%A7%202018-09-10%20%E4%B8%8B%E5%8D%888.29.00.png?alt=media\&token=d220343a-7206-4459-9ada-e3513cfb84a6)

## 2.想法

* 提問
* function header, parameter
* test input
* 說明想法
  * 一面走訪linked list, 一面比對數值
* 測試計算複雜度: O(n) , n是長的字串的長度

## **3.程式碼**

```
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
        ListNode* first = new ListNode(0);
        ListNode* head = first;
        while (l1 && l2) {
            if (l1->val <= l2->val) {
                head->next = new ListNode(l1->val);
                l1 = l1->next;
            } else {
                head->next = new ListNode(l2->val);
                l2 = l2->next;
            }
            head = head->next;
        }
        
        while (l1) {
            head->next = new ListNode(l1->val);
            head = head->next;
            l1 = l1->next;
        }
        
        while (l2) {
            head->next = new ListNode(l2->val);
            head = head->next;
            l2 = l2->next;
        } 
        
        return first->next;
    }
};
```
