问题:
You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8
代码示例:
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class Solution { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { int length1 = 0; ListNode temp = l1; while (temp != null) { length1++; temp = temp.next; } int length2 = 0; temp = l2; while(temp != null) { length2++; temp = temp.next; } int longLength = length1 > length2 ? length1 : length2; if (longLength == 0) { return null; } ListNode result = new ListNode(0); ListNode realResult = result; int carry = 0; for (int i = 0; i < longLength; ++i) { int first = 0; int second = 0; if (l1 != null) { first = l1.val; l1 = l1.next; } if (l2 != null) { second = l2.val; l2 = l2.next; } result.val = carry + first + second; if (result.val >= 10) { result.val = result.val - 10; carry = 1; } else { carry = 0; } //we should not make a listNode every time if (i < longLength -1) { result.next = new ListNode(0); result = result.next; } } //only if we have a carry, then we create a new listnode for the last addition if (carry == 1) { result.next = new ListNode(0); result.next.val = carry; } return realResult; } }