[leetcode] 445. Add Two Numbers II @ python

本文介绍了一种解决链表加法问题的方法,通过首先将两个非空链表转换为整数,进行加法运算后再将结果转换回链表形式。文章详细解释了实现步骤,包括如何避免反转输入链表,以及如何构建新的链表来存储结果。

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

原题

You are given two non-empty linked lists representing two non-negative integers. 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

解法

先定义getNum函数将链表转化为整数, 然后两整数相加, 将得到的结果转化为数字列表, 构建dummy节点, 遍历列表, 每次从列表中提取第一个数字, 作为节点的下一个节点, 最后返回dummy.next
Time: O(L1) + O(L2) + O(L1+L2), L1为l1的长度, L1+L2为l1加l2的长度
Space: O(1)

代码

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

class Solution:
    def addTwoNumbers(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        res = self.getNum(l1) + self.getNum(l2)
        res = [int(char) for char in list(str(res))]
        # convert res to linked list
        dummy = p = ListNode(0)
        while res:
            p.next = ListNode(res.pop(0))            
            p = p.next            
        return dummy.next
    
    def getNum(self, node):
        l = []
        while node:
            l.append(str(node.val))
            node = node.next
        return int(''.join(l))
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值