5mS Java non-recursive solution


  • 0
    H
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
            ListNode r2, temp1 = l1, temp2=l2, temp3 = null, r = null;
            int s,carry = 0;
            while (carry != 0 || temp1!=null || temp2 != null){
                s = carry + (temp1 != null ? temp1.val : 0) + (temp2 != null ? temp2.val : 0);
                
                if (s>=10) {
                    carry = 1;
                    s -= 10;
                } else {
                    carry = 0;
                }
                
                r2 = new ListNode(s);
                if (r == null) {
                    r = r2;
                    temp3 = r;
                } else {
                    temp3.next = r2;
                    temp3 = temp3.next;
                }
                if (temp1 != null) {
                    temp1 = temp1.next;
                }
                if (temp2 != null) {
                    temp2 = temp2.next;
                }
            }
            return r;
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.