水下功夫做透,水上才能顺风顺水。

链表中逆序的两数之和

 public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode  res = new ListNode();
        ListNode cur = res;
        int sum = 0;
        int carry = 0;
        while(l1!=null&&l2!=null){
            sum = l1.val+l2.val+carry;
            if(sum>=10){
                cur.val = sum%10;
                carry = sum/10;
            }else{
                cur.val =  sum;
                carry = 0;
            }
            l1 = l1.next;
            l2 = l2.next;
            if(l1!=null||l2!=null){
                cur.next = new ListNode();
                cur = cur.next;
            }

        }
        while(l1!=null){
            sum = l1.val+carry;
            if(sum>=10){
                cur.val = sum%10;
                carry = sum/10;
            }else{
                cur.val =  sum;
                carry = 0;
            }
            l1 = l1.next;
            if(l1!=null){
                cur.next = new ListNode();
                cur = cur.next;
            }
        }
        while(l2!=null){
            sum = l2.val+carry;
            if(sum>=10){
                cur.val = sum%10;
                carry = sum/10;
            }else{
                cur.val =  sum;
                carry = 0;
            }
            l2 = l2.next;
            if(l2!=null){
                cur.next = new ListNode();
                cur = cur.next;
            }
        }
        if(carry !=0){
             cur.next = new ListNode();
             cur = cur.next;
             cur.val = carry;
        }
        return res;
    }

 

posted @ 2022-03-05 11:35  北方寒士  阅读(67)  评论(0编辑  收藏  举报