# 【Java】对两个用链表表示的整数求和

	public LinkedList addLists(LinkedList l1, LinkedList l2, int carry){
if (null == l1 && null == l2 && 0 == carry) return null;
LinkedList result = new LinkedList();
int value = carry;
if (l1 != null) value += l1.data;
if (l2 != null) value += l2.data;
result.data = value % 10;
LinkedList more = addLists(null == l1? null : l1.next, null == l2? null : l2.next, value > 10? 1 : 0);
result.setNext(more);
return result;

}

public class PartialSum {
public LinkedList sum = null;
public int carry = 0;
}

LlinkedList addLists(LinkedList l1, LinkedList l2) {
int len1 = length(l1);
int len2 = length(l2);

if(len1 < len2) {
l1 = padList(l1, len2 - len1);
}
else {
l2 = padList(l2, len1 - len2);
}

PartialSum sum = addListsHelper(l1, l2);
if (sum.carry == 0) {
return sum.sum;
}
else {
LinkedList result = interBefore(sum.sum, sum.carry);
return result;
}
}

PartialSum addListsHelper(LinkedList l1, LinkedList l2) {
if (null == l1 && null == l2) {
PartialSum sum = new PartialSum();
return sum;
}

PartialSum sum = addListHelper(l1.next, l2.next);
int val = sum.carry + l1.data + l2.data;
LinkedList full_result = insetBefore(sum.sum, val%10);
sum.sum = full_result;
sum.carry = val / 10;
return sum;
}

LinkedList padList(LinkedList l, ind padding) {
LinkedList head = l;
for (int i = 0; i< padding; i++) {
LinkedList n = new LinkedList(0, null, null);
head.pre = n;
n.next = head;
head = n;
}
return head;
}

LinkedList insetBefore(LinkedList list, int data) {
LinkedList node = new LinkedList(data, null, null);
if(list != null) {
list.prev = node;
node.next = list;
}
return node;
}

int length(LinkedList l) {
int count = 0;
LinkedList p = l;
if (null == l) return 0;
while (p != null) {
count++;
p = p.next;
}
return count;
}

#### 【LeetCode-面试算法经典-Java实现】【002-Add Two Numbers (单链表表示的两个数相加)】

2015-07-16 07:10:21

#### 给定两个非空链表来表示两个非负整数。位数按照逆序方式存储，它们的每个节点只存储单个数字。将两数相加返回一个新的链表。

2018-05-21 15:06:54

#### [LeetCode] Add Two Numbers 两数相加

2018-02-20 22:49:03

#### 两数相加

2018-02-24 02:40:09

#### 链表相加

2016-07-20 20:36:01

#### LeetCode第2题：Add Two Numbers

2017-03-29 12:07:16

#### python求两个链表组成的数字的和

2018-04-21 02:41:59

#### LeetCode 2. 两数相加

2018-04-30 23:44:21

#### 给定两个链表表示的整数，编写函数对这两个整数求和，并用链表形式返回结果。

2016-06-03 15:09:20

#### leetCode——第二题：两数相加

2018-05-13 19:02:11