1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
|
class Solution { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { ListNode newL1 = reverseLinkedList(l1); ListNode newL2 = reverseLinkedList(l2); int carry = 0; int current = 0; ListNode newList = new ListNode(-1); ListNode temp = newList; while(newL1 != null || newL2 != null){ int a = newL1 == null ? 0 : newL1.val; int b = newL2 == null ? 0 : newL2.val; current = (a+b + carry) % 10; temp.next = new ListNode(current); carry = (a+b + carry) / 10; temp = temp.next; if(newL1 != null) newL1 = newL1.next; if(newL2 != null) newL2 = newL2.next; } if(carry == 1){ temp.next = new ListNode(carry); temp = temp.next; } temp.next = null; ListNode result = reverseLinkedList(newList.next); return result; } public ListNode reverseLinkedList(ListNode input){ if(input == null || input.next == null) return input; ListNode temp = reverseLinkedList(input.next); input.next.next = input; input.next = null; return temp; } }
|