You have two numbers represented by a linked list, where each node contains a single digit. The digits are stored in forward order, such that the 1’s digit is at the head of the list. Write a function that adds the two numbers and returns the sum as a linked list.
Example Given 6->1->7 + 2->9->5. That is, 617 + 295.
Return 9->1->2. That is, 912.
Solution:
Revese the given two linked list. Then use the solution presented in the solution of “Add Two Numbers” to add then together. Finally, reverse the result linked list back.
/************************************************************************* > File Name: AddTwoNumbersII.java > Author: Yao Zhang > Mail: psyyz10@163.com > Created Time: Mon 16 Nov 14:27:38 2015 ************************************************************************/
publicclassAddTwoNumbersII{ /** * @param l1: the first list * @param l2: the second list * @return: the sum list of l1 and l2 */ public ListNode addLists2(ListNode l1, ListNode l2){ l1 = reverse(l1); l2 = reverse(l2);
return reverse(addLists1(l1,l2)); }
public ListNode reverse(ListNode l){ ListNode head = null;
while (l != null){ ListNode temp = l.next; l.next = head; head = l; l = temp; }
return head; }
public ListNode addLists1(ListNode l1, ListNode l2){ if (l1 == null && l2 == null) returnnull;
ListNode head = new ListNode(0); ListNode current = head; int carry = 0;
while (l1 != null || l2 != null){ int sum = carry;
if (l1 != null){ sum += l1.val; l1 = l1.next; }
if (l2 != null){ sum += l2.val; l2 = l2.next; }
carry = sum / 10; current.next = new ListNode(sum % 10); current = current.next; }
if (carry != 0){ current.next = new ListNode(carry); }