反转链表 再计算
/*
* public class ListNode {
* int val;
* ListNode next = null;
* }
*/
public class Solution {
/**
*
* @param head1 ListNode类
* @param head2 ListNode类
* @return ListNode类
*/
int carry = 0;
public ListNode addInList (ListNode head1, ListNode head2) {
// write code here
ListNode list1 = reverseListNode(head1);
ListNode list2 = reverseListNode(head2);
ListNode curr1 = list1;
ListNode curr2 = list2;
ListNode guardNode = new ListNode(-1);
ListNode curr3 = guardNode;
while (curr1 != null || curr2 != null|| carry!=0){
int val1 = curr1 != null? curr1.val:0;
int val2 = curr2 != null? curr2.val:0;
int sum = val1 + val2+carry;
carry = sum/10;
int temp = sum%10;
ListNode node = new ListNode(temp);
curr3.next = node;
curr3 = node;
if(curr1 != null){
curr1 = curr1.next;
}
if(curr2 != null){
curr2 = curr2.next;
}
}
ListNode headNode = guardNode.next;
ListNode resNode = reverseListNode(headNode);
return resNode;
}
public ListNode reverseListNode (ListNode head){
if (head == null){
return head;
}
ListNode prev = null;
ListNode curr = head;
while (curr != null){
ListNode nextNode = curr.next;
curr.next = prev;
prev = curr;
curr = nextNode;
}
return prev;
}
}