LeetCode 2. Add Two Numbers - 链表(Linked List)系列题1

该博客介绍了如何用Python解决LeetCode中的2. Add Two Numbers问题,即用两个非空链表表示的逆序存储的非负整数相加。通过模拟手动计算过程,博主讲解了如何逐位相加并处理进位,同时提供了详细的解题思路和注意事项,包括如何处理链表的头部节点和结束条件。

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

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 contains a single digit. Add the two numbers and return the sum as a linked list.

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

Example 1:

Input: l1 = [2,4,3], l2 = [5,6,4]
Output: [7,0,8]
Explanation: 342 + 465 = 807.

Example 2:

Input: l1 = [0], l2 = [0]
Output: [0]

Example 3:

Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
Output: [8,9,9,9,0,0,0,1]

Constraints:

  • The number of nodes in each linked list is in the range [1, 100].
  • 0 <= Node.val <= 9
  • It is guaranteed that the list represents a number that does not have leading zeros.

题目大意:用两个非空链表来表示两个非负整数,链表的一个节点表示数字的其中一位,数字在链表中是以反顺序存储的,即最低位在前最高位在后。要求相加两个数把和存到一个新链表中。

解题思路:链表题的解法比较单一就是指针的各种操作。这题的两个数相加其实跟我们平时在草稿纸上手算相加两个数是一样的,就是个位与个位相加,大于10就进一位,然后十位与十位相加再与来自个位的进位相加,以此类推直到最高位。由于这题规定的数字最低位在链表的最前面,操作起来就很简单,用两个指针指向两个链表头,相当于两个数的个位是对齐的,用一个循环,两个指针同步向后,逐位相加,相加时要考虑是否有来自低位的进位。要是有一个链表结束而另一链表还没结束,循环继续但只考虑跟进位相加。最后循环结束时判断一下进位值,如果为1,则结果的最高位要增加一个节点。

注:在做链表题时,有一个小技巧会经常用到,就是创建一个新节点指向链表的头节点,这样链表的头节点就相当于一个普通节点而不需要特殊处理。

# 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]:
        preHead = ListNode()
        
        cur = preHead
        carry = 0
        while l1 or l2:
            sum = carry
            if l1:
                sum += l1.val
                l1 = l1.next
            if l2:
                sum += l2.val
                l2 = l2.next
            
            cur.next = ListNode(sum % 10)
            carry = sum // 10
            cur = cur.next
        
        if carry == 1:
            cur.next = ListNode(1)
        
        return preHead.next

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值