Question: Merge two sorted linked lists and return it as a new sorted list. The new list should be made by splicing together the nodes of the first two lists.
Example: Input: 1->2->4, 1->3->4 Output: 1->1->2->3->4->4
My solution:
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} l1
* @param {ListNode} l2
* @return {ListNode}
*/
var mergeTwoLists = function(l1, l2, l3) {
if (l2 === null) {
l3.next = l1;
return l3;
}
if (l1 === null) {
l3.next = l2;
return l3;
}
if (l2.val < l1.val) {
if (l3) {
l3.next = new ListNode(l2.val)
}
else {
l3 = new ListNode(l2.val)
}
return mergeTwoLists(l1, l2.next, l3)
} else {
if (l3) {
l3.next = new ListNode(l1.val);
}
else {
l3 = new ListNode(l1.val);
}
return mergeTwoLists(l1.next, l2, l3)
}
};
My output is just 1->4 instead of 1->1->2->3->4->4. Can anyone please tell me why?
ListNode- without that, the answer is a pineapple