LeetCode 2 两数相加 - 链表

LeetCode 2 两数相加,本质就是小学的加法竖式,用链表模拟而已。


🟡 两数相加

两个逆序链表各存一个数(头是低位),加起来返回新链表。2→4→3 + 5→6→4 = 7→0→8


第一次看到这题我以为要把链表转成 int 再加------脑子短路了,链表可能是几百位的数,int 早爆了。

其实只要你手算一遍 342 + 465,你就是在做这题:从最低位开始,逐位相加,满 10 进 1。链表本来就是逆序的,头刚好是最低位,天然适合从头开始加。每一位的处理就三件事:取两个加数(没有就补 0)、加上进位、算出新的进位。

java 复制代码
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
    ListNode dummy = new ListNode(0);
    ListNode cur = dummy;
    int carry = 0;

    while (l1 != null || l2 != null || carry != 0) {
        int sum = carry;
        if (l1 != null) { sum += l1.val; l1 = l1.next; }
        if (l2 != null) { sum += l2.val; l2 = l2.next; }
        cur.next = new ListNode(sum % 10);
        carry = sum / 10;
        cur = cur.next;
    }
    return dummy.next;
}

为什么循环条件里要写 || carry != 0[5] + [5] = 10,最后 l1 和 l2 都走完了但进位是 1,不处理的话返回 [0] 漏了最高位的 1。

dummy 头节点是个老技巧了------不用判断第一个节点是不是 null,直接 cur.next = new ListNode(...),最后返回 dummy.next


这道题你踩过什么坑?或者你用别的语言实现过吗?评论区聊聊,回头复习也方便翻。

相关推荐
ZC跨境爬虫1 小时前
LeetCode 219. 存在重复元素 II(滑动窗口 + 哈希表详解)
算法·leetcode·散列表
Navigator_Z2 小时前
LeetCode //C - 1220. Count Vowels Permutation
c语言·算法·leetcode
feilieren2 小时前
leetcode - 389. 找不同
算法·leetcode
evans在进步3 小时前
LeetCode 238 除自身以外数组的乘积:前缀积与后缀积详解
算法·leetcode·职场和发展
Thomas214313 小时前
Java scala 数组 链表
java·链表·scala
刃神太酷啦13 小时前
Linux 系统 MySQL 完整安装配置教程:从卸载 MariaDB 到优化 my.cnf----《Hello MySQL!》(1)
android·linux·c语言·c++·mysql·leetcode·mariadb
萌动的小火苗14 小时前
数据结构面试题【无答案】
c语言·开发语言·数据结构·链表
wenyq718 小时前
LeetCode 2904. Shortest and Lexicographically Smallest Beautiful String
算法·leetcode
_Narcissus_20 小时前
分治&递归
数据结构·c++·笔记·算法·leetcode·递归·分治