2. Add Two Numbers

class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode ret=new ListNode(0);
        ListNode l3=ret;
        int carry=0;
        while(l1!=null||l2!=null||carry!=0)
        {
            int sum=carry;
            if(l1!=null)
            {
                sum+=l1.val;
                l1=l1.next;
            }
            if(l2!=null)
            {
                sum+=l2.val;
                l2=l2.next;
            }
            carry=sum/10;
            l3.next=new ListNode(sum%10);
            l3=l3.next;
        }
        return ret.next;
    }
}
  

 

posted @ 2017-09-21 05:39  Weiyu Wang  阅读(108)  评论(0编辑  收藏  举报