参考:derrantcm,网址:https://blog.csdn.net/derrantcm/article/details/46905467
package algorithm;
import java.lang.ref.WeakReference;
/*
2个正数相加,该正数用链表表示,正数反向存储(最低位先存)
原题
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
题目大意
有两个单链表,代表两个非负数,每一个节点代表一个数位,数字是反向存储的,即第一个结点表示最低位,最后一个结点表示最高位。求两个数的相加和,并且以链表形式返回。
解题思路
对两个链表都从第一个开始处理,进行相加,结果再除以10求商,作为下一位相加的进位,同时记录余数,作为本位的结果,一直处理,直到所有的结点都处理完。
*/
public class TwoNumPlus {
/*
* 辅助类
*
* */
class ListNode{
int value;//值
ListNode nextNode; //下一个节点
ListNode(int value){
this.value=value;
this.nextNode=null;
}
}
/*
*数组变成链表对象
*输入:整型数组
*输出:链表对象
**/
ListNode buildListNode(int[] input){
ListNode first=null,last=null;
if(input==null){
return null;
}
ListNode newNode;
for(int i=0;i<input.length;i++){
newNode=new ListNode(input[i]);
if(first==null){//开始为空
first=newNode;
last=newNode;
}else{
last.nextNode=newNode;
last=newNode;
}
}
return first;
}
/**
* 002-Add Two Numbers (单链表表示的两个数相加)
* @param l1 第一个数
* @param l2 第二个数
* @return 结果
*/
public ListNode addTwoNumbers(ListNode l1,ListNode l2){
if(l1==null)
return l2;
if(l2==null)
return l1;
ListNode p1=l1;
ListNode p2=l2;
ListNode first=null,last=null;
int carry=0;//进位
while(p1!=null&&p2!=null){
int sum=p1.value+p2.value+carry;
int mod=sum%10;
carry=sum/10;
System.out.println("mod="+mod);
ListNode newNode=new ListNode(mod);
if(first==null){
first=newNode;
last=newNode;
}else{
last.nextNode=newNode;
last=newNode;
}
p1=p1.nextNode;
p2=p2.nextNode;
}
while(p1!=null){
int sum=p1.value+carry;
int mod=sum%10;
carry=sum/10;
ListNode newNode=new ListNode(mod);
if(first==null){
first=newNode;
last=newNode;
}else{
last.nextNode=newNode;
last=newNode;
}
p1=p1.nextNode;
}
while(p2!=null){
int sum=p2.value+carry;
int mod=sum%10;
carry=sum/10;
ListNode newNode=new ListNode(mod);
if(first==null){
first=newNode;
last=newNode;
}else{
last.nextNode=newNode;
last=newNode;
}
p2=p2.nextNode;
}
return first;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] input1={2,4,3};
int[] input2={5,6,4,1};
TwoNumPlus tp=new TwoNumPlus();
WeakReference<TwoNumPlus> wrf=new WeakReference<TwoNumPlus>(tp);
if(wrf.get()!=null){
ListNode l1=wrf.get().buildListNode(input1);
ListNode l2=wrf.get().buildListNode(input2);
ListNode head1=l1;
System.out.println("初始值--1--如下:");
while(l1!=null){
System.out.print("->"+l1.value);
l1=l1.nextNode;
}
System.out.println("");
System.out.println("");
ListNode head2=l2;
System.out.println("初始值--2--如下:");
while(l2!=null){
System.out.print("->"+l2.value);
l2=l2.nextNode;
}
System.out.println("");
ListNode listNode=wrf.get().addTwoNumbers(head1,head2);
System.out.println("结果为--如下:");
while(listNode!=null){
System.out.print("->"+listNode.value);
listNode=listNode.nextNode;
}
System.out.println("");
}
}
}