Skip to content

Commit 8a0c699

Browse files
committed
merge-two-sorted-lists
1 parent 9e5e459 commit 8a0c699

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
/**
2+
* 21. Merge Two Sorted Lists
3+
* You are given the heads of two sorted linked lists list1 and list2.
4+
* Merge the two lists into one sorted list. The list should be made by splicing together the nodes of the first two lists.
5+
* Return the head of the merged linked list.
6+
*
7+
* https://leetcode.com/problems/merge-two-sorted-lists/description/
8+
*/
9+
10+
/**
11+
* Definition for singly-linked list.
12+
* class ListNode {
13+
* val: number
14+
* next: ListNode | null
15+
* constructor(val?: number, next?: ListNode | null) {
16+
* this.val = (val===undefined ? 0 : val)
17+
* this.next = (next===undefined ? null : next)
18+
* }
19+
* }
20+
*/
21+
22+
// O(n + m) time
23+
// O(1) space
24+
function mergeTwoLists(
25+
list1: ListNode | null,
26+
list2: ListNode | null
27+
): ListNode | null {
28+
if (!list1) return list2;
29+
if (!list2) return list1;
30+
31+
let mergedListNode: ListNode;
32+
const val1 = list1.val;
33+
const val2 = list2.val;
34+
if (val1 > val2) {
35+
mergedListNode = new ListNode(val2);
36+
mergedListNode.next = mergeTwoLists(list1, list2.next);
37+
} else {
38+
mergedListNode = new ListNode(val1);
39+
mergedListNode.next = mergeTwoLists(list1.next, list2);
40+
}
41+
42+
return mergedListNode;
43+
}
44+
45+
class ListNode {
46+
val: number;
47+
next: ListNode | null;
48+
constructor(val?: number, next?: ListNode | null) {
49+
this.val = val === undefined ? 0 : val;
50+
this.next = next === undefined ? null : next;
51+
}
52+
}

0 commit comments

Comments
 (0)