LeetCode-addTwoNumbers

public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        // 思路: 在原链表l1上逆序相加,得到逆序的相加链表
        // 要考虑:(1) 进位(尤其是最后有进位,需要新建一个Listnode); (2) 链表长度不对齐
        // 时空分析:(1) O(max(len(l1),len(l2))); (2) O(1)
        // 返回: 链表头指针
        ListNode p1 = l1;
        ListNode p2 = l2;
        ListNode res = l1;
        int carry = 0;
        int sum = 0;
        int temp = 0;
        while(p1.next!=null && p2.next!=null){
            temp = p1.val+p2.val+carry;
            sum = temp%10;
            carry = temp/10;
            p1.val = sum;
            p1 = p1.next;
            p2 = p2.next;
        }
        // 两个链表当前的数字(包括两个链表长度都为1的情况)
        temp = carry+p1.val+p2.val;
        sum = temp%10;
        carry = temp/10;
        p1.val = sum;

        if(p2.next!=null){
            // 如果len(l2)>len(l1)
            p1.next=p2.next;
        }
        while(p1.next!=null&&carry!=0){
            p1 = p1.next;
            temp = p1.val+carry;
            sum = temp%10;
            carry = temp/10;
            p1.val =sum;
        }
        if(carry!=0){
            p1.next = new ListNode(carry,null);
        }
    return res;
    }

 

上一篇:LQBv45-Python:迷宫


下一篇:备战蓝桥杯day3__数码管静态显示