Leetcode #2 Add Two Numbers(Python)超详细

这篇博客详细介绍了LeetCode第2题——如何将两个反向存储数字的链表相加。文章通过实例展示了如何处理链表和进位问题,最终给出Python的AC代码实现。

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

Leetcode #2 Add Two Numbers

题目描述

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.

题解:

知识点:

1. 链表
2. 进位

1.链表

以 Leetcode 所给定义为例

 Definition for singly-linked list.
 class ListNode:
     def __init__(self, x):
         self.val = x
         self.next = None

__init__介绍
python class 里的函数:代表定义class时创建的变量

self: class 本身
x: 在创建时需要输入的变量
这个class定义了两个变量: val 和 next
next:指向下一个节点
val:本节点的值

example:
N = ListNode(3)
N 为新节点, x = 3 并赋值给val
现在 N.val = 3
N.next = None

2.进位

定义 carry为进位项

AC代码

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
        r = ListNode(0) #创建储存答案的链表的始节点
        nowNode = r #定义当前储存答案的节点
        carry = 0 # 上一次残留的进位
        while l1 or l2:#两个链表至少一个不是空
            x = l1.val if l1 else 0 #不空就赋值,否则为0
            y = l2.val if l2 else 0
            result = x + y + carry # 相加
            carry = result // 10 #除以10的商->进位
            nowNode.next = ListNode(result%10) # 下一个节点的值是和的个位数,使当前节点指向下一节点
            nowNode = nowNode.next #到下一节点
            if l1: l1 = l1.next #不为空则后移到下一节点
            if l2: l2 = l2.next
         #循环后多进位 再创建一个节点       
        if carry ==1:
            nowNode.next = ListNode(1)
            
        return r.next
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值