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) {
        // write code here
        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 count = 0;
        
        ListNode newNode = null;
        ListNode head = null;
        while(!s1.isEmpty() || !s2.isEmpty() || count==1){
            int a = (s1.isEmpty())?0:s1.pop();//逆序
            int b = (s2.isEmpty())?0:s2.pop();
            int sum = a + b + count;//模拟相加
            if(sum>9){
                count = 1;
                sum = sum%10;
            }
            else
                count = 0;
            //newNode.val = sum;
            newNode = new ListNode(sum);
            newNode.next = head;
            head = newNode;
           
        }
        return head;
   }
}