【链表】- 两数相加

1. 对应力扣题目连接

2. 实现案例代码

java 复制代码
public class AddingTwoNumbers {
    public static void main(String[] args) {

        // 示例用例 1
        ListNode l1 = new ListNode(2);
        l1.next = new ListNode(4);
        l1.next.next = new ListNode(5);

        ListNode l2 = new ListNode(5);
        l2.next = new ListNode(6);
        l2.next.next = new ListNode(4);

        ListNode s = addTwoNumbersNew(l1, l2);
        soutListNode(s);

    }

    public static ListNode addTwoNumbersNew(ListNode l1, ListNode l2) {
        ListNode dummy = new ListNode(0);
        ListNode current = 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;
            }

            carry = sum / 10;
            current.next = new ListNode(sum % 10);
            current = current.next;
        }

        return dummy.next;
    }
    
    public static void soutListNode(ListNode l1) {
        if (l1 == null) {
            return;
        }
        System.out.println(l1.val);
        soutListNode(l1.next);
    }
}

/**
 * 节点类
 */
class ListNode {
    int val;
    ListNode next;

    ListNode() {
    }

    ListNode(int val) {
        this.val = val;
    }

    ListNode(int val, ListNode next) {
        this.val = val;
        this.next = next;
    }
}
相关推荐
旷世奇才李先生2 分钟前
Tomcat 安装使用教程
java·tomcat
勤奋的知更鸟16 分钟前
Java 编程之策略模式详解
java·设计模式·策略模式
qq_49244844617 分钟前
Java 访问HTTP,信任所有证书,解决SSL报错问题
java·http·ssl
爱上语文20 分钟前
Redis基础(4):Set类型和SortedSet类型
java·数据库·redis·后端
冰糖猕猴桃21 分钟前
【Python】进阶 - 数据结构与算法
开发语言·数据结构·python·算法·时间复杂度、空间复杂度·树、二叉树·堆、图
lifallen35 分钟前
Paimon vs. HBase:全链路开销对比
java·大数据·数据结构·数据库·算法·flink·hbase
深栈解码1 小时前
JMM深度解析(三) volatile实现机制详解
java·后端
liujing102329291 小时前
Day04_刷题niuke20250703
java·开发语言·算法
Brookty1 小时前
【MySQL】JDBC编程
java·数据库·后端·学习·mysql·jdbc
能工智人小辰2 小时前
二刷 苍穹外卖day10(含bug修改)
java·开发语言