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

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

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

视频讲解

代码

  1. /**
  2. * Definition for singly-linked list.
  3. * struct ListNode {
  4. * int val;
  5. * ListNode *next;
  6. * ListNode(int x) : val(x), next(NULL) {}
  7. * };
  8. */
  9. class Solution {
  10. public:
  11. ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
  12. ListNode dummy(0);
  13. ListNode* tail = &dummy;
  14. while (l1 != nullptr && l2 != nullptr)
  15. {
  16. if (l1->val < l2->val)
  17. {
  18. tail->next = new ListNode(l1->val);
  19. tail = tail->next;
  20. l1 = l1->next;
  21. }
  22. else
  23. {
  24. tail->next = new ListNode(l2->val);
  25. tail = tail->next;
  26. l2 = l2->next;
  27. }
  28. }
  29. while (l1 != nullptr)
  30. {
  31. tail->next = new ListNode(l1->val);
  32. tail = tail->next;
  33. l1 = l1->next;
  34. }
  35. while (l2 != nullptr)
  36. {
  37. tail->next = new ListNode(l2->val);
  38. tail = tail->next;
  39. l2 = l2->next;
  40. }
  41. return dummy.next;
  42. }
  43. };
/**
 * 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岁,男生

发表评论

邮箱地址不会被公开。