Skip to content

Instantly share code, notes, and snippets.

@Axighi
Last active December 23, 2016 09:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Axighi/a32e6708a746a1bb5837cc4aff5f5ed1 to your computer and use it in GitHub Desktop.
Save Axighi/a32e6708a746a1bb5837cc4aff5f5ed1 to your computer and use it in GitHub Desktop.
# 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
"""
ret = ListNode(0)
is_initial = True
while l1.next or l2.next:
if l1.next and not l2.next:
ret.val = ret.val + l1.next.val
ret.next = l1.next
if is_initial:
_ret = ret
is_initial = False
break
elif not l1.next and l2.next:
ret.val = ret.val + l2.next.val
ret.next = l2.next
if is_initial:
_ret = ret
is_initial = False
break
else:
sum = l1.val + l2.val
if sum < 10:
ret.val = ret.val + sum
ret.next = ListNode(0)
else:
ret.val = ret.val + sum - 10
ret.next = ListNode(1)
ret = ret.next
l1 = l1.next
l2 = l2.next
if is_initial:
_ret = ret
is_initial = False
return _ret
a1 = ListNode(5)
a2 = ListNode(8)
a3 = ListNode(2)
a4 = ListNode(9)
a1.next = a2
a2.next = a3
a3.next = a4
b1 = ListNode(5)
b2 = ListNode(8)
b3 = ListNode(2)
b1.next = b2
b2.next = b3
s = Solution()
print(s.addTwoNumbers(a1, b1))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment