# [LeetCode][2]Add Two Numbers解析 -Java实现

Q：

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.

A:

1、把链表转化成long相加之后再转化成链表

2、在链表的基础上做相加

1、把链表中倒叙的数字正过来

2、直接改变数字的进位效果，向后进位。

public class AddTwoNumbers {
public static void main(String[] args){
LinkedList link1 = new LinkedList();
link1.addLast(1);
link1.addLast(2);
LinkedList link2 = new LinkedList();
link2.addLast(1);
link2.addLast(9);
link2.addLast(2);
LinkedList resultLink = addTwoNumbers(link1, link2);
for(Object i : resultLink){
System.out.println(""+(int)i);
}

}
public static LinkedList addTwoNumbers(LinkedList link1,LinkedList link2){
int maxLength = 0;
int minLength = 0;
LinkedList resultLink = null;//结果链表
int carry = 0;
if(link1.size()>link2.size()){
resultLink = link1;
maxLength = link1.size();
minLength = link2.size();
}
else {
resultLink = link2;
maxLength = link2.size();
minLength = link1.size();
}
for(int i =0;i<minLength;i++){
carry = 0;
int result = (int)link1.get(i)+(int)link2.get(i)+carry;
if(result>=10){//进位
carry = (int)result/10;
if(i==minLength-1){//超出了链表长度
if(i<maxLength-1){//没有超出最长，不用加位置
resultLink.set(i+1, (int)resultLink.get(i+1)+carry);
}else {//超出最长需要加链表长度
resultLink.addLast(carry);
}
}
resultLink.set(i, result%10);

}else {//不进位
resultLink.set(i, result);
}
}
return resultLink;
}
}

• 本文已收录于以下专栏：
• LeetCode

举报原因： 您举报文章：[LeetCode][2]Add Two Numbers解析 -Java实现 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)