// ListNode* l3 = new ListNode(-101);
// ListNode* start = l3;
// ListNode* prev = l3;
// while(l1 != nullptr || l2 != nullptr)
// {
// int l1val = (l1) ? l1->val : 101;
// int l2val = (l2) ? l2->val : 101;
// if(l1val < l2val)
// {
// l3->val = l1val;
// l1 = l1->next;
// }
// else
// {
// l3->val = l2val;
// l2 = l2->next;
// }
// prev = l3;
// l3->next = new ListNode();
// l3 = l3->next;
// }
// prev->next = nullptr;
// if(l3->val == -101) start = nullptr;
// return start;
ListNode dummy(0);
ListNode* tail = &dummy;
// While both lists have nodes
while (list1 && list2) {
if (list1->val <= list2->val) {
tail->next = list1; // Attach list1 node
list1 = list1->next; // Move list1 forward
} else {
tail->next = list2; // Attach list2 node
list2 = list2->next; // Move list2 forward
}
tail = tail->next; // Move tail forward
}
// Attach remaining nodes (only one of these will be non-null)
tail->next = list1 ? list1 : list2;
// Return merged list, skipping dummy node
return dummy.next;
노드를 새로 만드는게 아니라 기존 노드를 엮는 식으로 하는 풀이가 더 쉬웠다