原文:
You have two numbers represented by a linked list, where each node contains a single digit. The digits are stored in reverse 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
Input: (3 –> 1 –> 5), (5 –> 9 –> 2)
Output: 8 –> 0 –> 8
译文:
你有两个由单链表表示的数。每个结点代表其中的一位数字。数字的存储是逆序的, 也就是说个位位于链表的表头。写一函数使这两个数相加并返回结果,结果也由链表表示。
例子:(3 –> 1 –> 5), (5 –> 9 –> 2)
输入:8 –> 0 –> 8
使用递归,如果anode和bnode不同时为空,则new一个新的morenode,morenode.data=anode.data+bnode.data+carry(上一次相加的进位)。
public static void main(String args[]) {
// a = 815
int a[] = {5, 1, 8,};
// b = 3186
int b[] = {6, 8, 1, 3};
LinkedListNode aNode = arrToList(a);
LinkedListNode bNode = arrToList(b);
//output aNode: 518
printList(aNode);
//output bNode 6813
printList(bNode);
LinkedListNode result = add(aNode, bNode, 0);
//output result 1004
printList(result);
}
public static void printList(LinkedListNode a) {
LinkedListNode tmp = a;
while (tmp != null) {
System.out.println(tmp.data);
tmp = tmp.next;
};
System.out.println("");
}
public static LinkedListNode arrToList(int[] a) {
LinkedListNode node = null;
LinkedListNode tmp = null;
for (int i = 0; i < a.length; i++) {
LinkedListNode next = new LinkedListNode(a[i]);
if (i == 0) {
node = tmp = next;
continue;
}
tmp.next = next;
tmp = next;
}
return node;
}
public static LinkedListNode add(LinkedListNode a, LinkedListNode b, int carry) {
if (a == null && b == null) {
return null;
}
LinkedListNode result = new LinkedListNode(carry);
int value = carry;
if (a != null) {
value += a.data;
}
if (b != null) {
value += b.data;
}
result.data = value % 10;
LinkedListNode more = add(a == null ? null : a.next, b == null ? null : b.next, value > 9 ? 1 : 0);
result.next = more;
return result;
}