Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # 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
- """
- l1 = self.reverseList(l1)
- l2 = self.reverseList(l2)
- head1 = l1
- head2 = l2
- count = 0
- while head1 and head2:
- sum = head1.val + head2.val + count
- head1.val = sum % 10
- count = sum / 10
- if count and not head1.next and not head2.next:
- head1.next = ListNode(count)
- count = 0
- if not head1.next and head2.next: head1.next = ListNode(0)
- if not head2.next and head1.next: head2.next = ListNode(0)
- head1 = head1.next
- head2 = head2.next
- return self.reverseList(l1)
- def reverseList(self, head):
- """
- :type head: ListNode
- :rtype: ListNode
- """
- if not head: return head
- if not head.next: return head
- reversedList = self.reverseList(head.next)
- head.next.next = head
- head.next = None
- return reversedList
Add Comment
Please, Sign In to add comment