题目:
    图片.png

    归并:

    1. #include "iostream"
    2. using namespace std;
    3. struct ListNode {
    4. int value;
    5. ListNode *next;
    6. ListNode(int x) : value(x), next(NULL) {}
    7. };
    8. class Solution {
    9. public:
    10. ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
    11. if (l1 == nullptr)
    12. return l2;
    13. if (l2 == nullptr)
    14. return l1;
    15. if (l1->value < l2->value) {
    16. l1->next = mergeTwoLists(l1->next, l2);
    17. return l1;
    18. } else {
    19. l2->next = mergeTwoLists(l1, l2->next);
    20. return l2;
    21. }
    22. }
    23. };
    24. int main() {
    25. ListNode l1(1);
    26. ListNode l2(5);
    27. ListNode l3(9);
    28. l1.next = &l2;
    29. l2.next = &l3;
    30. ListNode b1(3);
    31. ListNode b2(4);
    32. b1.next = &b2;
    33. Solution s;
    34. s.mergeTwoLists(&l1, &b1);
    35. for (int i = 0; i < 5; ++i) {
    36. cout << l1.value << endl;
    37. l1 = *l1.next;
    38. }
    39. }
    40. //class Solution {
    41. //public:
    42. // ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
    43. //
    44. // }
    45. //};