> For the complete documentation index, see [llms.txt](https://jenhsuan.gitbook.io/algorithm/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://jenhsuan.gitbook.io/algorithm/leetcode/21.-merge-two-sorted-lists.md).

# 21. Merge Two Sorted Lists

## 1.問題

![](/files/-LM2SJkNgdtpNsPpuPB_)

## 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;
    }
};
```
