[LeetCode] 21. 合并两个有序链表(Merge Two Sorted Lists)

本文已收录于 LeetCode刷题 系列,共计 28 篇,本篇是第 4 篇

本文已收录到:LeetCode刷题 专题

视频讲解

代码

/**
 * 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 dummy(0);
        ListNode* tail = &dummy;

        while (l1 != nullptr && l2 != nullptr)
        {
            if (l1->val < l2->val)
            {
                tail->next = new ListNode(l1->val);
                tail = tail->next;
                l1 = l1->next;
            }
            else
            {
                tail->next = new ListNode(l2->val);
                tail = tail->next;
                l2 = l2->next;
            }
        }
        while (l1 != nullptr)
        {
            tail->next = new ListNode(l1->val);
            tail = tail->next;
            l1 = l1->next;
        }
        while (l2 != nullptr)
        {
            tail->next = new ListNode(l2->val);
            tail = tail->next;
            l2 = l2->next;
        }
        return dummy.next;
    }
};

 

作者: 高志远

高志远,24岁,男生

发表评论

邮箱地址不会被公开。