File tree Expand file tree Collapse file tree 1 file changed +68
-0
lines changed Expand file tree Collapse file tree 1 file changed +68
-0
lines changed Original file line number Diff line number Diff line change
1
+ /*
2
+ * @lc app=leetcode.cn id=21 lang=javascript
3
+ *
4
+ * [21] 合并两个有序链表
5
+ */
6
+
7
+ // @lc code=start
8
+ /**
9
+ * Definition for singly-linked list.
10
+ * function ListNode(val) {
11
+ * this.val = val;
12
+ * this.next = null;
13
+ * }
14
+ */
15
+ /**
16
+ * @param {ListNode } l1
17
+ * @param {ListNode } l2
18
+ * @return {ListNode }
19
+ */
20
+ var mergeTwoLists = function ( l1 , l2 ) {
21
+ let result = null ;
22
+ let current = null ;
23
+
24
+ while ( l1 && l2 ) {
25
+ let next = l1 . val <= l2 . val ? l1 : l2 ;
26
+ if ( ! result ) {
27
+ result = next ;
28
+ current = next ;
29
+ } else {
30
+ current . next = next ;
31
+ current = next ;
32
+ }
33
+
34
+ if ( l1 === next ) {
35
+ l1 = l1 . next ;
36
+ } else {
37
+ l2 = l2 . next ;
38
+ }
39
+ }
40
+
41
+ while ( l1 ) {
42
+ if ( ! result ) {
43
+ result = l1 ;
44
+ current = l1 ;
45
+ } else {
46
+ current . next = l1 ;
47
+ current = l1 ;
48
+ }
49
+
50
+ l1 = l1 . next ;
51
+ }
52
+
53
+ while ( l2 ) {
54
+ if ( ! result ) {
55
+ result = l2 ;
56
+ current = l2 ;
57
+ } else {
58
+ current . next = l2 ;
59
+ current = l2 ;
60
+ }
61
+
62
+ l2 = l2 . next ;
63
+ }
64
+
65
+ return result ;
66
+ } ;
67
+ // @lc code=end
68
+
You can’t perform that action at this time.
0 commit comments