【链表】- 两数相加

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;
    }
}
相关推荐
程序员小假1 分钟前
我们来说一说 Redisson 的原理
java·后端
chirrupy_hamal2 分钟前
网络编程 - TCP 篇
java
notillusion25 分钟前
KWW#71843
java·php·程序优化
liu****1 小时前
10.queue的模拟实现
开发语言·数据结构·c++·算法
Deschen1 小时前
设计模式-抽象工厂模式
java·设计模式·抽象工厂模式
齐木卡卡西在敲代码1 小时前
java流式编程学习
java
ʚ希希ɞ ྀ1 小时前
SpringBoot的学习
java·spring boot·学习
notillusion1 小时前
TRX#22597
java·php·程序优化
shinelord明1 小时前
【大数据技术实战】Kafka 认证机制全解析
大数据·数据结构·分布式·架构·kafka
让我们一起加油好吗1 小时前
【基础算法】01BFS
数据结构·c++·算法·bfs·01bfs