两数相加代码实现

上代码:

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode head = new ListNode();
        ListNode ln = head;
        ListNode ln1 = l1;
        ListNode ln2 = l2;
        int carry = 0;
        while(ln1 != null || ln2 != null){
            int val1 = (ln1 == null ? 0 : ln1.val);
            int val2 = (ln2 == null ? 0 : ln2.val);
            int sum = val1 + val2 + carry;
            carry = sum / 10;
            sum = sum % 10;
            ln.next=new ListNode(sum);
            if (ln1 != null){
                ln1 = ln1.next;
            }
            if(ln2 != null){
                ln2 = ln2.next;
            }
            ln = ln.next;
        }
        if (carry == 1) {
            ln.next = new ListNode(carry);
        }
        return head.next;
    }

 

posted @ 2022-07-12 00:50  努力学习の小白  阅读(143)  评论(0编辑  收藏  举报
Live2D