【链表】- 两数相加

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;
    }
}
相关推荐
今后1231 天前
【数据结构】二叉树的概念
数据结构·二叉树
计算机毕业设计木哥1 天前
计算机毕设选题推荐:基于Java+SpringBoot物品租赁管理系统【源码+文档+调试】
java·vue.js·spring boot·mysql·spark·毕业设计·课程设计
青衫客361 天前
Spring异步编程- 浅谈 Reactor 核心操作符
java·spring·响应式编程
Seven971 天前
剑指offer-30、连续⼦数组的最⼤和
java
BenChuat1 天前
Java常见排序算法实现
java·算法·排序算法
熙客1 天前
SpringCloud概述
java·spring cloud·微服务
a587691 天前
Elasticsearch核心概念与Java实战:从入门到精通
java·es
Brookty1 天前
【JavaEE】线程安全-内存可见性、指令全排序
java·开发语言·后端·java-ee·线程安全·内存可见性·指令重排序
tellmewhoisi1 天前
前置配置1:nacos 基本配置(注册与发现)
java
会开花的二叉树1 天前
继承与组合:C++面向对象的核心
java·开发语言·c++