LeetCode 445. Add Two Numbers II

本文介绍了一种解决LeetCode上两数相加问题的方法,该问题要求将两个非负整数以链表形式相加并返回结果链表。文章提供了一个不修改输入链表的解决方案,通过计算链表长度,逐位相加并处理进位。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原题网址:https://leetcode.com/problems/add-two-numbers-ii/

You are given two linked lists representing two non-negative numbers. The most significant digit comes first and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Follow up:
What if you cannot modify the input lists? In other words, reversing the lists is not allowed.

Example:

Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 8 -> 0 -> 7

方法:如果不能反转原链表的话,可以反转结果链表。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    private int length(ListNode node) {
        if (node == null) return 0;
        return 1 + length(node.next);
    }
    private ListNode reverse(ListNode node) {
        if (node == null) return null;
        if (node.next == null) return node;
        ListNode prev = node;
        ListNode curr = node.next;
        prev.next = null;
        while (curr != null) {
            ListNode next = curr.next;
            curr.next = prev;
            prev = curr;
            curr = next;
        }
        return prev;
    }
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        int len1 = length(l1);
        int len2 = length(l2);
        int len = Math.max(len1, len2);
        ListNode start = new ListNode(0);
        ListNode node = start;
        for(int i = 0; i < len; i++) {
            node.next = new ListNode(0);
            node = node.next;
            if (i + len1 >= len) {
                node.val += l1.val;
                l1 = l1.next;
            }
            if (i + len2 >= len) {
                node.val += l2.val;
                l2 = l2.next;
            }
        }
        start.next = reverse(start.next);
        node = start;
        int carry = 0;
        while (node.next != null) {
            node = node.next;
            node.val += carry;
            carry = node.val / 10;
            node.val %= 10;
        }
        if (carry != 0) {
            node.next = new ListNode(carry);
        }
        start.next = reverse(start.next);
        return start.next;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值