Guest User

Untitled

a guest
Nov 21st, 2017
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.23 KB | None | 0 0
  1. # Definition for singly-linked list.
  2. # class ListNode(object):
  3. # def __init__(self, x):
  4. # self.val = x
  5. # self.next = None
  6.  
  7. class Solution(object):
  8. def addTwoNumbers(self, l1, l2):
  9. """
  10. :type l1: ListNode
  11. :type l2: ListNode
  12. :rtype: ListNode
  13. """
  14. l1 = self.reverseList(l1)
  15. l2 = self.reverseList(l2)
  16. head1 = l1
  17. head2 = l2
  18. count = 0
  19. while head1 and head2:
  20. sum = head1.val + head2.val + count
  21. head1.val = sum % 10
  22. count = sum / 10
  23. if count and not head1.next and not head2.next:
  24. head1.next = ListNode(count)
  25. count = 0
  26. if not head1.next and head2.next: head1.next = ListNode(0)
  27. if not head2.next and head1.next: head2.next = ListNode(0)
  28. head1 = head1.next
  29. head2 = head2.next
  30. return self.reverseList(l1)
  31. def reverseList(self, head):
  32. """
  33. :type head: ListNode
  34. :rtype: ListNode
  35. """
  36. if not head: return head
  37. if not head.next: return head
  38. reversedList = self.reverseList(head.next)
  39. head.next.next = head
  40. head.next = None
  41. return reversedList
Add Comment
Please, Sign In to add comment