-
Notifications
You must be signed in to change notification settings - Fork 0
/
21.merge-two-sorted-lists.js
84 lines (56 loc) · 1.52 KB
/
21.merge-two-sorted-lists.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
/*
* @lc app=leetcode id=21 lang=javascript
*
* [21] Merge Two Sorted Lists
*/
// @lc code=start
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} list1
* @param {ListNode} list2
* @return {ListNode}
*/
// 1 3 5
// 2 4 6
// list1.next = list2 // 1->2
// list2 and list1.next(3) // 1->2->3
var mergeTwoLists = function(list1, list2) {
// recursion
// If list1.val < list2.val, recursive(list1.next, list2) and vice versa. Also return list1 or list2
if(!list1 || !list2){
return list1 ? list1:list2
}
if(list1.val<list2.val){
list1.next = mergeTwoLists(list1.next, list2);
return list1;
}
list2.next = mergeTwoLists(list1, list2.next);
return list2;
};
function ListNode(val, next) {
this.val = val === undefined ? 0 : val;
this.next = next === undefined ? null : next;
}
let l1 = new ListNode(1);
l1.next = new ListNode(2);
l1.next.next = new ListNode(4);
let l2 = new ListNode(1);
l2.next = new ListNode(3);
l2.next.next = new ListNode(4);
mergeTwoLists(l1, l2)
// @lc code=end
/*
if(!list1 || !list2) return list1 ? list1:list2
if(list1.val<list2.val){
list1.next = mergeTwoLists(list1.next, list2);
return list1;
}
list2.next = mergeTwoLists(list1, list2.next)
return list2
*/