Java solution


  • 0
    V
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
            
            int carry = 0;
            ListNode head = null;
            ListNode rear = null;
            
            ListNode d1 = l1;
            ListNode d2 = l2;
            
            while((d1 != null && d2 != null) || carry == 1){
                
                int val = (d1 == null ? 0 : d1.val) + (d2 == null ? 0 : d2.val) + carry;
                int dig = val%10;
                carry   = val/10;
    
                if (head == null) {
                    head = new ListNode(dig);
                    rear = head;
                }
                else {
                    rear.next = new ListNode(dig);
                    rear = rear.next;
                }
                
                d1 = d1 == null ? null : d1.next;
                d2 = d2 == null ? null : d2.next;
            }
            
            ListNode l = d1 != null ? d1 : d2;
            if (l != null){
                if (rear != null ){
                    rear.next = l;    
                }
                else {
                    head = l;
                }
            }
            
            return head;
        }
    
    

Log in to reply
 

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