Simple straight forward Java code


  • 0
    A
    public class Solution {
        public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
            if (l1 == null || l2 == null){
                return null;
            }
            int carry = 0;
            ListNode res = null;
            ListNode end = null;
            while (l1 != null && l2 != null){
                int val = l1.val + l2.val + carry;
                if (val > 9){
                    carry = 1;
                }
                else{
                    carry = 0;
                }
                if (res == null){
                    res = new ListNode(val%10);
                    end = res;
                }
                else {
                    end.next = new ListNode(val%10);
                    end = end.next;
                }
                l1 = l1.next;
                l2 = l2.next;
            }
            while (l1 != null){
                int val = l1.val + carry;
                if (val > 9){
                    carry = 1;
                }
                else{
                    carry = 0;
                }
                if (res == null){
                    res = new ListNode(val%10);
                    end = res;
                }
                else {
                    end.next = new ListNode(val%10);
                    end = end.next;
                }
                l1 = l1.next;
            }
            while (l2 != null){
                int val = l2.val + carry;
                if (val > 9){
                    carry = 1;
                }
                else{
                    carry = 0;
                }
                if (res == null){
                    res = new ListNode(val%10);
                    end = res;
                }
                else {
                    end.next = new ListNode(val%10);
                    end = end.next;
                }
                l2 = l2.next;
            }
            if (carry == 1){
                end.next = new ListNode(carry);
                end = end.next;
            }
            return res;
        }
    }

Log in to reply
 

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