编辑代码

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */

public class Java {

  private static class ListNode {
    int val;
    ListNode next;
    public ListNode() {}
    public ListNode(int val) { this.val = val; }
    public ListNode(int val, ListNode next) { this.val = val; this.next = next; }

    @Override
    public String toString() {
      StringBuilder string = new StringBuilder();
      ListNode temp = this;
      string.append("[" + temp.val);
      while(temp.next != null) {
        temp = temp.next;
        string.append(", " + temp.val);
      }
      string.append("]");
      return string.toString();
    }
  }

  // 2 ms
  public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
    if (l1 == null) { return l2; }
    if (l2 == null) { return l1; }
    ListNode ln = new ListNode(0, null);
    ListNode p = ln;
    int carry = 0;
    while(l1 != null || l2 != null) {
      int num1 = (l1 == null) ? 0 : l1.val;
      int num2 = (l2 == null) ? 0 : l2.val;
      int sum = num1 + num2 + carry;
      carry = sum / 10;
      p.next = new ListNode(sum % 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 ln.next;
  }

  // 以下是测试代码 -----------------------

  public static ListNode createNode(int list[]) {
    if (list == null) return null;
    if (!(list.getClass().isArray())) {
      throw new NullPointerException("不是数组");
    }

    ListNode nextNode = null;
    ListNode preNode = null;
    int length = list.length - 1;
    for (int i = 0; i <= length; i++) {
      if (i == 0) {
        nextNode = new ListNode(list[length]);
        preNode = nextNode;
      } else {
        preNode = new ListNode(list[length - i], nextNode);
        nextNode = preNode;
      }
    }

    return preNode;
  }

  public static void main(String[] args) {
    int testList[][] = {
      {2,4,3},
      {5,6,4}

      // {9,9,9,9,9,9,9},
      // {9,9,9,9}

      // {0},
      // {0}
    };

    int list1[] = testList[0];
    int list2[] = testList[1];
    // int list1Len = testList[0].length;
    // int list2Len = testList[1].length;
    // System.out.println(list1 + " " + list1Len);
    // System.out.println(list2 + " " + list2Len);

    ListNode l1 = createNode(list1);
    ListNode l2 = createNode(list2);
    System.out.println("源数据");
    System.out.println(l1);
    System.out.println(l2);

    System.out.println("结果");
    ListNode result = addTwoNumbers(l1, l2);
    System.out.println(result);
  }
}