import java.util.*;
public class Solution {
public ListNode addInList (ListNode head1, ListNode head2) {
Stack<ListNode> stack1 = new Stack<>();
Stack<ListNode> stack2 = new Stack<>();
while (head1 != null) {
stack1.push(head1);
head1 = head1.next;
}
while (head2 != null) {
stack2.push(head2);
head2 = head2.next;
}
int num = 0;
ListNode node=new ListNode(-1);
ListNode pre=node;
while (!stack2.isEmpty()||!stack1.isEmpty()||num!=0) {
int num1=stack1.isEmpty()? 0: stack1.pop().val;
int num2=stack2.isEmpty()? 0: stack2.pop().val;
int n = (num1 + num2 + num) % 10;
num = (num1 + num2 + num) / 10;
ListNode tmp=new ListNode(n);
pre.next=tmp;
pre=pre.next;
}
return reverse(node.next);
}
// public ListNode addInList (ListNode head1, ListNode head2) {
// if(head1==null){
// return head2;
// }else if(head2==null){
// return head1;
// }
// head1=reverse(head1);
// head2=reverse(head2);
// int n=0;
// ListNode node=new ListNode(-1);
// ListNode pre=node;
// while(head1!=null||head2!=null||n!=0){
// int n1=head1==null?0:head1.val;
// int n2=head2==null?0:head2.val;
// int sum=(n1+n2+n)%10;
// n=(n1+n2+n)/10;
// ListNode tmp=new ListNode(sum);
// node.next=tmp;
// node=node.next;
// if(head1!=null){
// head1=head1.next;
// }
// if(head2!=null){
// head2=head2.next;
// }
// }
// pre=reverse(pre.next);
// return pre;
// }
private static ListNode reverse(ListNode head){
ListNode node=null;
while(head!=null){
ListNode list=head.next;
head.next=node;
node=head;
head=list;
}
return node;
}
}