-
Notifications
You must be signed in to change notification settings - Fork 0
/
0021.MergeTwoSortedLists.js
117 lines (92 loc) · 2.13 KB
/
0021.MergeTwoSortedLists.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
// Merge two sorted linked lists and return it as a sorted list. The list should be made by splicing together the nodes of the first two lists.
//
// Example 1:
// Input: l1 = [1,2,4], l2 = [1,3,4]
// Output: [1,1,2,3,4,4]
// Example 2:
// Input: l1 = [], l2 = []
// Output: []
// Example 3:
// Input: l1 = [], l2 = [0]
// Output: [0]
// 来源:力扣(LeetCode)
// 链接:https://leetcode-cn.com/problems/merge-two-sorted-lists
// 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
// 🎨 方法一:递归
/**
* @param {ListNode} l1
* @param {ListNode} l2
* @return {ListNode}
*/
var mergeTwoLists = function (l1, l2) {
if (l1 === null) {
return l2
}
if (l2 === null) {
return l1
}
if (l2.val < l1.val) {
l2.next = mergeTwoLists(l1, l2.next)
return l2
}
if (l1.val <= l2.val) {
l1.next = mergeTwoLists(l1.next, l2)
return l1
}
};
// 🎨 方法二:双指针
/**
* @param {ListNode} l1
* @param {ListNode} l2
* @return {ListNode}
*/
var mergeTwoLists = function (l1, l2) {
let head = tail = new ListNode(null);
while (l1 && l2) {
if (l1.val < l2.val) {
tail.next = new ListNode(l1.val);
l1 = l1.next;
} else {
tail.next = new ListNode(l2.val)
l2 = l2.next;
}
tail = tail.next
}
tail.next = l1 || l2
return head.next
};
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
// 🎨 方法二:迭代
/**
* @param {ListNode} l1
* @param {ListNode} l2
* @return {ListNode}
*/
var mergeTwoLists = function (l1, l2) {
let head = tail = new ListNode(null);
while (l1 && l2) {
if (l1.val <= l2.val) {
tail.next = l1;
l1 = l1.next;
} else {
tail.next = l2
l2 = l2.next;
}
tail = tail.next;
}
tail.next = l1 || l2
return head.next
};