Merge two ordered lists into a new ordered list and return. The new linked list is composed of all nodes of two given linked lists.
Example:
Input: 1 - > 2 - > 4, 1 - > 3 - > 4 Output: 1 - > 1 - > 2 - > 3 - > 4 - > 4
/** * Definition for singly-linked list. * function ListNode(val) { * this.val = val; * this.next = null; * } */ /** * @param {ListNode} l1 * @param {ListNode} l2 * @return {ListNode} */ var mergeTwoLists = function(l1, l2) { if ( l1 == null) return l2; if ( l2 == null) return l1; console.log(l1 ,l1.val) if( l1.val < l2.val){ l1.next = mergeTwoLists(l1.next,l2); return l1 }else { l2.next = mergeTwoLists(l1,l2.next); return l2 } };
Before this, I wrote a version like this
/** * Definition for singly-linked list. * function ListNode(val) { * this.val = val; * this.next = null; * } */ /** * @param {ListNode} l1 * @param {ListNode} l2 * @return {ListNode} */ var mergeTwoLists = function(l1, l2) { let newA = [],newB = []; if (l1.length >= l2.length) { newA = l1; }else { newA = l2; } newA.map((d,i)=>{ if ( l1[i] == null) return newB.push(l2[i]); if ( l2[i] == null) return newB.push(l1[i]); if (l1[i] >= l2[i]){ newB.push(l2[i],l1[i]); }else { newB.push(l1[i],l2[i]); } }) return newB };
The result shows that map is not a function, but it is normal in the console.
There is no way. I printed the input parameter separately and found that the input parameter is a chain structure.
It's not array, so it's always reported an error.
These times, I feel that leetcode's support for javascript is not very good, or it may be because it faces too many languages, and I have been engaged in the development of js, so I don't know some unused data types, but use the usual ideas to complete, there are many inexplicable errors.
However, through some reporting mistakes, I found my own narrow knowledge and limitations of thinking. Let's continue to work hard.
ps: sometimes when the idea encounters a bottleneck, search. The search results are basically java or python. Hope to meet more js gods to share.