Leetcode 2 Add Two Numbers

# 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
        """
        if not l1:
            return l2
        if not l2:
            return l1
        x1=x2=''
        curr_node=l1
        while curr_node:
            x1+=str(curr_node.val)
            curr_node=curr_node.next
        curr_node=l2
        while curr_node:
            x2+=str(curr_node.val)
            curr_node=curr_node.next
        y=int(x1[::-1])+int(x2[::-1])
        y=str(y)[::-1]
        head=new_node=ListNode(y[0])
        for i in range(1,len(y)):
            new_node.next=ListNode(y[i])
            new_node=new_node.next
        return head

猜你喜欢

转载自blog.csdn.net/absent1353/article/details/80273006