21 5 月 2020

leetcode第二题解法1

题目:https://leetcode.com/problems/add-two-numbers/

两个单链表相加,输出一个单链表

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def backNode(self,node:ListNode)->int:
        back =0
        if node is None:
            return back
        cur = node
        cnt=-1
        while cur is not None:
            cnt+=1
            back+=cur.val*(10**cnt)
            cur = cur.next
        return back
    
    def genNode(self,l1:list)->ListNode:
        
        head = ListNode(l1[0])
        p=head
        
        for i in range(1,len(l1)):
            
            p.next=ListNode(l1[i])
            p=p.next
        return head
            
            
    
    def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
        print (self.backNode(l1))
        print (self.backNode(l2))
        sum=self.backNode(l1)+self.backNode(l2)
        list1=[int(x) for x in str(sum)]
        print (list1[::-1])
        list2=list1[::-1]
        
        
        return self.genNode(list2)