1 public ListNode addTwoNumbers(ListNode l1, ListNode l2) { 2 ListNode res = new ListNode(0); 3 int num = 0; 4 int carry = 0; 5 ListNode current = res; 6 while((l1 != null) || (l2 != null)) { 7 if(l1 != null && l2 != null) { 8 num = l1.val + l2.val + carry; 9 carry = 0; 10 if(num > 9) { 11 carry = 1; 12 num = num % 10; 13 } 14 current.next = new ListNode(num); 15 l1 = l1.next; 16 l2 = l2.next; 17 current = current.next; 18 }else if(l1 == null) { 19 if(carry == 0) { 20 num = l2.val; 21 }else { 22 num = l2.val + carry; 23 carry = 0; 24 if(num > 9) { 25 num = num % 10; 26 carry = 1; 27 } 28 } 29 current.next = new ListNode(num); 30 l2 = l2.next; 31 current = current.next; 32 }else { 33 if(carry == 0) { 34 num = l1.val; 35 }else { 36 num = l1.val + carry; 37 carry = 0; 38 if(num > 9) { 39 num = num % 10; 40 carry = 1; 41 } 42 } 43 current.next = new ListNode(num); 44 l1 = l1.next; 45 current = current.next; 46 } 47 } 48 if(carry == 1) {
//检查最后一次进位 49 current.next = new ListNode(1); 50 } 51 return res.next; 52 }