☆☆☆解法:考虑进位值 以及 较短的链表补0
class Solution { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { ListNode dummyHead = new ListNode(0); ListNode cur = dummyHead; int carry = 0; // 上一位的进位值 while (l1 != null || l2 != null) { // 如果一个链表较短则在前面补0 int val1 = l1 == null ? 0 : l1.val; int val2 = l2 == null ? 0 : l2.val; int temp = val1 + val2 + carry; carry = temp / 10; cur.next = new ListNode(temp % 10); cur = cur.next; if (l1 != null) l1 = l1.next; if (l2 != null) l2 = l2.next; } // 如果两个链表全部遍历完毕后,进位值为 1,则在新链表最前方添加节点 1 if (carry > 0) { // carry == 1 cur.next = new ListNode(carry); } return dummyHead.next; } }