Skip to content

Commit e1d2ed6

Browse files
committed
Merge Two Sorted Lists
1 parent 5d12f16 commit e1d2ed6

File tree

2 files changed

+54
-0
lines changed

2 files changed

+54
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,4 +7,5 @@
77
|7|[整数反转](https://leetcode-cn.com/problems/reverse-integer/)|[JavaScript](./algorithms/reverse-integer.js)|Medium|
88
|9|[回文数](https://leetcode-cn.com/problems/palindrome-number/)|[JavaScript](./algorithms/palindrome-number.js)|Easy|
99
|14|[最长公共前缀](https://leetcode-cn.com/problems/longest-common-prefix/)|[JavaScript](./algorithms/longest-common-prefix.js)|Easy|
10+
|21|[合并两个有序链表](https://leetcode-cn.com/problems/merge-two-sorted-lists/)|[JavaScript](./algorithms/merge-two-sorted-lists.js)|Easy|
1011
|189|[轮转数组](https://leetcode-cn.com/problems/rotate-array/)|[JavaScript](./algorithms/rotate-array.js)|Medium|

algorithms/merge-two-sorted-lists.js

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
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+
let dummyHead = new ListNode(0);
15+
let current = dummyHead;
16+
17+
while (list1 && list2) {
18+
if (list1.val < list2.val) {
19+
current.next = list1;
20+
current = current.next;
21+
list1 = list1.next;
22+
} else {
23+
current.next = list2;
24+
current = current.next;
25+
list2 = list2.next;
26+
}
27+
}
28+
29+
if (!list1) {
30+
current.next = list2;
31+
}
32+
33+
if (!list2) {
34+
current.next = list1;
35+
}
36+
37+
return dummyHead.next;
38+
};
39+
40+
41+
// recursion version
42+
var mergeTwoLists = function (list1, list2) {
43+
if (!list1) return list2;
44+
if (!list2) return list1;
45+
46+
if (list1.val < list2.val) {
47+
list1.next = mergeTwoLists(list1.next, list2);
48+
return list1;
49+
} else {
50+
list2.next = mergeTwoLists(list1, list2.next);
51+
return list2;
52+
}
53+
}

0 commit comments

Comments
 (0)