https://leetcode-cn.com/problems/add-two-numbers/solution/liang-shu-xiang-jia-by-leetcode-solution/

    • 总思路: 同时遍历两个链表,对应数字相加, 然后需要把头节点抓住,最后返回
    • 细节:

      • 用一个变量carry来表示进位,若为1表示有进位,若为0无进位,

        在相加的时候把carry一起加进去,
        sum % 10 就是新节点的值
        sum / 10 就是下一次的carry值

      • 到最后的时候可能会有进位,别忘了检查

        1. public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        2. if (l1 == null) return l2;
        3. if (l2 == null) return l1;
        4. ListNode head = new ListNode(0);
        5. ListNode last = head;
        6. int carry = 0;
        7. while (l1 != null || l2 != null) {
        8. int v1 = 0;
        9. if (l1 != null) {
        10. v1 = l1.val;
        11. l1 = l1.next;
        12. }
        13. int v2 = 0;
        14. if (l2 != null) {
        15. v2 = l2.val;
        16. l2 = l2.next;
        17. }
        18. int sum = v1 + v2 + carry;
        19. carry = sum / 10;
        20. last.next = new ListNode(sum % 10);
        21. last = last.next;
        22. }
        23. if (carry > 0) {
        24. last.next = new ListNode(carry);
        25. }
        26. return head.next;
        27. }