JAVA---------------Easy Version To Understand!!!!!!!


  • 1
    H
    	public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
    	if (l1 == null)
    		return l2;
    	if (l2 == null)
    		return l1;
    	ListNode head = new ListNode(0), r = head, p = l1, q = l2, tmp;
    	r.next = null;
    	int carry = 0, sum;
    	while (p != null || q != null) {
    		sum = 0;
    		sum += carry;
    		if (p != null) {
    			sum += p.val;
    			p = p.next;
    		}
    		if (q != null) {
    			sum += q.val;
    			q = q.next;
    		}
    		tmp = new ListNode(sum % 10);
    		carry = sum / 10;
    		r.next = tmp;
    		r = r.next;
    	}
    	if (carry == 1) {
    		tmp = new ListNode(1);
    		r.next = tmp;
    		r = r.next;
    	}
    	r.next = null;
    	return head.next;
    }

Log in to reply
 

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