Home > Programación, Python > Add Two Numbers(Linked List) – LeetCode #Python #py

Add Two Numbers(Linked List) – LeetCode #Python #py


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

class Solution(object):
    def addTwoNumbers(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        head = res = ListNode(-1)
        carry = 0
        while l1 or l2 or carry :
            sum = carry
            if l1 :
                sum += l1.val
                l1 = l1.next
            if l2 :
                sum += l2.val
                l2 = l2.next
            if sum > 9 :
                sum -= 10
                carry = 1
            else:
                carry = 0
            res.next = ListNode(sum)
            res = res.next
        return head.next

Here is the page of the problem

Advertisements
Categories: Programación, Python
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: