解题思路:
首先将链表1和链表2反转,得到7->3->9 和3->6
然后从头开始两两相加得到sum=head1.val+head2.val+jinwei,将之和sum%10放入新的链表中,进位为sum/10
最后将结果链表反转
参考代码
import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* }
*/
public class Solution {
/**
*
* @param head1 ListNode类
* @param head2 ListNode类
* @return ListNode类
*/
public ListNode addInList (ListNode head1, ListNode head2) {
// write code here
if(head1==null){
return head2;
}
if(head2==null){
return head1;
}
//反转链表
ListNode list1=reverse(head1);
ListNode list2=reverse(head2);
int jinwei=0;
int num1=0,num2=0,sum=0;
ListNode res=new ListNode(0);
ListNode res1=res;
while(list1!=null || list2!=null || jinwei!=0){
if(list1!=null){
num1=list1.val;
list1=list1.next;
}else{
num1=0;
}
if(list2!=null){
num2=list2.val;
list2=list2.next;
}else{
num2=0;
}
sum=num1+num2+jinwei;
res1.next=new ListNode(sum%10);
res1=res1.next;
jinwei=sum/10;
}
ListNode result=reverse(res.next);
return result;
}
public ListNode reverse(ListNode head){
ListNode pre=null;
ListNode next=null;
while(head!=null){
next=head.next;
head.next=pre;
pre=head;
head=next;
}
return pre;
}
}