给定两个非空链表来表示两个非负整数。位数按照逆序方式存储,它们的每个节点只存储单个数字。将两数相加返回一个新的链表。你可以假设除了数字 0 之外,这两个数字都不会以零开头。
示例:
输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807
代码一:
1 public ListNode addTwoNumbers(ListNode l1, ListNode l2) { 2 ListNode result = new ListNode(0); 3 ListNode first = l1, second = l2, tmpNode = result; 4 int tmp = 0; 5 6 while(first != null || second != null){ 7 int firstValue ,secondValue; 8 if(first == null){firstValue = 0;} 9 else{firstValue = first.val;} 10 11 if(second == null){secondValue = 0;} 12 else{secondValue = second.val;} 13 14 tmp = tmp + firstValue + secondValue; 15 tmpNode.next = new ListNode(tmp % 10); 16 tmp = tmp / 10; 17 18 tmpNode = tmpNode.next; 19 if(first != null){first = first.next;} 20 if(second != null){second = second.next;} 21 } 22 if(tmp != 0){ 23 tmpNode.next = new ListNode(tmp % 10); 24 } 25 return result.next; 26 }
代码二:
1 public ListNode addTwoNumbers(ListNode l1, ListNode l2) { 2 ListNode dummyHead = new ListNode(0); 3 ListNode p = l1, q = l2, curr = dummyHead; 4 int carry = 0; 5 while (p != null || q != null) { 6 int x = (p != null) ? p.val : 0; 7 int y = (q != null) ? q.val : 0; 8 int sum = carry + x + y; 9 carry = sum / 10; 10 curr.next = new ListNode(sum % 10); 11 curr = curr.next; 12 if (p != null) p = p.next; 13 if (q != null) q = q.next; 14 } 15 if (carry > 0) { 16 curr.next = new ListNode(carry); 17 } 18 return dummyHead.next; 19 }