Python:2. 两数相加——力扣

题目:
给你两个 非空 的链表,表示两个非负的整数。它们每位数字都是按照 逆序 的方式存储的,并且每个节点只能存储 一位 数字。

请你将两个数相加,并以相同形式返回一个表示和的链表。

你可以假设除了数字 0 之外,这两个数都不会以 0 开头。

https://leetcode-cn.com/problems/add-two-numbers

解题思路:

  1. l1,l2 (type:ListNode) 转换成 l1,l2 (type:list)格式
  2. l1,l2 按题目要求的方式相加得到 r
  3. r 转换成 list 格式并 reverse 得到 r_list
  4. r_list 转换成ListNode格式
# Definition for singly-linked list.
class ListNode(object):
     def __init__(self, val=0, next=None):
         self.val = val
         self.next = next
         
def link_to_list(listnode):
    res = []
    head = listnode
    temp = head
    while temp != None:
        res.append(temp.val)
        temp = temp.next
    return res

def list2link(list_):
    head = ListNode(list_[0])
    p = head
    for i in range(1, len(list_)):
        p.next = ListNode(list_[i])
        p = p.next
    return head

class Solution(object):
    def addTwoNumbers(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        l1 = link_to_list(l1)
        l2 = link_to_list(l2)
        n1 = len(l1)
        l1.reverse()
        num1 = 0
        for i in range(n1):
            temp1 = l1[i] * pow(10, n1 - 1 - i)
            num1 = num1 + temp1

        n2 = len(l2)
        l2.reverse()
        num2 = 0
        for i in range(n2):
            temp2 = l2[i] * pow(10, n2 - 1 - i)
            num2 = num2 + temp2

        r = num1 + num2
        r_list = [int(item) for item in str(r)]
        r_list.reverse()
        r_link = list2link(r_list)
        
        return r_link

PS:这个方法不是效率最高的方法,只是比较适合我这种初学者。

关于ListNode的讲解见:

http://codingdict.com/article/4838
https://blog.csdn.net/weixin_42322013/article/details/101001438
https://blog.csdn.net/sinat_32512123/article/details/100564871

其他的解决方法见:

https://blog.csdn.net/zhangyu4863/article/details/80669819

你可能感兴趣的:(力扣题库练习,leetcode)