之前做过字符串的加法,故而这里就先读取一次,得到两个链表的字符串表示,然后做字符串的加法即可。需要注意的是posa--; posb--;放置的位置在最后。

public class Solution {
    /**
     * 
     * @param head1 ListNode类 
     * @param head2 ListNode类 
     * @return ListNode类
     */
    public ListNode addInList (ListNode head1, ListNode head2) {
        // write code here
        String number1 = getNumber(head1);
        String number2 = getNumber(head2);
        int flag = 0, posa = number1.length() - 1;
        int posb = number2.length() - 1;
        StringBuilder result = new StringBuilder();
        while(posa >= 0 || posb >= 0){
            int a = posa >= 0 ? number1.charAt(posa) - '0' : 0;
            int b = posb >= 0 ? number2.charAt(posb) - '0' : 0;
            int sum_ = a + b + flag;
            if(sum_ > 9) {
                flag = 1;
                sum_ = sum_ % 10;
            }else{
                flag = 0;
            }
            result.append(sum_);
            posa--;
            posb--;
        }
        if(flag == 1) result.append("1");
        // 构建链表
        String resultStr = result.toString();
        int idx = resultStr.length() - 1;
        ListNode head = new ListNode(0);
        ListNode temp = head;
        while(idx >=0){
            int val = resultStr.charAt(idx) - '0';
            ListNode p = new ListNode(val);
            temp.next = p;
            temp = p;
            idx--;
        }
        return head.next;
    }

    public String getNumber(ListNode root){
        ListNode temp = root;
        StringBuilder sb = new StringBuilder();
        while(temp!=null){
            sb.append(String.valueOf(temp.val));
            temp = temp.next;
        }
        return sb.toString();
    }
}