Subject description:
The two ordered lists into a new sorted list and return. The new list is by all nodes in a given mosaic composed of two lists.
Example:
输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
Code:
JavaScript
- Recursive method, for a long time did not do recursive problem, a little rusty, recursion is a commonly used method in the list, in this question the idea of a small bit of a backwards move, and then recursively, successively carried out, the outcome .
/**
* 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
}
if (l1.val < l2.val) {
l1.next = mergeTwoLists(l1.next, l2)
return l1
} else {
l2.next = mergeTwoLists(l1, l2.next)
return l2
}
};