I am trying to solve a leetcode problem and I think I have figured it out, the problem is that my function returns an Array with the correct Answer and the problem specifies that I must return a NodeList,
I can't figure out how to create a NodeList without reaching to the DOM, or to transform my Array to NodeList.
The problem is:
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 code is :
const listOne = [1, 2, 4];
const listTwo = [1, 3, 4];
function myFunction(l1, l2) {
let lslength;
let newList = [];
if (l1.length >= l2.length) {
lslength = l1.length;
} else {
lslength = l2.length;
}
for (let i = 0; i < lslength; i++) {
if (l1[i] === l2[i]) {
newList.push(l1[i]);
newList.push(l2[i]);
} else if (l1[i] < l2[i]) {
newList.push(l1[i]);
newList.push(l2[i]);
} else if (l1[i] > l2[i]) {
newList.push(l2[i]);
newList.push(l1[i]);
} else if (l1[i]) {
newList.push(l1[i]);
} else {
newList.push(l2[i]);
}
}
return newList;
}
myFunction(listOne, listTwo);
--------EDIT--------- ok so I really didnt understand the problem because its about Linked Lists, now I know, thank you
You don't need to do that.
The test cases are represented like arrays for user simplicity I guess. Though, LinkedList and array are two different data types. Your function is returning an array, which is not a desired output here. The desired output is simply a merged linked list, not a merged array.
Here we'd use a sentinel node to merge two linked lists. This'll get accepted:
/**
* 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) {
var sentinel = {
val: -1,
next: null
};
var curr = sentinel;
while (l1 && l2) {
if (l1.val > l2.val) {
curr.next = l2;
l2 = l2.next;
} else {
curr.next = l1;
l1 = l1.next;
}
curr = curr.next;
}
curr.next = l1 || l2;
return sentinel.next;
};