Complete the code to create a new node with the given value.
ListNode* newNode = new ListNode([1]);The constructor of ListNode takes the value to store in the node. We pass val to create a node with that value.
Complete the code to move the pointer to the next node in the list.
current = current->[1];prev which is for doubly linked listsIn a singly linked list, each node points to the next node using the next pointer.
Fix the error in the condition to check if the first list is empty.
if (list1 == [1]) return list2;
In modern C++, nullptr is the preferred way to check for a null pointer instead of NULL or 0.
Fill both blanks to correctly compare node values and assign the next pointer.
if (list1->val [1] list2->val) { merged->next = list1; list1 = list1->[2]; } else { merged->next = list2; list2 = list2->next; }
We compare if list1->val is less than list2->val. If yes, we link merged->next to list1 and move list1 forward using next.
Fill all three blanks to complete the merge function that returns the merged list.
ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {
if (list1 == [1]) return list2;
if (list2 == [2]) return list1;
if (list1->val < list2->val) {
list1->next = mergeTwoLists(list1->next, list2);
return [3];
} else {
list2->next = mergeTwoLists(list1, list2->next);
return list2;
}
}We check if either list is empty using nullptr. Then we recursively merge and return the smaller node. When list1->val is smaller, we return list1 after linking its next.
