【链表】- 两数相加

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;
    }
}
相关推荐
爬山算法7 小时前
Hibernate(89)如何在压力测试中使用Hibernate?
java·压力测试·hibernate
驭渊的小故事7 小时前
简单模板笔记
数据结构·笔记·算法
消失的旧时光-19437 小时前
第十四课:Redis 在后端到底扮演什么角色?——缓存模型全景图
java·redis·缓存
BD_Marathon7 小时前
设计模式——依赖倒转原则
java·开发语言·设计模式
VT.馒头7 小时前
【力扣】2727. 判断对象是否为空
javascript·数据结构·算法·leetcode·职场和发展
BD_Marathon7 小时前
设计模式——里氏替换原则
java·设计模式·里氏替换原则
Coder_Boy_7 小时前
Deeplearning4j+ Spring Boot 电商用户复购预测案例中相关概念
java·人工智能·spring boot·后端·spring
css趣多多7 小时前
add组件增删改的表单处理
java·服务器·前端
雨中飘荡的记忆7 小时前
Spring Batch实战
java·spring
Java后端的Ai之路8 小时前
【Spring全家桶】-一文弄懂Spring Cloud Gateway
java·后端·spring cloud·gateway