在java解决方案中添加两个链表会导致超出时间限制

bbmckpt7  于 2021-08-25  发布在  Java
关注(0)|答案(1)|浏览(214)

leetcode上的问题:https://leetcode.com/problems/add-two-numbers/ 我的解决方案导致超出时间限制,我无法理解我的代码有什么问题:

class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        int c = 0, j = 0;
        ListNode temp3 = new ListNode(); //temp3 = null;
        ListNode h = temp3;
        int n;

        while (l1 != null || l2 != null || c == 1) {
            int s = 0;
            if (l1 == null && l2 == null)
                s = c;
            else if (l1 == null) 
                s = l2.val + c;
            else if (l2 == null)
                s = l1.val + c;
            else 
                s = l1.val + l2.val + c;

            if (s > 9) {
                c = s / 10;
                s = s % 10;
            }

            ListNode node = new ListNode(s);
            //System.out.println(node.val);
            h.next = node;

            if (l1 != null)
                l1 = l1.next;

            if (l2 != null)
                l2 = l2.next;

            h = h.next;
        }

        return temp3.next;        
    }
}
wlzqhblo

wlzqhblo1#

看起来你从来没有重置过携带( c )回到 0 .
因此,一旦将其设置为非零值,循环将永远不会结束。
您应该将其重置为 0 在项目的每个迭代开始时 while
或者你可以改变

if (s > 9) {
    c = s / 10;
    s = s % 10;
}

if (s > 9) {
    c = s / 10;
    s = s % 10;
} else {
    c = 0;
}

相关问题