代码

/**
 * 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* head = new ListNode(-1);
        ListNode* p = head;
        while (l1 && l2)
        {
            if (l1->val < l2->val)
            {
                p->next = l1;
                l1 = l1->next;
            }
            else
            {
                p->next = l2;
                l2 = l2->next;
            }
            p = p->next;
        }
        if (l1) p->next = l1;
        if (l2) p->next = l2;
        return head->next;
    }
};

21. Merge Two Sorted Lists

相关文章:

  • 2021-06-03
  • 2021-08-18
  • 2022-01-14
  • 2021-05-26
  • 2021-11-15
  • 2021-10-01
猜你喜欢
  • 2022-02-02
相关资源
相似解决方案