思路:创建一个ReverseList方法,然后将开头每个值相加,当和超过十时则进一,并加到链表下一个数上,最后将生成的链表进行反转;
import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* }
*/
public class Solution {
/**
*
* @param head1 ListNode类
* @param head2 ListNode类
* @return ListNode类
*/
public ListNode ReverseList(ListNode pHead){
if(pHead == null){
return null;
}
ListNode cur = pHead;
ListNode pre = null;
while(cur != null){
ListNode temp = cur.next;
cur.next = pre;
pre = cur;
cur = temp;
}
return pre;
}
public ListNode addInList (ListNode head1, ListNode head2) {
if(head1 == null){
return head2;
}
if(head2 == null){
return head1;
}
head1 = ReverseList(head1);
head2 = ReverseList(head2);
ListNode res = new ListNode(-1);
ListNode head = res;
int carry = 0;
while(head1 != null || head2 != null || carry != 0){
int k1 = head1 == null ? 0 : head1.val;
int k2 = head2 == null ? 0 : head2.val;
int temp = k1 + k2 + carry;
carry = temp / 10;
temp %= 10;
head.next = new ListNode(temp);
head = head.next;
if(head1 != null){
head1 = head1.next;
}
if(head2 != null){
head2 = head2.next;
}
}
return ReverseList(res.next);
}
}