【链表】- 两数相加

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;
    }
}
相关推荐
花开富贵ii1 小时前
代码随想录算法训练营四十三天|图论part01
java·数据结构·算法·深度优先·图论
布朗克1682 小时前
Java 10 新特性及具体应用
java·开发语言·新特性·java10
code小毛孩2 小时前
leetcode hot100数组:缺失的第一个正数
数据结构·算法·leetcode
ZZHow10245 小时前
JavaWeb开发_Day05
java·笔记·web
CHEN5_025 小时前
【Java虚拟机】垃圾回收机制
java·开发语言·jvm
Warren985 小时前
Lua 脚本在 Redis 中的应用
java·前端·网络·vue.js·redis·junit·lua
艾伦~耶格尔9 小时前
【数据结构进阶】
java·开发语言·数据结构·学习·面试
爪洼传承人9 小时前
18- 网络编程
java·网络编程
smileNicky9 小时前
SpringBoot系列之从繁琐配置到一键启动之旅
java·spring boot·后端
祈祷苍天赐我java之术10 小时前
Java 迭代器(Iterator)详解
java·开发语言