Skip to content

Commit 4468d02

Browse files
committed
Added merge two sorted list solution
1 parent e42b80c commit 4468d02

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

merge-two-sorted-lists/nhistory.js

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* function ListNode(val, next) {
4+
* this.val = (val===undefined ? 0 : val)
5+
* this.next = (next===undefined ? null : next)
6+
* }
7+
*/
8+
/**
9+
* @param {ListNode} list1
10+
* @param {ListNode} list2
11+
* @return {ListNode}
12+
*/
13+
var mergeTwoLists = function (list1, list2) {
14+
// Make sure both or one of the list is null
15+
if (!list1 && !list2) return null;
16+
if (!list1) return list2;
17+
if (!list2) return list1;
18+
19+
// Create dummy listNode
20+
let dummy = new ListNode(0);
21+
let head = dummy;
22+
// Make head of dummy list by using smaller node from list1 and list2
23+
while (list1 && list2) {
24+
if (list1.val <= list2.val) {
25+
dummy.next = list1;
26+
list1 = list1.next;
27+
} else {
28+
dummy.next = list2;
29+
list2 = list2.next;
30+
}
31+
// After choosing with dummy list, head should be moved next
32+
dummy = dummy.next;
33+
}
34+
// Iterate until both of list head is equal to null
35+
if (list1 !== null) {
36+
dummy.next = list1;
37+
} else {
38+
dummy.next = list2;
39+
}
40+
return head.next;
41+
};
42+
43+
// TC: O(m+n)
44+
// SC: O(1)

0 commit comments

Comments
 (0)