LeetCode:2 两数相加

class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        if(l1==null){
            return l2;
        }
        if(l2==null){
            return l1;
        }
        int t=0;
        
        ListNode res = new ListNode(0,null);
        ListNode recent = res;
        while(l1!=null||l2!=null){
            int x = l1==null?0:l1.val;
            int y = l2==null?0:l2.val;
            int temp=x+y+t;
            t = temp / 10;
            temp = temp % 10;
            ListNode n = new ListNode(temp,null);
            
            recent.next = n;
            recent = n;
            if(l1!=null)l1=l1.next;
            if(l2!=null)l2=l2.next;
        }
        if(t!=0){
            ListNode n = new ListNode(t,null);
            recent.next = n;
        }
        return res.next;
    }
}
原文地址:https://www.cnblogs.com/dloooooo/p/13763472.html