Add Two Numbers

这题不难 直接上递归就行
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        // Start typing your Java solution below
        // DO NOT write main() function
        if (l1 != null && l2 != null){
            int val = l1.val + l2.val;
            ListNode l3;
            if (val < 10){
                l3 = new ListNode(val);
                l3.next = addTwoNumbers(l1.next, l2.next);
            }
            else {
                l3 = new ListNode(val - 10);
                l3.next = addTwoNumbers(l1.next, l2.next);
                ListNode l4 = new ListNode(1);
                l3.next = addTwoNumbers(l3.next, l4);
            }
            return l3;
        }else{
            if (l1 != null){
                return l1;
            } else if (l2 != null)
                    return l2;
                else 
                    return null;
        }
    }
}

你可能感兴趣的:(number)