Java - Simple to understand


  • 0
    T
    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
            if(l1 == null) return l2;
            if(l2 == null) return l1;
            
            ListNode newHead = new ListNode(0);
            ListNode p = newHead;
            
            int carry = 0;
            while(l1!=null || l2!=null){
                int val1 = l1==null ? 0 : l1.val;
                int val2 = l2 == null ? 0 : l2.val;
                int total = val1+val2+carry;
                carry = total/10;
                p.next = new ListNode(total%10);
                p=p.next;
                if(l1!=null)l1=l1.next;
                if(l2!=null)l2=l2.next;
            }
            
            if(carry>0){
                p.next = new ListNode(carry);
            }
            return newHead.next;
            
        } 
    }
    

Log in to reply
 

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