Untitled

 avatar
unknown
plain_text
2 years ago
1.0 kB
60
Indexable
/**
 * Definition for singly-linked list.
 * class ListNode {
 *     public int val;
 *     public ListNode next;
 *     ListNode(int x) { val = x; next = null; }
 * }
 */
public class Solution {
    public ListNode addTwoNumbers(ListNode A, ListNode B) {
        ListNode dummy = new ListNode(-1);
        ListNode temp = dummy; 
        
        ListNode t1 = A, t2 = B;
        int carry = 0;
        
        while(t1 != null || t2 != null || carry != 0){
            int sum = carry;
            if(t1 != null){
                sum += t1.val;
                t1 = t1.next;
            }
            if(t2 != null){
                sum += t2.val;
                t2 = t2.next;
            }
            
            if(sum >= 10){
                sum -= 10;
                carry = 1;
            }else{
                carry = 0;
            }
            
            ListNode nn = new ListNode(sum);
            temp.next = nn;
            temp = nn;
        }
        return dummy.next;
    }
}
Editor is loading...