1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| class Solution { public: ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) { ListNode* resList = new ListNode(); ListNode* node = resList; ListNode* node1 = list1; ListNode* node2 = list2; while (node1 != nullptr || node2 != nullptr) { if (node2 == nullptr || node1 != nullptr && node1->val <= node2->val) { node->next = new ListNode(node1->val); node1 = node1->next; node = node->next; } else { node->next = new ListNode(node2->val); node2 = node2->next; node = node->next; } } if (resList == nullptr) { return nullptr; } else { node = resList->next; delete resList; return node; } } };
|