每日一题 力扣 445 https://leetcode.cn/problems/add-two-numbers-ii/

发布时间 2023-07-03 14:22:05作者: 故里oc

可以直接用栈去做就行,逆序想到栈的做法

然后算完一个就直接赋值给答案数组

 我用的是常见
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {

        int sizeA=0;
        int sizeB=0;

        ListNode start=l1;
        ListNode r1=l1;
        ListNode r2=l2;
        while (start!=null){
            r1=start;
            start=start.next;
            sizeA++;
        }

         start=l2;
        while (start!=null){
            r2=start;
            start=start.next;
            sizeB++;
        }

        //    逆转
        reverse(l1, 0);
        reverse(l2, 0);

        int add = 0;
        //把长的放到r1
        if (sizeA<sizeB){
            ListNode t=r1;
            r1=r2;
            r2=t;
        }



        start=r1;
        while (r1 != null ) {

            int a = r1.val;
            int b = r2 == null ? 0 : r2.val;

            //   全都放到r1上面
            r1.val = (a + b + add) % 10;
            add = (a + b + add) / 10;
            r1=r1.next;
            if (r2!=null){
                r2=r2.next;
            }
        }
        //返回头节点
    //    对start逆转
        ListNode[] reverse = reverse(start, 0);
        if (add!=0){
            ListNode temp = new ListNode(add);
            temp.next=reverse[1];
            return temp;
        }

        return reverse[1];

    }

    /**
     * 返回2个
     * 0 下一个
     * 1 尾巴
     * @param root
     * @param sum
     * @return
     */
    public ListNode[] reverse(ListNode root, int sum) {

        if (root == null) {
            return null;
        }
        sum++;
        ListNode[] res = reverse(root.next, sum);
        ListNode next=null;
        if (res!=null){
            next=res[0];
        }
        if (next != null) {
            root.next=null;
            next.next = root;

            //返回尾巴
            return new ListNode[]{root,res[1]};
        } else {
            return new ListNode[]{root,root};
        }

    }

 

的做法,将链表进行逆转,适合大部分情况