import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* public ListNode(int val) {
* this.val = val;
* }
* }
*/
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;
}
head1 = reverseList(head1);
head2 = reverseList(head2);
ListNode head = new ListNode(-1);
ListNode nhead = head;
int flag = 0;
while(head1 != null || head2 !=null)
{
int val=0;
if(head1 != null)
{
val += head1.val;
head1 = head1.next;
}
if(head2 != null)
{
val += head2.val;
head2= head2.next;
}
val += flag;
if(val > 9)
{
val = val%10;
flag = 1;
}else{
flag = 0;
}
nhead.next = new ListNode(val);
nhead = nhead.next;
}
if(flag == 1)
{
nhead.next = new ListNode(1);
}
return reverseList(head.next);
}
private ListNode reverseList(ListNode head) {
if (head == null) return head;
ListNode pre = null;
ListNode cur = head;
ListNode next;
while (cur != null) {
next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
return pre;
}
}