Skip to content
Advertisement

Adding two linked lists in java solution results in time limit exceeded

the problem on leetcode: https://leetcode.com/problems/add-two-numbers/ My solution results in time limit exceeded and I cannot understand what’s wrong with my code:

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;        
    }
}

Advertisement

Answer

It looks like you are never resetting the carry (c) back to 0.

Therefore, once you set it to a non-zero value, the loop will never end.

You should reset it to 0 at the start of each iteration of the while loop.

Or you can change

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

to

if (s > 9) {
    c = s / 10;
    s = s % 10;
} else {
    c = 0;
}
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement