@@ -9,42 +9,22 @@ function ListNode(val, next) {
99 * @return {ListNode }
1010 */
1111var mergeTwoLists = function ( list1 , list2 ) {
12- if ( ! list1 && ! list2 ) {
13- return null ;
14- }
15-
16- if ( ! list1 || ! list2 ) {
17- return [ list1 , list2 ] . find ( Boolean ) ;
18- }
19-
20- // firstPointer is a head of list who has the smallest value of node
21- let [ firstPointer , secondPointer ] =
22- list1 . val < list2 . val ? [ list1 , list2 ] : [ list2 , list1 ] ;
23- const mergedList = firstPointer ;
24-
25- if ( firstPointer . next === null ) {
26- firstPointer . next = secondPointer ;
27- return mergedList ;
28- }
29-
30- while ( secondPointer !== null ) {
31- let nextFirstPointer = firstPointer . next ;
32- const nextSecondPointer = secondPointer . next ;
33-
34- while (
35- firstPointer . next !== null &&
36- firstPointer . next . val < secondPointer ?. val
37- ) {
38- firstPointer = firstPointer . next ;
39- nextFirstPointer = firstPointer . next ;
12+ const dummy = new ListNode ( ) ;
13+ let current = dummy ;
14+
15+ while ( list1 !== null && list2 !== null ) {
16+ if ( list1 . val < list2 . val ) {
17+ current . next = list1 ;
18+ list1 = list1 . next ;
19+ } else {
20+ current . next = list2 ;
21+ list2 = list2 . next ;
4022 }
4123
42- firstPointer . next = secondPointer ;
43- firstPointer . next . next = nextFirstPointer ;
44-
45- secondPointer = nextSecondPointer ;
46- firstPointer = firstPointer . next ;
24+ current = current . next ;
4725 }
4826
49- return mergedList ;
27+ current . next = list1 !== null ? list1 : list2 ;
28+
29+ return dummy . next ;
5030} ;
0 commit comments