445. Add Two Numbers II

You are given two linked lists representing two non-negative numbers. The most significant digit comes first and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Follow up:
What if you cannot modify the input lists? In other words, reversing the lists is not allowed.

Example:

Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 8 -> 0 -> 7

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode reverseL1 = reverseList(l1);
        ListNode reverseL2 = reverseList(l2);
        int digit = 0;
        int curry = 0;
        ListNode dummy = new ListNode(0);
        ListNode pre = dummy;
        while(reverseL2 != null || reverseL1 != null || curry != 0){
            int index1 = (reverseL1 == null? 0 : reverseL1.val);
            int index2 = (reverseL2 == null? 0 : reverseL2.val);
            digit = (index1 + index2 + curry) % 10;
            curry = (index1 + index2 + curry) / 10;
            dummy.next = new ListNode(digit);
            dummy = dummy.next;
            if(reverseL1 != null) reverseL1 = reverseL1.next;
            if(reverseL2 != null) reverseL2 = reverseL2.next;
        }
        return reverseList(pre.next);
    }
    public ListNode reverseList(ListNode head){
        if(head== null || head.next == null) return head;
        ListNode dummy = new ListNode(0);
        dummy.next =  head;
        ListNode cur = head.next;
        while(cur != null){
            head.next = cur.next;
            cur.next = dummy.next;
            dummy.next = cur;
            cur = head.next;
        }
        return dummy.next;
        
    }
}
原文地址:https://www.cnblogs.com/joannacode/p/6108133.html