Java 56 ms clean solution using dummy node


  • 0
    S

    Using a dummy node, no need to worry about null pointers.

    /**
     * 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) {
            ListNode head = new ListNode(-1);   // dummy
            ListNode current = head;
            int sum = 0;
    
            while(l1 != null || l2 != null){
                sum /= 10;
                sum += l1 != null ? l1.val : 0;
                sum += l2 != null ? l2.val : 0;
                current.next = new ListNode(sum % 10);
                current = current.next;
                l1 = l1 != null ? l1.next : null; 
                l2 = l2 != null ? l2.next : null;
            }
            
            if(sum >= 10) {
                current.next = new ListNode(sum/10);
            }
            
            return head.next;
        }
    }
    

Log in to reply
 

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