【LeetCode Hot 100】2. 两数相加

louistang0524 / 2024-09-17 / 原文

题目描述

题目手下留情给出的链表使用逆序表示加数,因此我们可以从链表头开始逐位相加。我总结了一下有几点需要注意:

  1. 显然加法需要注意进位,此外需要格外注意的是最后一位没有加数时,还需要考虑进位是否被置位,如果最后的进位为1,我们还需要创建一个新的节点。
  2. 当其中一个链表走完,需要注意要把另一个链表余下的部分继续走完。
// C++
class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        ListNode* head = nullptr;
        ListNode* tail = nullptr;
        int c = 0;
        while (l1 || l2) {
            int val1 = l1 ? l1->val : 0;
            int val2 = l2 ? l2->val : 0;
            int s = c + val1 + val2;
            c = s / 10;
            if (head) {
                tail->next = new ListNode(s % 10);
                tail = tail->next;
            } else {
                head = tail = new ListNode(s % 10);
            }
            if (l1) {
                l1 = l1->next;
            }
            if (l2) {
                l2 = l2->next;
            }
        }
        if (c) {
            tail->next = new ListNode(c);
        }
        return head;
    }
};

// Java
class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode head = null;
        ListNode tail = null;
        int c = 0;
        while (l1 != null || l2 != null) {
            int val1 = (l1 == null ? 0 : l1.val);
            int val2 = (l2 == null ? 0 : l2.val);
            int s = val1 + val2 + c;
            c = s / 10;
            if (head == null) {
                head = tail = new ListNode(s % 10);
            } else {
                tail.next = new ListNode(s % 10);
                tail = tail.next;
            }
            if (l1 != null) {
                l1 = l1.next;
            }
            if (l2 != null) {
                l2 = l2.next;
            }
        }
        if (c != 0) {
            tail.next = new ListNode(c);
        }
        return head;
    }
}