File tree Expand file tree Collapse file tree 2 files changed +54
-0
lines changed Expand file tree Collapse file tree 2 files changed +54
-0
lines changed Original file line number Diff line number Diff line change 7
7
| 7| [ 整数反转] ( https://leetcode-cn.com/problems/reverse-integer/ ) | [ JavaScript] ( ./algorithms/reverse-integer.js ) | Medium|
8
8
| 9| [ 回文数] ( https://leetcode-cn.com/problems/palindrome-number/ ) | [ JavaScript] ( ./algorithms/palindrome-number.js ) | Easy|
9
9
| 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|
10
11
| 189| [ 轮转数组] ( https://leetcode-cn.com/problems/rotate-array/ ) | [ JavaScript] ( ./algorithms/rotate-array.js ) | Medium|
Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments