8
8
*
9
9
* You are given two linked lists representing two non-negative numbers.
10
10
* The digits are stored in reverse order and each of their nodes contain
11
- *a single digit. Add the two numbers and return it asa linked list.
11
+ *l1 single digit. Add the two numbers and return it asl1 linked list.
12
12
* Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
13
13
* Output: 7 -> 0 -> 8
14
14
*
@@ -28,26 +28,18 @@ public class Solution {
28
28
* Be careful to test null before reference node's value
29
29
*/
30
30
public ListNode addTwoNumbers (ListNode l1 ,ListNode l2 ) {
31
- int carry =0 ;
32
- ListNode h1 =l1 ;
33
- ListNode h2 =l2 ;
34
31
ListNode dummy =new ListNode (0 );
35
32
ListNode node =dummy ;
36
- while (h1 !=null ||h2 !=null ||carry >0 ) {
37
- int n1 =0 ;
38
- int n2 =0 ;
39
- if (h1 !=null ) {
40
- n1 =h1 .val ;
41
- h1 =h1 .next ;
42
- }
43
- if (h2 !=null ) {
44
- n2 =h2 .val ;
45
- h2 =h2 .next ;
46
- }
47
- int num =n1 +n2 +carry ;
48
- node .next =new ListNode (num %10 );
33
+ int carry =0 ;
34
+ while (l1 !=null ||l2 !=null ||carry !=0 ) {
35
+ int n1 =l1 !=null ?l1 .val :0 ;
36
+ int n2 =l2 !=null ?l2 .val :0 ;
37
+ int sum =n1 +n2 +carry ;
38
+ node .next =new ListNode (sum %10 );
49
39
node =node .next ;
50
- carry =num /10 ;
40
+ carry =sum /10 ;
41
+ l1 =l1 !=null ?l1 .next :null ;
42
+ l2 =l2 !=null ?l2 .next :null ;
51
43
}
52
44
return dummy .next ;
53
45
}