『LeetCode』2. 两数相加 Add Two Numbers

发布时间 2023-12-21 23:07:27作者: 北岛孤影

『1』迭代法

class Solution {
    // Iteration
    // N is the size of l1, M is the size of l2
    // Time Complexity: O(max(M, N))
    // Space Complexity: O(max(M, N)) if dummy is counted else O(1)
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        int next1 = 0;
        int total = 0;
        ListNode dummy = new ListNode(); // 虚拟头节点
        ListNode cur = dummy;
        while (l1 != null && l2 != null) {
            total = l1.val + l2.val + next1;
            cur.next = new ListNode(total % 10);
            next1 = total / 10;
            l1 = l1.next;
            l2 = l2.next;
            cur = cur.next;
        }

        while (l1 != null) {
            total = l1.val + next1;
            cur.next = new ListNode(total % 10);
            next1 = total / 10;
            l1 = l1.next;
            cur = cur.next;
        }

        while (l2 != null) {
            total = l2.val + next1;
            cur.next = new ListNode(total % 10);
            next1 = total / 10;
            l2 = l2.next;
            cur = cur.next;
        }

        // 处理最后的进位
        if (next1 != 0) {
            cur.next = new ListNode(next1);
        }
        
        return dummy.next;
    }
}

扩展:哨兵节点通常被称为"哑结点"或"虚拟节点"。它们的作用是充当链表中的一个假头,其目的是简化链表操作的边界条件处理。它们通常用于链表的插入、删除和遍历操作中,可以帮助简化代码逻辑,避免对空链表或头结点进行特殊处理。在一些算法和数据结构中,哨兵节点能够简化代码的实现,提高程序的健壮性和可读性。

『2』递归法

class Solution {
    // Recursion
    // N is the size of l1, M is the size of l2
    // Time Complexity: O(max(M, N))
    // Space Complexity: O(max(M, N)) if dummy is counted else O(1)
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        int total = l1.val + l2.val;
        int next1 = total / 10;
        ListNode res = new ListNode(total % 10);
        if (l1.next != null || l2.next != null || next1 != 0) {
            l1 = l1.next != null ? l1.next : new ListNode(0);
            l2 = l2.next != null ? l2.next : new ListNode(0);
            l1.val += next1;
            res.next = addTwoNumbers(l1, l2);
        }
        return res;
    }
}