//先将两个链表分别存放在两个栈中,然后每次分别取出一个值组成新的栈即可
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) {
    Stack<Integer> s1 = new Stack<>();
    Stack<Integer> s2 = new Stack<>();
    while (head1 != null) {
        s1.push(head1.val);
        head1 = head1.next;
    }
    while (head2 != null) {
        s2.push(head2.val);
        head2 = head2.next;
    }
    int  sum = 0;
    int val1 = 0;
    int val2 = 0;
    ListNode res = null;
    int n = Math.max(s1.size(), s2.size());
    for (int i = 0; i < n; i++) {
        if (!s1.isEmpty()) {
            val1 = s1.pop();
        }
        if (!s2.isEmpty()) {
            val2 = s2.pop();
        }
        sum += val1 + val2;
        ListNode list = new ListNode(sum % 10 );
        list.next = res;
        res = list;
        sum = sum / 10;
        val1 = 0;
        val2 = 0;

    }
    return res;

    // write code here
}

}