Commented Java Solution ( Does not change l1 or l2)


  • 0
    P
    public class Solution {
        public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
            //return the other list if one of them is null
            if (l1 == null) return l2;
            if (l2 == null) return l1;
            
            //first traverses the l1, second l2
            ListNode first,second;
            first = l1; second = l2;
            ListNode node,prev,newHead;
            node = prev = newHead = null;
            int carryOver = 0;//
            
            while(first != null || second != null || carryOver > 0){//loop while carryOver is greater than 0 and till the end of both the lists
                
                int f,s,newVal;f = s = newVal = 0;
                //get the val of the lists, 0 if list is null
                if (first != null){ f = first.val; first = first.next;}
                if (second != null){ s = second.val; second = second.next;}
                newVal = f+s+carryOver;//new value
                if (newVal > 9) {//sum greater than 9 
                    carryOver = 1;//to be added in the next iteration
                    newVal = newVal%10;//store the remainder
                }else{
                    carryOver = 0;//no carry over
                }
                node = new ListNode(newVal);//make a new node
                if (prev != null) prev.next = node;//check if it is the first node
                else {
                    newHead = node;//assign the node as head node
                }
                prev = node;
                
            }
            return newHead;// return the head node of the new list
        }
    }

  • 3
    R

    my solution for ref

    public class Solution {
        public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
            ListNode nh = new ListNode(0);
            ListNode l = nh;
            int carry = 0;
            while ( l1 != null || l2 != null ) {
                int n = (l1 == null ? 0 : l1.val) + (l2 == null ? 0 : l2.val) + carry;
                carry = n / 10;
                n = n % 10;
                l.next = new ListNode(n);
                l = l.next;
                l1 = l1 == null ? null : l1.next;
                l2 = l2 == null ? null : l2.next;
            }
            if ( carry > 0 ) {
                l.next = new ListNode(carry);
            }
            return nh.next;
        }
    }

  • 0
    P

    looks clean, really good


  • 0
    L

    Your code is compact and beautiful!!!


  • 0
    G

    Very good code!!!


Log in to reply
 

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