Add Two Numbers --- LeetCode

Problem:

You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order 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.

 

Example:

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.

 

 

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
       //没什么,分情况而已
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode ln=new ListNode(0);
        if(l1==null&&l2==null) return null;
        else if(l1==null) return l2;
        else if(l2==null) return l1;
        else if(l1.next==null&&l2.next==null){
            ln.val=l1.val+l2.val;
            if(ln.val>9){
                int temp=ln.val%10;
                ln.next=new ListNode(ln.val/10);
                ln.val=temp;
            }
            return ln;
        }
        else if(l1.next==null){
            ln.val=l1.val+l2.val;
            l2.val=0;
            if(ln.val>9){
                int temp=ln.val%10;
                ln.next=new ListNode(ln.val/10);
                ln.val=temp;
            }
            ln.next=addTwoNumbers(ln.next,l2.next);
            return ln;
        }
        else if(l2.next==null){
            ln.val=l1.val+l2.val;
            l1.val=0;
            if(ln.val>9){
                int temp=ln.val%10;
                ln.next=new ListNode(ln.val/10);
                ln.val=temp;
            }
            ln.next=addTwoNumbers(ln.next,l1.next);
            return ln;
        }
        else{
            ln.val=l1.val+l2.val;
            l1.val=0;
            l2.val=0;
            if(ln.val>9){
                int temp=ln.val%10;
                l1.next.val+=ln.val/10;
                ln.val=temp;
            }
            ln.next=addTwoNumbers(l1.next,l2.next);
            return ln;
        }
    }
}
这个问题是 LeetCode 中的经典题目 **“两数相加”(Add Two Numbers)**,它要求我们实现两个链表形式表示的非负整数相加,类似于竖式加法。 --- ### 🔍 题目描述(中文简述): 给你两个 **非空** 的链表,表示两个非负整数。它们的每个节点都存储一个数字,其中 **数字逆序存储**(个位在前),请你将这两个数相加,并以相同形式返回一个新的链表。 --- ### ✅ 示例: 输入: ``` l1 = 2 -> 4 -> 3 (表示数字 342) l2 = 5 -> 6 -> 4 (表示数字 465) ``` 输出: ``` 7 -> 0 -> 8 (表示数字 807) ``` --- ### 🧠 解题思路: 1. 使用一个虚拟头结点(dummy head)来方便构建结果链表。 2. 使用一个变量 `carry` 表示进位。 3. 遍历两个链表,直到两个链表都为空。 4. 每次取出两个链表当前节点的值(如果存在),加上进位 `carry`,计算当前位的值和新的进位。 5. 创建新节点加入结果链表中。 6. 最后如果还有进位,要额外添加一个节点。 --- ### 🧾 Python 实现代码如下: ```python from typing import Optional # Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]: dummy = ListNode() # 虚拟头结点 current = dummy # 当前指针用于构建链表 carry = 0 # 进位值 # 同时遍历两个链表 while l1 or l2: x = l1.val if l1 else 0 y = l2.val if l2 else 0 total = x + y + carry carry = total // 10 digit = total % 10 current.next = ListNode(digit) current = current.next if l1: l1 = l1.next if l2: l2 = l2.next # 处理最后的进位 if carry > 0: current.next = ListNode(carry) return dummy.next ``` --- ### 📌 注意事项: - 两个链表可能长度不同,所以需要判断是否为 `None`。 - 最后可能还有进位(如 `999 + 1`)。 - 使用虚拟头结点可以简化链表构建过程。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值