# LeetCode - 0021. Merge Two Sorted Lists ### 題目網址:https://leetcode.com/problems/merge-two-sorted-lists/ ###### tags: `LeetCode` `Easy` `連結串列(Linked List)` ```cpp= /* -LeetCode format- Problem: 21. Merge Two Sorted Lists Difficulty: Easy by Inversionpeter */ /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { if (!l1) return l2; if (!l2) return l1; ListNode *head, *now; if (l1->val < l2->val) head = l1, l1 = l1->next; else head = l2, l2 = l2->next; now = head; while (l1 || l2) { if (!l1) { now->next = l2; break; } else if (!l2) { now->next = l1; break; } else if (l1->val < l2->val) { now = now->next = l1, l1 = l1->next; } else { now = now->next = l2, l2 = l2->next; } } return head; } }; ```