File tree 1 file changed +27
-15
lines changed
1 file changed +27
-15
lines changed Original file line number Diff line number Diff line change 10
10
*/
11
11
class Solution {
12
12
public ListNode mergeTwoLists (ListNode list1 , ListNode list2 ) {
13
- ListNode dummy = new ListNode (- 1 );
14
- ListNode curr = dummy ;
15
- while ( list1 != null || list2 != null ) {
16
- if ( list1 ! = null && list2 != null ) {
17
- if ( list1 . val > list2 . val ) {
18
- curr . next = new ListNode ( list2 . val );
19
- list2 = list2 .next ;
20
- } else {
21
- curr . next = new ListNode ( list1 . val );
22
- list1 = list1 . next ;
13
+ if ( list1 == null || list2 == null ) {
14
+ return list1 == null ? list2 : list1 ;
15
+ }
16
+ ListNode prev = null ;
17
+ ListNode head = null ;
18
+ while ( list1 != null && list2 != null ) {
19
+ if ( list1 . val < = list2 .val ) {
20
+ prev = list1 ;
21
+ if ( head == null ) {
22
+ head = list1 ;
23
23
}
24
- } else if (list1 != null && list2 == null ) {
25
- curr .next = new ListNode (list1 .val );
26
24
list1 = list1 .next ;
27
25
} else {
28
- curr . next = new ListNode ( list2 . val ) ;
26
+ ListNode node = list2 ;
29
27
list2 = list2 .next ;
28
+ if (prev == null ) {
29
+ node .next = list1 ;
30
+ prev = node ;
31
+ head = prev ;
32
+ } else {
33
+ prev .next = node ;
34
+ node .next = list1 ;
35
+ prev = node ;
36
+ }
30
37
}
31
- curr = curr .next ;
32
38
}
33
- return dummy .next ;
39
+ if (list2 != null ) {
40
+ prev .next = list2 ;
41
+ }
42
+ if (list1 != null ) {
43
+ prev .next = list1 ;
44
+ }
45
+ return head ;
34
46
}
35
47
}
You can’t perform that action at this time.
0 commit comments