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;
    }
}

 

posted @ 2020-10-03 08:40  dlooooo  阅读(106)  评论(0编辑  收藏  举报