Merge Two Sorted Lists
You are given the heads of two sorted linked lists list1 and list2.
Merge the two lists in a one sorted list. The list should be made by splicing together the nodes of the first two lists.
Return the head of the merged linked list.
Input: list1 = [1,2,4], list2 = [1,3,4]
Output: [1,1,2,3,4,4]
const mergeTwoLists = function (list1, list2) { if (!list1) return list2; if (!list2) return list1; const res = new ListNode(); let cur = res; while (list1 && list2) { const v1 = list1.val; const v2 = list2.val; if (v1 <= v2) { cur.next = list1; list1 = list1.next; } else if (v1 > v2) { cur.next = list2; list2 = list2.next; } cur = cur.next; } cur.next = list1 || list2; return res.next; };
// Recursive const mergeTwoLists = function (l1, l2) { if (!l1) return l2; if (!l2) return l1; if (l1.val > l2.val) { l2.next = mergeTwoLists(l1, l2.next); return l2; } else { l1.next = mergeTwoLists(l1.next, l2); return l1; } };